2019-03-18 19:27:51 +03:00
|
|
|
# cython: profile=True
|
|
|
|
# coding: utf8
|
|
|
|
from preshed.maps import PreshMap
|
2019-03-15 18:05:23 +03:00
|
|
|
|
|
|
|
|
|
|
|
cdef class KnowledgeBase:
|
2019-03-18 19:27:51 +03:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._entry_index = PreshMap()
|
|
|
|
self._alias_index = PreshMap()
|
|
|
|
self.mem = Pool()
|
|
|
|
|
2019-03-15 18:05:23 +03:00
|
|
|
def __len__(self):
|
2019-03-19 17:51:56 +03:00
|
|
|
return self.get_size_entities()
|
|
|
|
|
|
|
|
def get_size_entities(self):
|
2019-03-15 18:05:23 +03:00
|
|
|
return self._entries.size()
|
|
|
|
|
2019-03-19 17:51:56 +03:00
|
|
|
def get_size_aliases(self):
|
|
|
|
return self._aliases_table.size()
|
|
|
|
|
2019-03-18 19:27:51 +03:00
|
|
|
def add_entity(self, unicode entity_id, float prob, vectors=None, features=None):
|
|
|
|
cdef hash_t id_hash = hash_string(entity_id)
|
|
|
|
|
2019-03-15 18:05:23 +03:00
|
|
|
# TODO: more friendly check for non-unique name
|
2019-03-18 19:27:51 +03:00
|
|
|
if id_hash in self._entry_index:
|
2019-03-15 18:05:23 +03:00
|
|
|
return
|
|
|
|
|
2019-03-18 19:27:51 +03:00
|
|
|
|
2019-03-18 12:31:01 +03:00
|
|
|
cdef int32_t dummy_value = 342
|
2019-03-18 14:38:40 +03:00
|
|
|
self.c_add_entity(entity_key=id_hash, prob=prob, vector_rows=&dummy_value, feats_row=dummy_value)
|
2019-03-18 12:31:01 +03:00
|
|
|
# TODO self._vectors_table.get_pointer(vectors),
|
2019-03-18 14:38:40 +03:00
|
|
|
# self._features_table.get(features))
|
2019-03-15 18:05:23 +03:00
|
|
|
|
2019-03-18 19:27:51 +03:00
|
|
|
def add_alias(self, unicode alias, entities, probabilities):
|
2019-03-15 18:05:23 +03:00
|
|
|
"""For a given alias, add its potential entities and prior probabilies to the KB."""
|
|
|
|
cdef hash_t alias_hash = hash_string(alias)
|
2019-03-18 14:38:40 +03:00
|
|
|
|
|
|
|
# TODO: check that alias hadn't been defined before
|
|
|
|
# TODO: check that entity is already in this KB (entity_index is OK)
|
|
|
|
# TODO: check sum(probabilities) <= 1
|
2019-03-15 18:05:23 +03:00
|
|
|
# TODO: check len(entities) == len(probabilities)
|
2019-03-18 14:38:40 +03:00
|
|
|
|
2019-03-18 19:27:51 +03:00
|
|
|
self.c_add_aliases(alias_key=alias_hash, entities=entities, probabilities=probabilities)
|
|
|
|
|
2019-03-18 19:50:01 +03:00
|
|
|
def get_candidates(self, unicode alias):
|
|
|
|
cdef hash_t alias_hash = hash_string(alias)
|
2019-03-19 17:51:56 +03:00
|
|
|
alias_index = <int64_t>self._alias_index.get(alias_hash)
|
|
|
|
return self._aliases_table[alias_index]
|
2019-03-15 18:05:23 +03:00
|
|
|
|