google.auth.exceptions.DefaultCredentialsError - not a valid json file

Viewed 6609

I'mt trying to use goole vision api but i can't run my python script without getting the following error:

google.auth.exceptions.DefaultCredentialsError: ('File /root/GoogleCloudStaff/apikey.json is not a valid json file.', ValueError('Invalid control character at: line 5 column 37 (char 172)',))

My python script:

import io
from google.cloud import vision

vision_client = vision.Client()
#file_name = "/var/www/FlaskApp/FlaskApp/static/"#'375px-Guido_van_Rossum_OSCON_2006_cropped.png'

file_name = '1200px-Guido_van_Rossum_OSCON_2006.jpg'

#file_name = "/var/www/FlaskApp/FlaskApp/static/cyou_pic_folders/cyou_folder_2017_11_16_10_26_18/pi_pic_lc_2017_11_16_10_26_1800049.png"

with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(
        content=content, )

labels = image.detect_labels()
for label in labels:
    print(label.description)

Thanks very much!

3 Answers

DefaultCredentialsError indicates that you failed acquiring default credentials.Have you done initial set up in a proper manner? Take a look at vision

The error you are facing might be attributed to an issue with the service account key itself. \n is a control character present in the key which signifies a new line, which might be causing the issue. To solve the error, you can either validate the content of the JSON file or you can download the key from Google Cloud again. The key can be downloaded by following these instructions.

After acquiring the service account key, the environment variable GOOGLE_APPLICATION_CREDENTIALS has to be set depending on the Operating System used.

As the final step, run the following Python code which performs a labeling task using the Cloud Vision API. The service account key will be automatically used to authenticate the labeling request.

import io
import os

# Imports the Google Cloud client library
from google.cloud import vision

# Instantiates a client
client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
file_name = os.path.abspath('path/to/file/sample.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations

print('Labels:')
for label in labels:
    print(label.description)

The code prints out the labels which the API returns. The Vision API can detect and extract information about entities in an image, across a broad group of categories.

Related