use of com.google.cloud.vision.v1p4beta1.Feature in project java-docs-samples by GoogleCloudPlatform.
the class ImageMagick method accept.
// [END functions_imagemagick_setup]
// [START functions_imagemagick_analyze]
@Override
public // Blurs uploaded images that are flagged as Adult or Violence.
void accept(GcsEvent event, Context context) {
// Validate parameters
if (event.getBucket() == null || event.getName() == null) {
logger.severe("Error: Malformed GCS event.");
return;
}
BlobInfo blobInfo = BlobInfo.newBuilder(event.getBucket(), event.getName()).build();
// Construct URI to GCS bucket and file.
String gcsPath = String.format("gs://%s/%s", event.getBucket(), event.getName());
logger.info(String.format("Analyzing %s", event.getName()));
// Construct request.
ImageSource imgSource = ImageSource.newBuilder().setImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feature = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feature).setImage(img).build();
List<AnnotateImageRequest> requests = List.of(request);
// Send request to the Vision API.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
logger.info(String.format("Error: %s", res.getError().getMessage()));
return;
}
// Get Safe Search Annotations
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
if (annotation.getAdultValue() == 5 || annotation.getViolenceValue() == 5) {
logger.info(String.format("Detected %s as inappropriate.", event.getName()));
blur(blobInfo);
} else {
logger.info(String.format("Detected %s as OK.", event.getName()));
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Error with Vision API: " + e.getMessage(), e);
}
}
use of com.google.cloud.vision.v1p4beta1.Feature in project AGREE by loonwerks.
the class AgreeASTBuilder method portToAgreeVar.
private void portToAgreeVar(List<AgreeVar> outputs, List<AgreeVar> inputs, FeatureInstance feature, List<AgreeStatement> assumptions, List<AgreeStatement> guarantees) {
Feature dataFeature = feature.getFeature();
NamedElement dataClass;
if (dataFeature instanceof DataPort) {
DataPort dataPort = (DataPort) dataFeature;
dataClass = dataPort.getDataFeatureClassifier();
} else if (dataFeature instanceof EventDataPort) {
EventDataPort eventDataPort = (EventDataPort) dataFeature;
dataClass = eventDataPort.getDataFeatureClassifier();
} else {
dataClass = null;
}
String name = feature.getName();
boolean isEvent = feature.getCategory() == FeatureCategory.EVENT_DATA_PORT || feature.getCategory() == FeatureCategory.EVENT_PORT;
if (isEvent) {
AgreeVar var = new AgreeVar(name + eventSuffix, NamedType.BOOL, feature.getFeature(), feature.getComponentInstance(), feature);
switch(feature.getDirection()) {
case IN:
inputs.add(var);
break;
case OUT:
outputs.add(var);
break;
default:
throw new AgreeException("Unable to reason about bi-directional event port: " + dataFeature.getQualifiedName());
}
}
if (dataClass == null) {
// we do not reason about this type
return;
}
AgreeTypeSystem.TypeDef td = AgreeTypeSystem.inferFromNamedElement(dataFeature);
Type type = symbolTable.updateLustreTypeMap(td);
if (type == null) {
// we do not reason about this type
return;
}
AgreeVar agreeVar = new AgreeVar(name, type, feature.getFeature(), feature.getComponentInstance(), feature);
switch(feature.getDirection()) {
case IN:
inputs.add(agreeVar);
if (dataClass instanceof DataClassifier) {
List<Expr> constraints = getConstraintsFromTypeDef(name, td);
if (!constraints.isEmpty()) {
assumptions.add(getDataClassifierTypePredicate(feature.getName(), constraints, dataFeature));
}
}
break;
case OUT:
outputs.add(agreeVar);
if (dataClass instanceof DataClassifier) {
List<Expr> constraints = getConstraintsFromTypeDef(name, td);
if (!constraints.isEmpty()) {
guarantees.add(getDataClassifierTypePredicate(feature.getName(), constraints, dataFeature));
}
}
break;
default:
throw new AgreeException("Unable to reason about bi-directional event port: " + dataFeature.getQualifiedName());
}
}
use of com.google.cloud.vision.v1p4beta1.Feature in project AGREE by loonwerks.
the class AgreeValidator method checkNamedElement.
@Check(CheckType.FAST)
public void checkNamedElement(NamedElement namedEl) {
// check for namespace collision in component types of component
// implementations
// and for collisions between subcomponent and feature names
EObject container = namedEl.eContainer();
if (container == null) {
return;
}
if (container instanceof RecordDef || container instanceof NodeDef) {
// TODO: perhaps we can ignore all arguments?
return;
}
while (!(container instanceof AadlPackage || container instanceof ComponentImplementation || container instanceof ComponentType)) {
container = container.eContainer();
}
ComponentImplementation compImpl = null;
ComponentType type = null;
if (container instanceof ComponentImplementation) {
compImpl = (ComponentImplementation) container;
type = compImpl.getType();
checkDupNames(namedEl, type, compImpl);
} else if (container instanceof ComponentType) {
type = (ComponentType) container;
}
if (type != null && (namedEl.getName() != null)) {
for (Feature feat : type.getAllFeatures()) {
if (namedEl.getName().equals(feat.getName())) {
error(feat, "Element of the same name ('" + namedEl.getName() + "') in AGREE Annex in '" + (compImpl == null ? type.getName() : compImpl.getName()) + "'");
error(namedEl, "Feature of the same name ('" + namedEl.getName() + "') in component type");
}
}
}
// check name space collision with enumerated types
}
use of com.google.cloud.vision.v1p4beta1.Feature in project AGREE by loonwerks.
the class AgreeValidator method checkLiftContract.
@Check(CheckType.FAST)
public void checkLiftContract(LiftContractStatement lcst) {
Classifier comp = lcst.getContainingClassifier();
if (comp instanceof ComponentImplementation) {
ComponentType ct = ((ComponentImplementation) comp).getType();
List<AnnexSubclause> agreeAnnexes = AnnexUtil.getAllAnnexSubclauses(ct, AgreePackage.eINSTANCE.getAgreeContractSubclause());
if (agreeAnnexes.size() > 0) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whose type has an AGREE annex.");
}
List<Subcomponent> subcomps = ((ComponentImplementation) comp).getAllSubcomponents();
if (subcomps.size() == 1) {
Subcomponent subcomp = subcomps.get(0);
Classifier subCls = subcomp.getClassifier();
ComponentType subCt = null;
if (subCls instanceof ComponentImplementation) {
subCt = ((ComponentImplementation) subCls).getType();
} else if (subCls instanceof ComponentType) {
subCt = (ComponentType) subCls;
} else {
throw new RuntimeException();
}
{
Set<String> usedParentInPorts = new HashSet<>();
Set<String> usedParentOutPorts = new HashSet<>();
Set<String> usedChildInPorts = new HashSet<>();
Set<String> usedChildOutPorts = new HashSet<>();
EList<Classifier> ctPlusAllExtended = ct.getSelfPlusAllExtended();
EList<Classifier> subCtPlusAllExtended = subCt.getSelfPlusAllExtended();
for (Connection conn : ((ComponentImplementation) comp).getAllConnections()) {
{
NamedElement sourceNe = conn.getSource().getConnectionEnd();
if (subCtPlusAllExtended.contains(sourceNe.getContainingClassifier())) {
if (usedChildOutPorts.contains(sourceNe.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whith more than one connection out of same output " + sourceNe.getQualifiedName() + ".");
}
usedChildOutPorts.add(sourceNe.getName());
}
if (ctPlusAllExtended.contains(sourceNe.getContainingClassifier())) {
if (usedParentInPorts.contains(sourceNe.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whith more than one connection out of same input " + sourceNe.getQualifiedName() + ".");
}
usedParentInPorts.add(sourceNe.getName());
}
}
{
NamedElement destNe = conn.getDestination().getConnectionEnd();
if (subCtPlusAllExtended.contains(destNe.getContainingClassifier())) {
if (usedChildInPorts.contains(destNe.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whith more than one connection into same input " + destNe.getQualifiedName() + ".");
}
usedChildInPorts.add(destNe.getName());
}
if (ctPlusAllExtended.contains(destNe.getContainingClassifier())) {
if (usedParentOutPorts.contains(destNe.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whith more than one connection into same output " + destNe.getQualifiedName() + ".");
}
usedParentOutPorts.add(destNe.getName());
}
}
}
for (Feature feat : comp.getAllFeatures()) {
boolean isIn = false;
if (feat instanceof DataPort) {
isIn = ((DataPort) feat).isIn();
} else if (feat instanceof EventDataPort) {
isIn = ((EventDataPort) feat).isIn();
} else if (feat instanceof EventPort) {
isIn = ((EventPort) feat).isIn();
}
if (isIn) {
if (!usedParentInPorts.contains(feat.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whithout connection from input " + feat.getQualifiedName() + ".");
}
} else {
if (!usedParentOutPorts.contains(feat.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whithout connection to output " + feat.getQualifiedName() + ".");
}
}
}
for (Feature feat : subCt.getAllFeatures()) {
boolean isIn = false;
if (feat instanceof DataPort) {
isIn = ((DataPort) feat).isIn();
} else if (feat instanceof EventDataPort) {
isIn = ((EventDataPort) feat).isIn();
} else if (feat instanceof EventPort) {
isIn = ((EventPort) feat).isIn();
}
if (isIn) {
if (!usedChildInPorts.contains(feat.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whithout connection into " + feat.getQualifiedName() + ".");
}
} else {
if (!usedChildOutPorts.contains(feat.getName())) {
error(lcst, "'lift contract;' statement is not allowed in component implementation whithout connection out of " + feat.getQualifiedName() + ".");
}
}
}
}
} else {
error(lcst, "'lift contract;' statement is not allowed in component implementation whithout exactly one subcomponent.");
}
} else {
error(lcst, "'lift contract;' statement is not allowed in component interface.");
}
}
use of com.google.cloud.vision.v1p4beta1.Feature in project java-vision by googleapis.
the class QuickstartSample method main.
public static void main(String... args) throws Exception {
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {
// The path to the image file to annotate
String fileName = "./resources/wakeupcat.jpg";
// Reads the image file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString imgBytes = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
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);
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
annotation.getAllFields().forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
}
}
}
}
Aggregations