mirror of
				https://github.com/explosion/spaCy.git
				synced 2025-10-31 16:07:41 +03:00 
			
		
		
		
	* Add implementation of batching + backwards compatibility fixes. Tests indicate issue with batch disambiguation for custom singular entity lookups. * Fix tests. Add distinction w.r.t. batch size. * Remove redundant and add new comments. * Adjust comments. Fix variable naming in EL prediction. * Fix mypy errors. * Remove KB entity type config option. Change return types of candidate retrieval functions to Iterable from Iterator. Fix various other issues. * Update spacy/pipeline/entity_linker.py Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Update spacy/pipeline/entity_linker.py Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Update spacy/kb_base.pyx Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Update spacy/kb_base.pyx Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Update spacy/pipeline/entity_linker.py Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Add error messages to NotImplementedErrors. Remove redundant comment. * Fix imports. * Remove redundant comments. * Rename KnowledgeBase to InMemoryLookupKB and BaseKnowledgeBase to KnowledgeBase. * Fix tests. * Update spacy/errors.py Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Move KB into subdirectory. * Adjust imports after KB move to dedicated subdirectory. * Fix config imports. * Move Candidate + retrieval functions to separate module. Fix other, small issues. * Fix docstrings and error message w.r.t. class names. Fix typing for candidate retrieval functions. * Update spacy/kb/kb_in_memory.pyx Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Update spacy/ml/models/entity_linker.py Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Fix typing. * Change typing of mentions to be Span instead of Union[Span, str]. * Update docs. * Update EntityLinker and _architecture docs. * Update website/docs/api/entitylinker.md Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> * Adjust message for E1046. * Re-add section for Candidate in kb.md, add reference to dedicated page. * Update docs and docstrings. * Re-add section + reference for KnowledgeBase.get_alias_candidates() in docs. * Update spacy/kb/candidate.pyx * Update spacy/kb/kb_in_memory.pyx * Update spacy/pipeline/legacy/entity_linker.py * Remove canididate.md. Remove mistakenly added config snippet in entity_linker.py. Co-authored-by: Paul O'Leary McCann <polm@dampfkraft.com> Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
		
			
				
	
	
		
			146 lines
		
	
	
		
			4.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			146 lines
		
	
	
		
			4.1 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| import warnings
 | |
| from unittest import TestCase
 | |
| import pytest
 | |
| import srsly
 | |
| from numpy import zeros
 | |
| from spacy.kb.kb_in_memory import InMemoryLookupKB, Writer
 | |
| from spacy.vectors import Vectors
 | |
| from spacy.language import Language
 | |
| from spacy.pipeline import TrainablePipe
 | |
| from spacy.vocab import Vocab
 | |
| 
 | |
| from ..util import make_tempdir
 | |
| 
 | |
| 
 | |
| def nlp():
 | |
|     return Language()
 | |
| 
 | |
| 
 | |
| def vectors():
 | |
|     data = zeros((3, 1), dtype="f")
 | |
|     keys = ["cat", "dog", "rat"]
 | |
|     return Vectors(data=data, keys=keys)
 | |
| 
 | |
| 
 | |
| def custom_pipe():
 | |
|     # create dummy pipe partially implementing interface -- only want to test to_disk
 | |
|     class SerializableDummy:
 | |
|         def __init__(self, **cfg):
 | |
|             if cfg:
 | |
|                 self.cfg = cfg
 | |
|             else:
 | |
|                 self.cfg = None
 | |
|             super(SerializableDummy, self).__init__()
 | |
| 
 | |
|         def to_bytes(self, exclude=tuple(), disable=None, **kwargs):
 | |
|             return srsly.msgpack_dumps({"dummy": srsly.json_dumps(None)})
 | |
| 
 | |
|         def from_bytes(self, bytes_data, exclude):
 | |
|             return self
 | |
| 
 | |
|         def to_disk(self, path, exclude=tuple(), **kwargs):
 | |
|             pass
 | |
| 
 | |
|         def from_disk(self, path, exclude=tuple(), **kwargs):
 | |
|             return self
 | |
| 
 | |
|     class MyPipe(TrainablePipe):
 | |
|         def __init__(self, vocab, model=True, **cfg):
 | |
|             if cfg:
 | |
|                 self.cfg = cfg
 | |
|             else:
 | |
|                 self.cfg = None
 | |
|             self.model = SerializableDummy()
 | |
|             self.vocab = vocab
 | |
| 
 | |
|     return MyPipe(Vocab())
 | |
| 
 | |
| 
 | |
| def tagger():
 | |
|     nlp = Language()
 | |
|     tagger = nlp.add_pipe("tagger")
 | |
|     # need to add model for two reasons:
 | |
|     # 1. no model leads to error in serialization,
 | |
|     # 2. the affected line is the one for model serialization
 | |
|     tagger.add_label("A")
 | |
|     nlp.initialize()
 | |
|     return tagger
 | |
| 
 | |
| 
 | |
| def entity_linker():
 | |
|     nlp = Language()
 | |
| 
 | |
|     def create_kb(vocab):
 | |
|         kb = InMemoryLookupKB(vocab, entity_vector_length=1)
 | |
|         kb.add_entity("test", 0.0, zeros((1, 1), dtype="f"))
 | |
|         return kb
 | |
| 
 | |
|     entity_linker = nlp.add_pipe("entity_linker")
 | |
|     entity_linker.set_kb(create_kb)
 | |
|     # need to add model for two reasons:
 | |
|     # 1. no model leads to error in serialization,
 | |
|     # 2. the affected line is the one for model serialization
 | |
|     nlp.initialize()
 | |
|     return entity_linker
 | |
| 
 | |
| 
 | |
| objects_to_test = (
 | |
|     [nlp(), vectors(), custom_pipe(), tagger(), entity_linker()],
 | |
|     ["nlp", "vectors", "custom_pipe", "tagger", "entity_linker"],
 | |
| )
 | |
| 
 | |
| 
 | |
| def write_obj_and_catch_warnings(obj):
 | |
|     with make_tempdir() as d:
 | |
|         with warnings.catch_warnings(record=True) as warnings_list:
 | |
|             warnings.filterwarnings("always", category=ResourceWarning)
 | |
|             obj.to_disk(d)
 | |
|             # in python3.5 it seems that deprecation warnings are not filtered by filterwarnings
 | |
|             return list(filter(lambda x: isinstance(x, ResourceWarning), warnings_list))
 | |
| 
 | |
| 
 | |
| @pytest.mark.parametrize("obj", objects_to_test[0], ids=objects_to_test[1])
 | |
| def test_to_disk_resource_warning(obj):
 | |
|     warnings_list = write_obj_and_catch_warnings(obj)
 | |
|     assert len(warnings_list) == 0
 | |
| 
 | |
| 
 | |
| def test_writer_with_path_py35():
 | |
|     writer = None
 | |
|     with make_tempdir() as d:
 | |
|         path = d / "test"
 | |
|         try:
 | |
|             writer = Writer(path)
 | |
|         except Exception as e:
 | |
|             pytest.fail(str(e))
 | |
|         finally:
 | |
|             if writer:
 | |
|                 writer.close()
 | |
| 
 | |
| 
 | |
| def test_save_and_load_knowledge_base():
 | |
|     nlp = Language()
 | |
|     kb = InMemoryLookupKB(nlp.vocab, entity_vector_length=1)
 | |
|     with make_tempdir() as d:
 | |
|         path = d / "kb"
 | |
|         try:
 | |
|             kb.to_disk(path)
 | |
|         except Exception as e:
 | |
|             pytest.fail(str(e))
 | |
| 
 | |
|         try:
 | |
|             kb_loaded = InMemoryLookupKB(nlp.vocab, entity_vector_length=1)
 | |
|             kb_loaded.from_disk(path)
 | |
|         except Exception as e:
 | |
|             pytest.fail(str(e))
 | |
| 
 | |
| 
 | |
| class TestToDiskResourceWarningUnittest(TestCase):
 | |
|     def test_resource_warning(self):
 | |
|         scenarios = zip(*objects_to_test)
 | |
| 
 | |
|         for scenario in scenarios:
 | |
|             with self.subTest(msg=scenario[1]):
 | |
|                 warnings_list = write_obj_and_catch_warnings(scenario[0])
 | |
|                 self.assertEqual(len(warnings_list), 0)
 |