Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.google.cloud.vision.spi.v1.ImageAnnotatorClient;
- import com.google.cloud.vision.v1.*;
- import com.google.protobuf.ByteString;
- import nl.remcobuddelmeijer.config.Config;
- import nl.remcobuddelmeijer.config.Configs;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.locks.ReentrantLock;
- /**
- * Created by Remco on 25-6-2017.
- */
- public class VisionInstance {
- //Client for VisionAPI
- private final ImageAnnotatorClient client = ImageAnnotatorClient.create();
- private final ExecutorService executor = Executors.newWorkStealingPool();
- private final ReentrantLock lock = new ReentrantLock();
- private volatile byte[] content;
- //API Key used for Authentication
- private final String key;
- //Configurations for VisionAPI (Hardcoded)
- @Configs({
- //API Key based annotation
- @Config(key = "key", serializedValue = "AIzaSyAcEdI1whFqiYjlqGhFm8fKybuzNO60XdU")
- })
- /**
- * Constructor for one of the VisionAPI instances running.
- */
- public VisionInstance() throws IOException {
- this.key = "";
- }
- public Future<?> fetch(URL url) throws InterruptedException {
- executor.execute(() -> {
- lock.lock();
- URLConnection connection = new URLConnection(url) {
- @Override
- public void connect() throws IOException {
- OutputStream stream = this.getOutputStream();
- byte[] b = new byte[2048];
- int length;
- while((length = this.getInputStream().read(b)) != -1){
- stream.write(b, 0, length);
- }
- content = b;
- try {
- this.getInputStream().close();
- this.getOutputStream().close();
- }finally{
- lock.unlock();
- }
- }
- };
- });
- while (lock.isLocked()) {
- wait();
- }
- return executor.submit(() -> {
- List<AnnotateImageRequest> requests = new ArrayList<>();
- ByteString imgBytes = ByteString.copyFrom(content);
- Image image = Image.newBuilder().setContent(imgBytes).build();
- Feature feature = Feature.newBuilder().setType(Feature.Type.FACE_DETECTION).build();
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(feature).setImage(image).build();
- requests.add(request);
- BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
- return response.getResponsesList();
- });
- }
- /**
- * VisionAPI client bound to instance.
- * Can only be used by one thread.
- *
- * @return
- */
- public synchronized ImageAnnotatorClient getClient() {
- return client;
- }
- /**
- * Key assigned to identify identity for Google Auth.
- *
- * @return
- */
- public String getKey() {
- return key;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement