Search code examples
pythongoogle-cloud-platformnlpsentiment-analysis

ValueError: If the `request` argument is set, then none of the individual field arguments should be set


I am using Google NLP API for Sentiment Analysis to extract sentiment score of dataframe with review as my text column. My code looks lik,

def getSentiments(df):
inserts = 0
df1 = pd.DataFrame(columns = ['Content', 'Sentiment', 'Magnitude', 'ReviewId'])
for index, row in df.iterrows():
    time.sleep(0.5)
    print(index)
    text1 = row['review']
    reviewid = row['review_id']
    texts = []
    sentiments = []    
    magnitudes = []
    salience = []
    try:
        document = analyze_sentiment(text1)
        result = client.analyze_sentiment(document, encoding_type = "UTF8")
        # Get overall sentiment of the input document
        print(u"Document sentiment score: {}".format(result.document_sentiment.score))
       
        sentiments.append(result.document_sentiment.score)
        magnitudes.append(result.document_sentiment.magnitude)
        dfEntitySentiment = pd.DataFrame(columns=['Content','Sentiment','Magnitude', 'ReviewId'])
        dfEntitySentiment['Content'] = text1
        dfEntitySentiment['Sentiment'] = sentiments
        dfEntitySentiment['Magnitude'] = magnitudes
        dfEntitySentiment['ReviewId'] = reviewid
        df1 = df1.append(dfEntitySentiment, ignore_index = True)
        
    except:
        traceback.print_exc()
        continue
return df1

My analyze_sentiment function looks like,

def analyze_sentiment(text_content):
client = language_v1.LanguageServiceClient.from_service_account_json(Alteryx.read("#2").iloc[0]['FullPath'])
type_ = language_v1.types.Document.Type.PLAIN_TEXT
language = "en"
document = {"content": text_content, "type": type_, "language": language}
encoding_type = "UTF8"

return document

I am getting the above error and am not sure how to resolve this.

from google.cloud.language_v1 import enums
from google.cloud.language_v1 import types

These 2 libraries I was using before but I had to update them. After updating the libraries I am getting the error.


Solution

  • There is a library update, according to the Migration Guide, the submodule enums and types have been removed.

    request parameter to client.analyze_sentiment needs to be following format,

    result = client.analyze_sentiment(request = {'document': document, 'encoding_type': encoding_type})
    

    This helped me to resolve my error.