I use Google cloud's Natural Language API from this link:
And I use this command in powershell :
$env:GOOGLE_APPLICATION_CREDENTIALS="D:\analyze_sentiment\MyFirstProject-bbe4f7bccb98.json"
Then I use this command in cmd:
set GOOGLE_APPLICATION_CREDENTIALS=D:\analyze_sentiment\MyFirstProject-bbe4f7bccb98.json
But when I use python code:
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))
The error message said:
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials.
@dapsjj Thanks for the report. In order to help us diagnose, can you please provide:
pip --freezeAlso, at the top of your script, can you add the following lines, and include the output:
import os
print('Credendtials from environ: {}'.format(
os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'))
@tseaver I modify my code as you said.
Now my code:
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
import os
print('Credendtials from environ: {}'.format(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')))
# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))
The output of the console is like this:
Credendtials from environ: None
Traceback (most recent call last):
File "E:/test_opencv/test_120.py", line 8, in
client = language.LanguageServiceClient()
File "E:\Anaconda3\lib\site-packages\google\cloud\language_v1\gapic\language_service_client.py", line 92, in __init__
scopes=self._DEFAULT_SCOPES)
File "E:\Anaconda3\lib\site-packages\google\api_core\grpc_helpers.py", line 132, in create_channel
credentials, _ = google.auth.default(scopes=scopes)
File "E:\Anaconda3\lib\site-packages\google\auth_default.py", line 306, in default
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials.
This is the clue:
Credendtials from environ: None
Your script is not running in a context where it has the GOOGLE_APPLICATION_CREDENTIALS environment variable set.
@tseaver The google staff told me “I checked your Cloud Console and I see that you don't have enabled the Natural Language API. Please proceed to enable this API by going to the Library inside the "APIs & Services" section”
I think this is the real reason for my mistake.I will try it.
@tseaver, on a similar note. I have carried out the same process. My credentials are verified, however, it is not able to locate the service account file
# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
import os
print('Credendtials from environ: {}'.format(os.environ.get('GOOGLE_APPLICATION_CREDENTIALS')))
# Instantiates a client
client = language.LanguageServiceClient()
# The text to analyze
text = u'Hello, world!'
document = types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT)
# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment
print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))
print O/P: Credendtials from environ: "C:\Users\varun.mohankumar\amazon-san-review-c82780df4538.json"
Error:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\auth\_default.py in _get_explicit_environ_credentials()
163 if explicit_file is not None:
164 credentials, project_id = _load_credentials_from_file(
--> 165 os.environ[environment_vars.CREDENTIALS])
166
167 return credentials, project_id
~\AppData\Local\Continuum\anaconda3\lib\site-packages\google\auth\_default.py in _load_credentials_from_file(filename)
87 if not os.path.exists(filename):
88 raise exceptions.DefaultCredentialsError(
---> 89 'File {} was not found.'.format(filename))
90
91 with io.open(filename, 'r') as file_obj:
DefaultCredentialsError: File "C:\Users\varun.mohankumar\amazon-san-review-c82780df4538.json" was not found
However, this is where my file is located in my local machine.
Any help on this is appreciated!
@vroon5 The exception is being raised because the file does not exist: can you check for a typo in the path?
Thank you for the quick reply @tseaver, that was the first thing I checked. I don't see any typo.
@vroon5 Can you try running a Python script which tests each part of the path? There might be escaped characters embedded, somehow.
Hi @tseaver, I tried placing the file in every subpath and running the code again. It is still not working.
However, I am curious about the step we need perform prior to running this code. While setting up the environment variable for google application credentials, the command prompt does not give any feedback after I set the environment variable, it just moves to the next line. Would that be an issue?

@vroon5 I don't think so. If you run set from that command prompt, do you see the expected value for GOOGLE_APPLICATION_CREDENTIALS? E.g.:
> set

I cannot completely interpret the output of set, but I assume this is your question. It identifies that google application credentials above path.
That establishes that you have set the environment variable as expected. If you run your script from that console, to you still get the "File was not found" traceback?
I did not run the script from the console, but I ran it in jupyter notebook. The error is same as what I posted first. I try to run from the console and let you know, Thank you once again for your patience @tseaver
Hi @tseaver here is what I tried from the console. The error stays the same!

I know the error reason,I must use cmd mode to run the code,please do not run the code with pycharm or other IDE.And set this link API "enable".
And then the error disappeared.
The following solution worked.
: explicitly mentioning the location of the private key
https://google-auth.readthedocs.io/en/latest/user-guide.html#service-account-private-key-files

The following solution worked.
: explicitly mentioning the location of the private key
https://google-auth.readthedocs.io/en/latest/user-guide.html#service-account-private-key-files
Just sharing it in plain text so it can be easily copied 😄
`
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
from google.oauth2 import service_account
import os
# In this case I'm using a relative path from the the same path where this script is located.
credentials_path = os.path.dirname(os.path.realpath(__file__)) + os.sep + '[RELATIVE_PATH_TO_JSON_KEY]'
credentials = service_account.Credentials.from_service_account_file(credentials_path)
client = language.LanguageServiceClient(credentials=credentials)
`
I cannot completely interpret the output of set, but I assume this is your question. It identifies that google application credentials above path.
set path without quotation marks!
set GOOGLE_APPLICATION_CREDENTIALS=[PATH]
This one solved it for me on all platforms:
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "FULLPATH TO JSON"
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "FULLPATH TO JSON"
@fbaeumer Thankyou .It worked for me
If you are using PyCharm or anything else, and your program works in Windows terminal but not if you run it from IDE debug configuration, set the environment variable inside the IDE's run/debug configurations panel on the top right corner. Insert it manually into the environment variable field for the project and you are good to go!

How to solve
@vishu002 la opción que comenta @fbaeumer a mi me funciono, no me sirvió crear la variable del entorno decargue mi archivo Json como mencionan en la documentación de google https://cloud.google.com/docs/authentication/getting-started#linux-or-macos y luego agregue en mi archivo:
import os
os.environ ["GOOGLE_APPLICATION_CREDENTIALS"] = "FULLPATH TO JSON"
Todo funciono correcto
My issues already solved
export GOOGLE_APPLICATION_CREDENTIALS='PATH'
worked for me in Linux.
Please note that the google-cloud-language Python client library is no longer maintained in this repository. Future issues should be reported to the python-language tracker.
Most helpful comment
The following solution worked.

: explicitly mentioning the location of the private key
https://google-auth.readthedocs.io/en/latest/user-guide.html#service-account-private-key-files