Search code examples
python-3.xgoogle-cloud-platformnlpgoogle-cloud-functionsgoogle-natural-language

Request has type LocalProxy, but expected one of: bytes, unicode


I'm trying to use the Google Cloud Platform Natural Language API with Python within a Google Cloud Function. Whenever I use the code provided in this Google tutorial for analyzing entity analysis using text in Cloud Storage, I get the following error message:

 File "/user_code/main.py", line 9, in entity_sentiment_file
    type=enums.Document.Type.PLAIN_TEXT)
TypeError: <Request 'http://25e4801f1004e4eb41d11633d9b2e9e9-dot-ad6bdc7c397c15e62-tp.appspot.com/'
[POST]> has type LocalProxy, but expected one of: bytes, unicode

I obtain that error message after successfully deploying the function and clicking "Test the Function" with a triggering event of empty curly braces {}, then going to the View Logs page.

I've tried providing the test event parameters like below, but I obtained the same result.

{"gcs_uri":"gs://test-news-articles/news-article-1.txt"}

Here's my entire function:

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

def entity_sentiment_file(gcs_uri,request=None):
    print('gcs_uri: {}'.format(gcs_uri))
    client = language.LanguageServiceClient()
    document = types.Document(
        gcs_content_uri=gcs_uri,
        type=enums.Document.Type.PLAIN_TEXT)

    # Detect and send native Python encoding to receive correct word offsets.
    encoding = enums.EncodingType.UTF32
    if sys.maxunicode == 65535:
        encoding = enums.EncodingType.UTF16

    result = client.analyze_entity_sentiment(document, encoding)

    for entity in result.entities:
        print(u'Name: "{}"'.format(entity.name))
        for mention in entity.mentions:
            print(u'  Begin Offset : {}'.format(mention.text.begin_offset))
            print(u'  Content : {}'.format(mention.text.content))
            print(u'  Magnitude : {}'.format(mention.sentiment.magnitude))
            print(u'  Sentiment : {}'.format(mention.sentiment.score))
            print(u'  Type : {}'.format(mention.type))
        print(u'Salience: {}'.format(entity.salience))
        print(u'Sentiment: {}\n'.format(entity.sentiment))

Any help would be much appreciated.


Solution

  • A function that responds to an HTTP request needs to have the signature:

    def my_function(request):
        ...
    

    where request is provided by the Cloud Functions runtime on every new request.

    Right now, gcs_uri is getting set to the request value (which is a LocalProxy type) and then you're trying to format a string with it, which causes the exception.

    I'm not sure where you're expecting gcs_uri to come from, but it won't be provided to the function as an argument. If you're making a request with JSON, it will be available using request.json['gcs_uri']. See "Writing HTTP Functions" for more details.