Строковое поле 'google.cloud.language.v1beta2.TextSpan.content' содержит недопустимые данные UTF-8 при анализе буфера протокола.

Я пытаюсь запустить скрипт Python из Google Cloud Natural Language API Python Samples

https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/language/cloud-client/v1beta2/snippets.py

Я не делал никаких модификаций, поэтому я ожидал, что это просто сработает. В частности, я хочу запустить анализ сущностей в текстовом файле/документе. и соответствующая часть кода ниже.

def entities_file(gcs_uri):
"""Detects entities in the file located in Google Cloud Storage."""
client = language_v1beta2.LanguageServiceClient()

# Instantiates a plain text document.
document = types.Document(
    gcs_content_uri=gcs_uri,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects sentiment in the document. You can also analyze HTML with:
#   document.type == enums.Document.Type.HTML
entities = client.analyze_entities(document).entities

# entity types from enums.Entity.Type
entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
               'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')

for entity in entities:
    print('=' * 20)
    print(u'{:<16}: {}'.format('name', entity.name))
    print(u'{:<16}: {}'.format('type', entity_type[entity.type]))
    print(u'{:<16}: {}'.format('metadata', entity.metadata))
    print(u'{:<16}: {}'.format('salience', entity.salience))
    print(u'{:<16}: {}'.format('wikipedia_url',
          entity.metadata.get('wikipedia_url', '-')))

Я поместил свой текстовый файл (кодировка utf-8) в облачное хранилище по адресу gs://neotokyo-cloud-bucket/TXT/TTS-01.txt.

Я запускаю скрипт в облачной оболочке Google. и когда я запускаю файл:

python snippets.py entities-file gs://neotokyo-cloud-bucket/TXT/TTS-01.txt

Я получаю следующую ошибку, которая, похоже, связана с protobuf.

[libprotobuf ERROR google/protobuf/wire_format_lite.cc:629]. 
String field 'google.cloud.language.v1beta2.TextSpan.content' 
contains invalid UTF-8 data when parsing a protocol buffer. 
Use the 'bytes' type if you intend to send raw bytes.

 ERROR:root:Exception deserializing message!
 Traceback (most recent call last):
 File "/usr/local/lib/python2.7/dist-packages/grpc/_common.py", line 87, in _transform
return transformer(message)
 DecodeError: Error parsing message
 Traceback (most recent call last):
 File "snippets.py", line 336, in <module>
entities_file(args.gcs_uri)
 File "snippets.py", line 114, in entities_file
entities = client.analyze_entities(document).entities
 File "/usr/local/lib/python2.7/dist-     packages/google/cloud/language_v1beta2/gapic/language_service_client.py", line 226, in analyze_entities
return self._analyze_entities(request, retry=retry, timeout=timeout)
 File "/usr/local/lib/python2.7/dist-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
return wrapped_func(*args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
on_error=on_error,
 File "/usr/local/lib/python2.7/dist-packages/google/api_core/retry.py", line 177, in retry_target
return target()
 File "/usr/local/lib/python2.7/dist-packages/google/api_core/timeout.py", line 206, in func_with_timeout
return func(*args, **kwargs)
 File "/usr/local/lib/python2.7/dist-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
 File "/usr/local/lib/python2.7/dist-packages/six.py", line 737, in raise_from
raise value
 google.api_core.exceptions.InternalServerError: 500 Exception deserializing response!

Я не знаю protobuf, так что любая помощь приветствуется!


person complexitocous    schedule 27.05.2018    source источник
comment
Вы получаете ту же ошибку, если запускаете ее в Python 3?   -  person Luke Sneeringer    schedule 29.05.2018
comment
Привет, проблема в том, что для Google Cloud SDK требуется Python 2.7.9 или более поздняя версия, и в настоящее время он не работает на Python 3. Поэтому я должен предположить, что это не сработает. Я также разместил свой вопрос как проблему в репозитории github. github.com/GoogleCloudPlatform/google-cloud-python/issues/5411   -  person complexitocous    schedule 30.05.2018


Ответы (2)


Откуда ваш текстовый файл?

Python ParseFromString/SerializeToString использует байты. Попробуйте преобразовать текстовый файл в байты перед разбором

person Jie Luo    schedule 30.05.2018
comment
Я пробовал это: entities = client.analyze_entities(document, encoding_type='bytes').entities, но он говорит ValueError: unknown enum label Или вы имеете в виду что-то еще, на стороне кода protobuf? - person complexitocous; 31.05.2018
comment
Да, я говорю о проводном формате protobuf python (я в команде protobuf python). Похоже, проблема более конкретна с language/cloud-client/v1beta2/snippets.py. - person Jie Luo; 31.05.2018

Похоже, ваш файл начинается с метки порядка байтов (utf-8-sig). Попробуйте преобразовать свой контент в стандартную UTF8 перед вызовом клиента.

person mcasbon    schedule 14.12.2019