Как сохранить и перезагрузить пространственные документы из байтов - PullRequest
0 голосов
/ 12 февраля 2019

У меня много документов для обработки, и я хочу использовать методы .to_bytes () и .from_bytes, но у объекта Doc для чтения нет doc ._. OIE_ents

import spacy
import pickle

def set_OIE(doc):
    ''' Set OpenIE Tuples '''

    atuple = [{'ent_type': "ARG0", 'text': 'dog'},
              {'ent_type': "B-V", 'text': 'can'},
              {'ent_type': "V", 'text': 'run'},
              {'ent_type': "ARG1", 'text': 'fast'}
              ]

    anothertuple = [{'ent_type': "ARG0", 'text':'cat'},
                    {'ent_type': "V", 'text':'is'},
                    {'ent_type': "ARG1", 'text':'smart'}
                    ]

    doc._.OIE_ents.append(atuple)
    doc._.OIE_ents.append(anothertuple)

    return doc

sentence = "The dog can run fast, but the cat is smarter"

nlp = spacy.load('en')
spacy.tokens.Doc.set_extension('OIE_ents', default=[], force=True)
nlp.add_pipe(set_OIE, name='set_OIE')

doc = nlp(sentence)

#Save Bytes
doc_bytes = doc.to_bytes()
vocab_bytes = nlp.vocab.to_bytes()
with open("save_the_full_doc.pkl","wb") as handle:
     pickle.dump( (doc_bytes, vocab_bytes)   ,handle)

print(doc._.OIE_ents)

ОжидаетсяРезультат, список списков словаря:

[[{'ent_type': 'ARG0', 'text': 'dog'}, {'ent_type': 'B-V', 'text': 'can'}, 
{'ent_type': 'V', 'text': 'run'}, {'ent_type': 'ARG1', 'text': 'fast'}], 
[{'ent_type': 'ARG0', 'text': 'cat'}, {'ent_type': 'V', 'text': 'is'}, 
{'ent_type': 'ARG1', 'text': 'smart'}]]

Теперь, в другой среде, загрузите документ:

import spacy, pickle

#Load from Bytes
with open("save_the_full_doc.pkl", "rb") as handle:
    doc_bytes2, vocab_bytes2 = pickle.load(handle)

nlp2 = spacy.load('en')
vocab2 = nlp2.vocab.from_bytes(vocab_bytes2)
doc2 = spacy.tokens.Doc(vocab2).from_bytes(doc_bytes2)

print(doc2._.OIE_ents)

Результаты, doc2 ._. OIE_ents не найдено:

Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    print(doc2._.OIE_ents)
  File "C:\Program Files\Python36\lib\site-packages\spacy\tokens\underscore.py", line 28, in __getattr__
    raise AttributeError(Errors.E046.format(name=name))
AttributeError: [E046] Can't retrieve unregistered extension attribute 'OIE_ents'. Did you forget to call the `set_extension` method?

Итак, как мне вернуть документ полностью?

Обсуждение по теме: https://github.com/explosion/spaCy/issues/1521 spaCy: ошибки при попытке загрузить сериализованный документ https://github.com/explosion/spaCy/issues/1920

...