medcat.utils.legacy.helpers

Attributes

logger

Classes

CAT

This is a collection of serialisable model parts.

CDB

The abstract serialisable base class.

NameDescriptor

Functions

prepare_name(raw_name, nlp, names, configs)

Generates different forms of a name. Will edit the provided names

has_per_concept_subnames(cdb)

_fix_subnames(cat)

fix_old_style_cnf(data[, remove, take_from])

fix_subnames(cat)

Module Contents

class medcat.utils.legacy.helpers.CAT(cdb, vocab=None, config=None, model_load_path=None)

Bases: medcat.storage.serialisables.AbstractSerialisable

This is a collection of serialisable model parts.

Parameters:
__init__(cdb, vocab=None, config=None, model_load_path=None)
Parameters:
Return type:

None

cdb
vocab = None
config = None
_trainer: medcat.trainer.Trainer | None = None
_pipeline
usage_monitor
_recreate_pipe(model_load_path=None)
Parameters:

model_load_path (Optional[str])

Return type:

medcat.pipeline.pipeline.Pipeline

classmethod get_init_attrs()
Return type:

list[str]

classmethod ignore_attrs()
Return type:

list[str]

__call__(text)
Parameters:

text (str)

Return type:

Optional[medcat.tokenizing.tokens.MutableDocument]

_ensure_not_training()

Method to ensure config is not set to train.

config.components.linking.train should only be True while training and not during inference. This aalso corrects the setting if necessary.

Return type:

None

get_entities(text: str, only_cui: Literal[False] = False) medcat.data.entities.Entities
get_entities(text: str, only_cui: Literal[True] = True) medcat.data.entities.OnlyCUIEntities
get_entities(text: str, only_cui: bool = False) dict | medcat.data.entities.Entities | medcat.data.entities.OnlyCUIEntities

Get the entities recognised and linked within the provided text.

This will run the text through the pipeline and annotated the recognised and linked entities.

Parameters:
  • text (str) – The text to use.

  • only_cui (bool, optional) – Whether to only output the CUIs rather than the entire context. Defaults to False.

Returns:

Union[dict, Entities, OnlyCUIEntities] – The entities found and linked within the text.

_mp_worker_func(texts_and_indices)
Parameters:

texts_and_indices (list[tuple[str, str, bool]])

Return type:

list[tuple[str, str, Union[dict, medcat.data.entities.Entities, medcat.data.entities.OnlyCUIEntities]]]

_generate_batches_by_char_length(text_iter, batch_size_chars, only_cui)
Parameters:
  • text_iter (Union[Iterator[str], Iterator[tuple[str, str]]])

  • batch_size_chars (int)

  • only_cui (bool)

Return type:

Iterator[list[tuple[str, str, bool]]]

_generate_batches(text_iter, batch_size, batch_size_chars, only_cui)
Parameters:
  • text_iter (Union[Iterator[str], Iterator[tuple[str, str]]])

  • batch_size (int)

  • batch_size_chars (int)

  • only_cui (bool)

Return type:

Iterator[list[tuple[str, str, bool]]]

_generate_simple_batches(text_iter, batch_size, only_cui)
Parameters:
  • text_iter (Union[Iterator[str], Iterator[tuple[str, str]]])

  • batch_size (int)

  • only_cui (bool)

Return type:

Iterator[list[tuple[str, str, bool]]]

_mp_one_batch_per_process(executor, batch_iter, external_processes)
Parameters:
  • executor (concurrent.futures.ProcessPoolExecutor)

  • batch_iter (Iterator[list[tuple[str, str, bool]]])

  • external_processes (int)

Return type:

Iterator[tuple[str, Union[dict, medcat.data.entities.Entities, medcat.data.entities.OnlyCUIEntities]]]

get_entities_multi_texts(texts, only_cui=False, n_process=1, batch_size=-1, batch_size_chars=1000000)

Get entities from multiple texts (potentially in parallel).

If n_process > 1, n_process - 1 new processes will be created and data will be processed on those as well as the main process in parallel.

Parameters:
  • texts (Union[Iterable[str], Iterable[tuple[str, str]]]) – The input text. Either an iterable of raw text or one with in the format of (text_index, text).

  • only_cui (bool) – Whether to only return CUIs rather than other information like start/end and annotated value. Defaults to False.

  • n_process (int) – Number of processes to use. Defaults to 1.

  • batch_size (int) – The number of texts to batch at a time. A batch of the specified size will be given to each worker process. Defaults to -1 and in this case the character count will be used instead.

  • batch_size_chars (int) – The maximum number of characters to process in a batch. Each process will be given batch of texts with a total number of characters not exceeding this value. Defaults to 1,000,000 characters. Set to -1 to disable.

Yields:

Iterator[tuple[str, Union[dict, Entities, OnlyCUIEntities]]] – The results in the format of (text_index, entities).

Return type:

Iterator[tuple[str, Union[dict, medcat.data.entities.Entities, medcat.data.entities.OnlyCUIEntities]]]

_get_entity(ent, doc_tokens, cui)
Parameters:
Return type:

medcat.data.entities.Entity

get_addon_output(ent)

Get the addon output for the entity.

This includes a key-value pair for each addon that provides some. Sometimes same-type addons may combine their output under the same key.

Parameters:

ent (MutableEntity) – The entity in quesiton.

Raises:

ValueError – If unable to merge multiple addon output.

Returns:

dict[str, dict] – All the addon output.

Return type:

dict[str, dict]

_doc_to_out_entity(ent, doc_tokens, only_cui)
Parameters:
Return type:

tuple[int, Union[medcat.data.entities.Entity, str]]

_doc_to_out(doc, only_cui, out_with_text=False)
Parameters:
Return type:

Union[medcat.data.entities.Entities, medcat.data.entities.OnlyCUIEntities]

property trainer

The trainer object.

save_model_pack(target_folder, pack_name=DEFAULT_PACK_NAME, serialiser_type='dill', make_archive=True, only_archive=False, add_hash_to_pack_name=True, change_description=None)

Save model pack.

The resulting model pack name will have the hash of the model pack in its name if (and only if) the default model pack name is used.

Parameters:
  • target_folder (str) – The folder to save the pack in.

  • pack_name (str, optional) – The model pack name. Defaults to DEFAULT_PACK_NAME.

  • serialiser_type (Union[str, AvailableSerialisers], optional) – The serialiser type. Defaults to ‘dill’.

  • make_archive (bool) – Whether to make the arhive /.zip file. Defaults to True.

  • only_archive (bool) – Whether to clear the non-compressed folder. Defaults to False.

  • add_hash_to_pack_name (bool) – Whether to add the hash to the pack name. This is only relevant if pack_name is specified. Defaults to True.

  • change_description (Optional[str]) – If provided, this the description will be added to the model description. Defaults to None.

Returns:

str – The final model pack path.

Return type:

str

_get_hash()
Return type:

str

_versioning(change_description)
Parameters:

change_description (Optional[str])

Return type:

str

classmethod attempt_unpack(zip_path)

Attempt unpack the zip to a folder and get the model pack path.

If the folder already exists, no unpacking is done.

Parameters:

zip_path (str) – The ZIP path

Returns:

str – The model pack path

Return type:

str

classmethod load_model_pack(model_pack_path)

Load the model pack from file.

Parameters:

model_pack_path (str) – The model pack path.

Raises:

ValueError – If the saved data does not represent a model pack.

Returns:

CAT – The loaded model pack.

Return type:

CAT

classmethod load_cdb(model_pack_path)

Loads the concept database from the provided model pack path

Parameters:

model_pack_path (str) – path to model pack, zip or dir.

Returns:

CDB – The loaded concept database

Return type:

medcat.cdb.CDB

get_model_card(as_dict: Literal[True]) medcat.data.model_card.ModelCard
get_model_card(as_dict: Literal[False]) str

Get the model card either a (nested) dict or a json string.

Parameters:

as_dict (bool) – Whether to return as dict. Defaults to False.

Returns:

Union[str, ModelCard] – The model card.

__eq__(other)
Parameters:

other (Any)

Return type:

bool

add_addon(addon)
Parameters:

addon (medcat.components.addons.addons.AddonComponent)

Return type:

None

get_strategy()
Return type:

SerialisingStrategy

classmethod include_properties()
Return type:

list[str]

class medcat.utils.legacy.helpers.CDB(config)

Bases: medcat.storage.serialisables.AbstractSerialisable

The abstract serialisable base class.

This defines some common defaults.

Parameters:

config (medcat.config.Config)

__init__(config)
Parameters:

config (medcat.config.Config)

Return type:

None

config
cui2info: dict[str, medcat.cdb.concepts.CUIInfo]
name2info: dict[str, medcat.cdb.concepts.NameInfo]
type_id2info: dict[str, medcat.cdb.concepts.TypeInfo]
token_counts: dict[str, int]
addl_info: dict[str, Any]
_subnames: set[str]
is_dirty = False
has_changed_names = False
classmethod get_init_attrs()
Return type:

list[str]

_reset_subnames()
has_subname(name)

Whether the CDB has the specified subname.

Parameters:

name (str) – The subname to check.

Returns:

bool – Whether the subname is present in this CDB.

Return type:

bool

get_name(cui)

Returns preferred name if it exists, otherwise it will return the longest name assigned to the concept.

Parameters:

cui (str) – Concept ID or unique identifier in this database.

Returns:

str – The name of the concept.

Return type:

str

weighted_average_function(step)

Get the weighted average for steop.

Parameters:

step (int) – The steop.

Returns:

float – The weighted average.

Return type:

float

add_types(types)

Add type info to CDB.

Parameters:

types (Iterable[tuple[str, str]]) – The raw type info.

Return type:

None

add_names(cui, names, name_status=ST.AUTOMATIC, full_build=False)

Adds a name to an existing concept.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally.

  • names (dict[str, NameDescriptor]) –

    Names for this concept, or the value that if found in free text can be linked to this concept. Names is an dict like: `{name: {‘tokens’: tokens, ‘snames’: snames,

    ’raw_name’: raw_name}, …}`

    Names should be generated by helper function ‘medcat.preprocessing.cleaners.prepare_name’

  • name_status (str) – One of P, N, A. Defaults to ‘A’.

  • full_build (bool) – If True the dictionary self.addl_info will also be populated, contains a lot of extra information about concepts, but can be very memory consuming. This is not necessary for normal functioning of MedCAT (Default value False).

Return type:

None

_add_concept_names(cui, names, name_status)
Parameters:
Return type:

None

_add_full_build(cui, names, ontologies, description, type_ids)
Parameters:
Return type:

None

_add_concept(cui, names, ontologies, name_status, type_ids, description, full_build=False)

Add a concept to internal Concept Database (CDB). Depending on what you are providing this will add a large number of properties for each concept.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally.

  • names (dict[str, NameDescriptor]) –

    Names for this concept, or the value that if found in free text can be linked to this concept. Names is a dict like: `{name: {‘tokens’: tokens, ‘snames’: snames,

    ’raw_name’: raw_name}, …}`

    Names should be generated by helper function ‘medcat.preprocessing.cleaners.prepare_name’

  • ontologies (set[str]) – ontologies in which the concept exists (e.g. SNOMEDCT, HPO)

  • name_status (str) – One of P, N, A

  • type_ids (set[str]) – Semantic type identifier (have a look at TUIs in UMLS or SNOMED-CT)

  • description (str) – Description of this concept.

  • full_build (bool) – If True the dictionary self.addl_info will also be populated, contains a lot of extra information about concepts, but can be very memory consuming. This is not necessary for normal functioning of MedCAT (Default Value False).

Return type:

None

reset_training()

Will remove all training efforts - in other words all embeddings that are learnt for concepts in the current CDB. Please note that this does not remove synonyms (names) that were potentially added during supervised/online learning.

Return type:

None

filter_by_cui(cuis_to_keep)

Subset the core CDB fields (dictionaries/maps).

Note that this will potenitally keep a bit more CUIs then in cuis_to_keep. It will first find all names that link to the cuis_to_keep and then find all CUIs that link to those names and keep all of them.

This also will not remove any data from cdb.addl_info - as this field can contain data of unknown structure.

Parameters:

cuis_to_keep (Collection[str]) – CUIs that will be kept, the rest will be removed (not completely, look above).

Raises:

Exception – If no snames and subsetting is not possible.

Return type:

None

remove_cui(cui)

This function takes a CUI and removes it the CDB.

It also removes the CUI from name specific per_cui_status maps as well as well as removes all the names that do not correspond to any CUIs after the removal of this one.

Parameters:

cui (str) – The CUI to remove.

Return type:

None

_remove_names(cui, names)

Remove names from an existing concept - effect is this name will never again be used to link to this concept. This will only remove the name from the linker (namely name2cuis and name2cuis2status), the name will still be present everywhere else. Why? Because it is bothersome to remove it from everywhere, but could also be useful to keep the removed names in e.g. cui2names.

Parameters:
  • cui (str) – Concept ID or unique identifier in this database.

  • names (Iterable[str]) – Names to be removed (e.g list, set, or even a dict (in which case keys will be used)).

Return type:

None

__eq__(other)
Parameters:

other (Any)

Return type:

bool

get_cui2count_train()
Return type:

dict[str, int]

get_name2count_train()
Return type:

dict[str, int]

get_hash()
Return type:

str

get_basic_info()
Return type:

medcat.data.model_card.CDBInfo

save(save_path, serialiser=AvailableSerialisers.dill, overwrite=False)

Save CDB at path.

Parameters:
  • save_path (str) – The path to save at.

  • serialiser (Union[ str, AvailableSerialisers], optional) – The serialiser. Defaults to AvailableSerialisers.dill.

  • overwrite (bool, optional) – Whether to allow overwriting existing files. Defaults to False.

Return type:

None

classmethod load(path)
Parameters:

path (str)

Return type:

CDB

get_strategy()
Return type:

SerialisingStrategy

classmethod ignore_attrs()
Return type:

list[str]

classmethod include_properties()
Return type:

list[str]

medcat.utils.legacy.helpers.prepare_name(raw_name, nlp, names, configs)

Generates different forms of a name. Will edit the provided names dictionary and add information generated from the name.

Parameters:
  • nlp (BaseTokenizer) – The tokenizer.

  • names (dict[str, NameDescriptor]) – Dictionary of existing names for this concept in this row of a CSV. The new generated name versions and other required information will be added here.

  • configs (tuple[LGeneral, LPreprocessing, LCDBMaker]) – Applicable configs for medcat.

  • raw_name (str)

Returns:

names (dict) – The updated dictionary of prepared names.

Return type:

dict[str, NameDescriptor]

class medcat.utils.legacy.helpers.NameDescriptor
tokens: list[str]
snames: set[str]
raw_name: str
is_upper: bool
medcat.utils.legacy.helpers.logger
medcat.utils.legacy.helpers.has_per_concept_subnames(cdb)
Parameters:

cdb (medcat.cdb.cdb.CDB)

Return type:

bool

medcat.utils.legacy.helpers._fix_subnames(cat)
Parameters:

cat (medcat.cat.CAT)

Return type:

None

medcat.utils.legacy.helpers.fix_old_style_cnf(data, remove={'py/object', '__fields_set__', '__private_attribute_values__'}, take_from='py/state.__dict__')
Parameters:
  • data (dict)

  • remove (set[str])

  • take_from (str)

medcat.utils.legacy.helpers.fix_subnames(cat)
Parameters:

cat (medcat.cat.CAT)

Return type:

None