Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate access token in Java for Google AutoML Vision API without gcloud?

I am making an Android App that will utilize the Google AutoML Vision API. I am looking for a way to get a permanent access token or generate them in code so that I do not need to use gcloud everytime I want to use my app. How would I go about doing this?

I have created the AutoML model, set up my service account, and coded my app in Android Studio so that it makes the request to the API using Volley. The problem is, they require you to generate and pass an access token using gcloud. I can generate the token and put it in my code but it only lasts for an hour and then it expires. The REST API requires the access token as shown below.

curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth application-default print-access- 
token)" 

I have looked into different ways around this problem. For example, there are some Google Client Libraries for Java and Google Cloud Applications that show how to add the service account credentials into the code. I am confused how I would add the Json key file into the code when running it from a phone. I have also read that Firebase could be used but I am unfamiliar about what the process for that would be.

Currently, I will open up gcloud on my computer, generate the access token, paste it into my code and run the app as follows with the header and this returns the desired results for up to an hour until the access code expires.

@Override
public Map<String, String> getHeaders() throws AuthFailureError{
    Map<String, String> headers = new HashMap<>();
    headers.put("Authorization", "Bearer " + accesstoken);
    return headers;
 }

I would like this to be a stand alone application that can run on an Android phone. What is the best way to go about doing this?


UPDATE: I was able to add the file into Android Studio and then use some functions to get an access token and it appears to work in the Emulator. I am not sure how secure this method is though because the json file with the key needs to be kept private.

InputStream is = getAssets().open("app.json");
GoogleCredentials credentials = 
GoogleCredentials.fromStream(i).createScoped(Lists.newArrayList(scope));
credentials.refreshIfExpired();
AccessToken accesstoken = credentials.getAccessToken();
like image 470
CowLord Avatar asked Nov 07 '22 18:11

CowLord


1 Answers

  • Add firebase to you android project. https://firebase.google.com/docs/android/setup You will create a project in Firebase and download a json file for configuration and add it in app directory. Add also dependencies in gradle files.
  • On Firebase console go to ML Kit section and create a AUTML model with your photos.
  • Train the model
  • When the training is finished you can download your model and downloaded 3 files in your assets/model directory. And it is ready to use. By this way you will use Firebase AutoML SDK and you dont need to generate the token.

  • Use your model and do predictions from application. Steps are :

    • Prepare image for prediction
    • Prepare the model
    • Get the image labeler
    • Process the image for classification

     public void findLabelsWithAutoML() {
            Bitmap bitmap = null;
            File file = new File(currentPhotoPath);
            System.out.println("file "+file);
            try {
                bitmap = MediaStore.Images.Media
                        .getBitmap(getContentResolver(), Uri.fromFile(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
            FirebaseVisionImageMetadata metadata =  new FirebaseVisionImageMetadata.Builder()
                     .setWidth(480) // 480x360 is typically sufficient for
                    .setHeight(360) // image recognition
                    .setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
                    .setRotation(FirebaseVisionImageMetadata.ROTATION_0)
                    .build();

            FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap);

            System.out.println("firebaseVisionImage :"+firebaseVisionImage);
            FirebaseAutoMLLocalModel localModel = new FirebaseAutoMLLocalModel.Builder()
                    .setAssetFilePath("model/manifest.json")
                    .build();
            FirebaseVisionOnDeviceAutoMLImageLabelerOptions labelerOptions = new FirebaseVisionOnDeviceAutoMLImageLabelerOptions.Builder(localModel)
                    .setConfidenceThreshold(0.65F)  // Evaluate your model in the Firebase console
                    // to determine an appropriate value.
                    .build();
            FirebaseVisionImageLabeler firebaseVisionImageLabeler = null;
            try {
                firebaseVisionImageLabeler = FirebaseVision.getInstance().getOnDeviceAutoMLImageLabeler(labelerOptions);
            } catch (Exception e) {
                e.printStackTrace();
            }
            firebaseVisionImageLabeler.processImage(firebaseVisionImage)
                    .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
                        @Override
                        public void onSuccess(List<FirebaseVisionImageLabel> labels) {
                            for (FirebaseVisionImageLabel label : labels) {
                                System.out.println("label " + label.getText() + " score: " + (label.getConfidence() * 100));
                            }
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //
                        }
                    });

        }

like image 97
bilgin Avatar answered Nov 14 '22 10:11

bilgin