medcat2.components.addons.meta_cat.meta_cat =========================================== .. py:module:: medcat2.components.addons.meta_cat.meta_cat Attributes ---------- .. autoapisummary:: medcat2.components.addons.meta_cat.meta_cat.logger medcat2.components.addons.meta_cat.meta_cat._META_ANNS_PATH medcat2.components.addons.meta_cat.meta_cat._SHARE_TOKENS_PATH Exceptions ---------- .. autoapisummary:: medcat2.components.addons.meta_cat.meta_cat.MisconfiguredMetaCATException Classes ------- .. autoapisummary:: medcat2.components.addons.meta_cat.meta_cat.Hasher medcat2.components.addons.meta_cat.meta_cat.BaseTokenizer medcat2.components.addons.meta_cat.meta_cat.ConfigMetaCAT medcat2.components.addons.meta_cat.meta_cat.AddonComponent medcat2.components.addons.meta_cat.meta_cat.TokenizerWrapperBase medcat2.components.addons.meta_cat.meta_cat.AbstractSerialisable medcat2.components.addons.meta_cat.meta_cat.SerialisingStrategy medcat2.components.addons.meta_cat.meta_cat.MutableDocument medcat2.components.addons.meta_cat.meta_cat.MutableEntity medcat2.components.addons.meta_cat.meta_cat.CDB medcat2.components.addons.meta_cat.meta_cat.Vocab medcat2.components.addons.meta_cat.meta_cat.MedCATTrainerExportDocument medcat2.components.addons.meta_cat.meta_cat.MetaCATAddon medcat2.components.addons.meta_cat.meta_cat.MetaCAT Functions --------- .. autoapisummary:: medcat2.components.addons.meta_cat.meta_cat.predict medcat2.components.addons.meta_cat.meta_cat.train_model medcat2.components.addons.meta_cat.meta_cat.set_all_seeds medcat2.components.addons.meta_cat.meta_cat.eval_model medcat2.components.addons.meta_cat.meta_cat.prepare_from_json medcat2.components.addons.meta_cat.meta_cat.encode_category_values medcat2.components.addons.meta_cat.meta_cat.prepare_for_oversampled_data medcat2.components.addons.meta_cat.meta_cat.serialise medcat2.components.addons.meta_cat.meta_cat.deserialise Module Contents --------------- .. py:class:: Hasher(dumper = dumps) A consistent hasher. This class is able to hash the same object(s) to the same value every time. This is in contrast to the normal hashing in python that does not guarantee identical results over multiple runs. :param dumper: The dumper to be used. Defaults to the `dumps` method. :type dumper: Callable[[Any, bool], bytes], optional .. py:method:: __init__(dumper = dumps) .. py:attribute:: m .. py:attribute:: _dumper .. py:method:: update(obj, length = False) Update the hasher with the object in question. If `length = True` is passed, only the length of the byte array corresponding to the data is considered Otherwise the entire byte array is used. :param obj: The object to be added / hashed. :type obj: Any :param length: Whether to only dump the length of the file array. Defaults to False. :type length: bool, optional .. py:method:: update_bytes(b) Update the hasher with a byte array. :param b: The byte array to update with. :type b: bytes .. py:method:: hexdigest() Get the hex for the current hash state. :Returns: **str** -- The hex representation of the hashed objects. .. py:class:: BaseTokenizer Bases: :py:obj:`Protocol` The base tokenizer protocol. .. py:method:: create_entity(doc, token_start_index, token_end_index, label) Create an entity from a document. :param doc: The document to use. :type doc: MutableDocument :param token_start_index: The token start index. :type token_start_index: int :param token_end_index: The token end index. :type token_end_index: int :param label: The label. :type label: str :Returns: **MutableEntity** -- The resulting entity. .. py:method:: entity_from_tokens(tokens) Get an entity from the list of tokens. :param tokens: List of tokens. :type tokens: list[MutableToken] :Returns: **MutableEntity** -- The resulting entity. .. py:method:: __call__(text) .. py:method:: get_init_args(config) :classmethod: .. py:method:: get_init_kwargs(config) :classmethod: .. py:method:: get_doc_class() Get the document implementation class used by the tokenizer. This can be used (e.g) to register addon paths. :Returns: **Type[MutableDocument]** -- The document class. .. py:method:: get_entity_class() Get the entity implementation class used by the tokenizer. :Returns: **Type[MutableEntity]** -- The entity class. .. py:attribute:: __slots__ :value: () .. py:attribute:: _is_protocol :value: True .. py:attribute:: _is_runtime_protocol :value: False .. py:method:: __init_subclass__(*args, **kwargs) :classmethod: .. py:method:: __class_getitem__(params) :classmethod: .. py:class:: ConfigMetaCAT(/, **data) Bases: :py:obj:`medcat2.config.config.ComponentConfig` The MetaCAT part of the config .. py:attribute:: general :type: General .. py:attribute:: model :type: Model .. py:attribute:: train :type: Train .. py:class:: Config .. py:attribute:: extra :value: 'allow' .. py:attribute:: validate_assignment :value: True .. py:attribute:: comp_name :type: str :value: 'default' The name of the component. If a custom implementation is required, it needs to be registered using `medcat2.components.types.register_core_component( , , ) By default, only the 'default' component is registered. .. py:attribute:: init_args :type: list These are the positional arguments required to construct the component. For default components, these will be automatically filled. However, if a custom component is used, these would need to be set manually. .. py:attribute:: init_kwargs :type: dict These are the keyword arguments required to construct the component. For default components, these will be automatically filled. However, if a custom component is used, these would need to be set manually. .. py:method:: ignore_attrs() :classmethod: .. py:method:: get_strategy() .. py:method:: get_init_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:method:: merge_config(other) Merge this config with another config's (partial) model dump. The exepctation is that the `other` dict is a partial model dump. Values specified there are overwritten into the current config. Values not specified there are left intact. The `other` config can have keys/values that do not exist in the config or sub-config. And they will be added where possible. :param other: The model dump :type other: dict :raises IncorrectConfigValues: If unable to set the attribute, trying to set incorrect value, or trying to set sub-config values in an incorrect format (non-dict). .. py:attribute:: model_config :type: ClassVar[pydantic.config.ConfigDict] Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. .. py:attribute:: model_fields :type: ClassVar[Dict[str, pydantic.fields.FieldInfo]] Metadata about the fields defined on the model, mapping of field names to [`FieldInfo`][pydantic.fields.FieldInfo] objects. This replaces `Model.__fields__` from Pydantic V1. .. py:attribute:: model_computed_fields :type: ClassVar[Dict[str, pydantic.fields.ComputedFieldInfo]] A dictionary of computed field names and their corresponding `ComputedFieldInfo` objects. .. py:attribute:: __class_vars__ :type: ClassVar[set[str]] The names of the class variables defined on the model. .. py:attribute:: __private_attributes__ :type: ClassVar[Dict[str, pydantic.fields.ModelPrivateAttr]] Metadata about the private attributes of the model. .. py:attribute:: __signature__ :type: ClassVar[inspect.Signature] The synthesized `__init__` [`Signature`][inspect.Signature] of the model. .. py:attribute:: __pydantic_complete__ :type: ClassVar[bool] :value: False Whether model building is completed, or if there are still undefined fields. .. py:attribute:: __pydantic_core_schema__ :type: ClassVar[pydantic_core.CoreSchema] The core schema of the model. .. py:attribute:: __pydantic_custom_init__ :type: ClassVar[bool] Whether the model has a custom `__init__` method. .. py:attribute:: __pydantic_decorators__ :type: ClassVar[pydantic._internal._decorators.DecoratorInfos] Metadata containing the decorators defined on the model. This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. .. py:attribute:: __pydantic_generic_metadata__ :type: ClassVar[pydantic._internal._generics.PydanticGenericMetadata] Metadata for generic models; contains data used for a similar purpose to __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these. .. py:attribute:: __pydantic_parent_namespace__ :type: ClassVar[Dict[str, Any] | None] :value: None Parent namespace of the model, used for automatic rebuilding of models. .. py:attribute:: __pydantic_post_init__ :type: ClassVar[None | Literal['model_post_init']] The name of the post-init method for the model, if defined. .. py:attribute:: __pydantic_root_model__ :type: ClassVar[bool] :value: False Whether the model is a [`RootModel`][pydantic.root_model.RootModel]. .. py:attribute:: __pydantic_serializer__ :type: ClassVar[pydantic_core.SchemaSerializer] The `pydantic-core` `SchemaSerializer` used to dump instances of the model. .. py:attribute:: __pydantic_validator__ :type: ClassVar[pydantic_core.SchemaValidator | pydantic.plugin._schema_validator.PluggableSchemaValidator] The `pydantic-core` `SchemaValidator` used to validate instances of the model. .. py:attribute:: __pydantic_extra__ :type: dict[str, Any] | None A dictionary containing extra values, if [`extra`][pydantic.config.ConfigDict.extra] is set to `'allow'`. .. py:attribute:: __pydantic_fields_set__ :type: set[str] The names of fields explicitly set during instantiation. .. py:attribute:: __pydantic_private__ :type: dict[str, Any] | None Values of private attributes set on the model instance. .. py:attribute:: __slots__ :value: ('__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__') .. py:method:: __init__(/, **data) Create a new model by parsing and validating input data from keyword arguments. Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name. .. py:property:: model_extra :type: dict[str, Any] | None Get extra fields set during validation. :Returns: **A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`.** .. py:property:: model_fields_set :type: set[str] Returns the set of fields that have been explicitly set on this model instance. :Returns: **A set of strings representing the fields that have been set,** -- i.e. that were not filled from defaults. .. py:method:: model_construct(_fields_set = None, **values) :classmethod: Creates a new instance of the `Model` class with validated data. Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. Default values are respected, but no other validation is performed. !!! note `model_construct()` generally respects the `model_config.extra` setting on the provided model. That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in an error if extra values are passed, but they will be ignored. :param _fields_set: A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the `values` argument will be used. :param values: Trusted or pre-validated data dictionary. :Returns: **A new instance of the `Model` class with validated data.** .. py:method:: model_copy(*, update = None, deep = False) Usage docs: https://docs.pydantic.dev/2.9/concepts/serialization/#model_copy Returns a copy of the model. :param update: Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data. :param deep: Set to `True` to make a deep copy of the model. :Returns: **New model instance.** .. py:method:: model_dump(*, mode = 'python', include = None, exclude = None, context = None, by_alias = False, exclude_unset = False, exclude_defaults = False, exclude_none = False, round_trip = False, warnings = True, serialize_as_any = False) Usage docs: https://docs.pydantic.dev/2.9/concepts/serialization/#modelmodel_dump Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. :param mode: The mode in which `to_python` should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects. :param include: A set of fields to include in the output. :param exclude: A set of fields to exclude from the output. :param context: Additional context to pass to the serializer. :param by_alias: Whether to use the field's alias in the dictionary key if defined. :param exclude_unset: Whether to exclude fields that have not been explicitly set. :param exclude_defaults: Whether to exclude fields that are set to their default value. :param exclude_none: Whether to exclude fields that have a value of `None`. :param round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. :param warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. :param serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. :Returns: **A dictionary representation of the model.** .. py:method:: model_dump_json(*, indent = None, include = None, exclude = None, context = None, by_alias = False, exclude_unset = False, exclude_defaults = False, exclude_none = False, round_trip = False, warnings = True, serialize_as_any = False) Usage docs: https://docs.pydantic.dev/2.9/concepts/serialization/#modelmodel_dump_json Generates a JSON representation of the model using Pydantic's `to_json` method. :param indent: Indentation to use in the JSON output. If None is passed, the output will be compact. :param include: Field(s) to include in the JSON output. :param exclude: Field(s) to exclude from the JSON output. :param context: Additional context to pass to the serializer. :param by_alias: Whether to serialize using field aliases. :param exclude_unset: Whether to exclude fields that have not been explicitly set. :param exclude_defaults: Whether to exclude fields that are set to their default value. :param exclude_none: Whether to exclude fields that have a value of `None`. :param round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. :param warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. :param serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. :Returns: **A JSON string representation of the model.** .. py:method:: model_json_schema(by_alias = True, ref_template = DEFAULT_REF_TEMPLATE, schema_generator = GenerateJsonSchema, mode = 'validation') :classmethod: Generates a JSON schema for a model class. :param by_alias: Whether to use attribute aliases or not. :param ref_template: The reference template. :param schema_generator: To override the logic used to generate the JSON schema, as a subclass of `GenerateJsonSchema` with your desired modifications :param mode: The mode in which to generate the schema. :Returns: **The JSON schema for the given model class.** .. py:method:: model_parametrized_name(params) :classmethod: Compute the class name for parametrizations of generic classes. This method can be overridden to achieve a custom naming scheme for generic BaseModels. :param params: Tuple of types of the class. Given a generic class `Model` with 2 type variables and a concrete model `Model[str, int]`, the value `(str, int)` would be passed to `params`. :Returns: **String representing the new class where `params` are passed to `cls` as type variables.** :raises TypeError: Raised when trying to generate concrete names for non-generic models. .. py:method:: model_post_init(__context) Override this method to perform additional initialization after `__init__` and `model_construct`. This is useful if you want to do some validation that requires the entire model to be initialized. .. py:method:: model_rebuild(*, force = False, raise_errors = True, _parent_namespace_depth = 2, _types_namespace = None) :classmethod: Try to rebuild the pydantic-core schema for the model. This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails. :param force: Whether to force the rebuilding of the model schema, defaults to `False`. :param raise_errors: Whether to raise errors, defaults to `True`. :param _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. :param _types_namespace: The types namespace, defaults to `None`. :Returns: * **Returns `None` if the schema is already "complete" and rebuilding was not required.** * **If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.** .. py:method:: model_validate(obj, *, strict = None, from_attributes = None, context = None) :classmethod: Validate a pydantic model instance. :param obj: The object to validate. :param strict: Whether to enforce types strictly. :param from_attributes: Whether to extract data from object attributes. :param context: Additional context to pass to the validator. :raises ValidationError: If the object could not be validated. :Returns: **The validated model instance.** .. py:method:: model_validate_json(json_data, *, strict = None, context = None) :classmethod: Usage docs: https://docs.pydantic.dev/2.9/concepts/json/#json-parsing Validate the given JSON data against the Pydantic model. :param json_data: The JSON data to validate. :param strict: Whether to enforce types strictly. :param context: Extra variables to pass to the validator. :Returns: **The validated Pydantic model.** :raises ValidationError: If `json_data` is not a JSON string or the object could not be validated. .. py:method:: model_validate_strings(obj, *, strict = None, context = None) :classmethod: Validate the given object with string data against the Pydantic model. :param obj: The object containing string data to validate. :param strict: Whether to enforce types strictly. :param context: Extra variables to pass to the validator. :Returns: **The validated Pydantic model.** .. py:method:: __get_pydantic_core_schema__(source, handler, /) :classmethod: Hook into generating the model's CoreSchema. :param source: The class we are generating a schema for. This will generally be the same as the `cls` argument if this is a classmethod. :param handler: A callable that calls into Pydantic's internal CoreSchema generation logic. :Returns: **A `pydantic-core` `CoreSchema`.** .. py:method:: __get_pydantic_json_schema__(core_schema, handler, /) :classmethod: Hook into generating the model's JSON schema. :param core_schema: A `pydantic-core` CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`), or just call the handler with the original schema. :param handler: Call into Pydantic's internal JSON schema generation. This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema generation fails. Since this gets called by `BaseModel.model_json_schema` you can override the `schema_generator` argument to that function to change JSON schema generation globally for a type. :Returns: **A JSON schema, as a Python object.** .. py:method:: __pydantic_init_subclass__(**kwargs) :classmethod: This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass` only after the class is actually fully initialized. In particular, attributes like `model_fields` will be present when this is called. This is necessary because `__init_subclass__` will always be called by `type.__new__`, and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that `type.__new__` was called in such a manner that the class would already be sufficiently initialized. This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely, any kwargs passed to the class definition that aren't used internally by pydantic. :param \*\*kwargs: Any keyword arguments passed to the class definition that aren't used internally by pydantic. .. py:method:: __class_getitem__(typevar_values) :classmethod: .. py:method:: __copy__() Returns a shallow copy of the model. .. py:method:: __deepcopy__(memo = None) Returns a deep copy of the model. .. py:method:: __getattr__(item) .. py:method:: _check_frozen(name, value) .. py:method:: __getstate__() .. py:method:: __setstate__(state) .. py:method:: __eq__(other) .. py:method:: __init_subclass__(**kwargs) :classmethod: This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs. ```py from pydantic import BaseModel class MyModel(BaseModel, extra='allow'): ... ``` However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.) :param \*\*kwargs: Keyword arguments passed to the class definition, which set model_config .. note:: You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called *after* the class is fully initialized. .. py:method:: __iter__() So `dict(model)` works. .. py:method:: __repr__() .. py:method:: __repr_args__() .. py:attribute:: __repr_name__ .. py:attribute:: __repr_str__ .. py:attribute:: __pretty__ .. py:attribute:: __rich_repr__ .. py:method:: __str__() .. py:property:: __fields__ :type: dict[str, pydantic.fields.FieldInfo] .. py:property:: __fields_set__ :type: set[str] .. py:method:: dict(*, include = None, exclude = None, by_alias = False, exclude_unset = False, exclude_defaults = False, exclude_none = False) .. py:method:: json(*, include = None, exclude = None, by_alias = False, exclude_unset = False, exclude_defaults = False, exclude_none = False, encoder = PydanticUndefined, models_as_dict = PydanticUndefined, **dumps_kwargs) .. py:method:: parse_obj(obj) :classmethod: .. py:method:: parse_raw(b, *, content_type = None, encoding = 'utf8', proto = None, allow_pickle = False) :classmethod: .. py:method:: parse_file(path, *, content_type = None, encoding = 'utf8', proto = None, allow_pickle = False) :classmethod: .. py:method:: from_orm(obj) :classmethod: .. py:method:: construct(_fields_set = None, **values) :classmethod: .. py:method:: copy(*, include = None, exclude = None, update = None, deep = False) Returns a copy of the model. !!! warning "Deprecated" This method is now deprecated; use `model_copy` instead. If you need `include` or `exclude`, use: ```py data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) ``` :param include: Optional set or mapping specifying which fields to include in the copied model. :param exclude: Optional set or mapping specifying which fields to exclude in the copied model. :param update: Optional dictionary of field-value pairs to override field values in the copied model. :param deep: If True, the values of fields that are Pydantic models will be deep-copied. :Returns: **A copy of the model with included, excluded and updated fields as specified.** .. py:method:: schema(by_alias = True, ref_template = DEFAULT_REF_TEMPLATE) :classmethod: .. py:method:: schema_json(*, by_alias = True, ref_template = DEFAULT_REF_TEMPLATE, **dumps_kwargs) :classmethod: .. py:method:: validate(value) :classmethod: .. py:method:: update_forward_refs(**localns) :classmethod: .. py:method:: _iter(*args, **kwargs) .. py:method:: _copy_and_set_values(*args, **kwargs) .. py:method:: _get_value(*args, **kwargs) :classmethod: .. py:method:: _calculate_keys(*args, **kwargs) .. py:function:: predict(model, data, config) Predict on data used in the meta_cat.pipe :param model: The model. :type model: nn.Module :param data: Data in the format: [[, ], ...] :type data: list[tuple[list[int], int, Optional[int]]] :param config: Configuration for this meta_cat instance. :type config: ConfigMetaCAT :Returns: * **predictions** (*list[int]*) -- For each row of input data a prediction * **confidence** (*list[float]*) -- For each prediction a confidence value .. py:function:: train_model(model, data, config, save_dir_path = None) Trains a LSTM model and BERT with autocheckpoints :param model: The model :type model: nn.Module :param data: The data. :type data: list :param config: MetaCAT config. :type config: ConfigMetaCAT :param save_dir_path: The save dir path if required. Defaults to None. :type save_dir_path: Optional[str] :Returns: **dict** -- The classification report for the winner. :raises Exception: If auto-save is enabled but no save dir path is provided. .. py:function:: set_all_seeds(seed) .. py:function:: eval_model(model, data, config, tokenizer) Evaluate a trained model on the provided data :param model: The model. :type model: nn.Module :param data: The data. :type data: list :param config: The MetaCAT config. :type config: ConfigMetaCAT :param tokenizer: The tokenizer. :type tokenizer: TokenizerWrapperBase :Returns: **dict** -- Results (precision, recall, f1, examples, confusion matrix) .. py:function:: prepare_from_json(data, cntx_left, cntx_right, tokenizer, cui_filter = None, replace_center = None, prerequisites = {}, lowercase = True) Convert the data from a json format into a CSV-like format for training. This function is not very efficient (the one working with documents as part of the meta_cat.pipe method is much better). If your dataset is > 1M documents think about rewriting this function - but would be strange to have more than 1M manually annotated documents. :param data: Loaded output of MedCATtrainer. If we have a `my_export.json` from MedCATtrainer, than data = json.load(). :type data: dict :param cntx_left: Size of context to get from the left of the concept :type cntx_left: int :param cntx_right: Size of context to get from the right of the concept :type cntx_right: int :param tokenizer: Something to split text into tokens for the LSTM/BERT/whatever meta models. :type tokenizer: TokenizerWrapperBase :param replace_center: If not None the center word (concept) will be replaced with whatever this is. :type replace_center: Optional[str] :param prerequisites: A map of prerequisites, for example our data has two meta-annotations (experiencer, negation). Assume I want to create a dataset for `negation` but only in those cases where `experiencer=patient`, my prerequisites would be: {'Experiencer': 'Patient'} - Take care that the CASE has to match whatever is in the data. Defaults to `{}`. :type prerequisites: dict :param lowercase: Should the text be lowercased before tokenization. Defaults to True. :type lowercase: bool :param cui_filter: CUI filter if set. Defaults to None. :type cui_filter: Optional[set] :Returns: **out_data** (*dict*) -- Example: {'category_name': [('', '<[tokens]>', ''), ...], ...} .. py:function:: encode_category_values(data, existing_category_value2id = None, category_undersample=None) Converts the category values in the data outputted by `prepare_from_json` into integer values. :param data: Output of `prepare_from_json`. :type data: dict :param existing_category_value2id: Map from category_value to id (old/existing). :type existing_category_value2id: Optional[dict] :param category_undersample: Name of class that should be used to undersample the data (for 2 phase learning) :Returns: * **dict** -- New data with integers inplace of strings for category values. * **dict** -- New undersampled data (for 2 phase learning) with integers inplace of strings for category values * **dict** -- Map from category value to ID for all categories in the data. .. py:function:: prepare_for_oversampled_data(data, tokenizer) Convert the data from a json format into a CSV-like format for training. This function is not very efficient (the one working with documents as part of the meta_cat.pipe method is much better). If your dataset is > 1M documents think about rewriting this function - but would be strange to have more than 1M manually annotated documents. :param data: Oversampled data expected in the following format: [[['text','of','the','document'], [index of medical entity], "label" ], ['text','of','the','document'], [index of medical entity], "label" ]] :type data: list :param tokenizer: Something to split text into tokens for the LSTM/BERT/whatever meta models. :type tokenizer: TokenizerWrapperBase :Returns: **data_sampled** (*list*) -- The processed data in the format that can be merged with the output from prepare_from_json. [[<[tokens]>, [index of medical entity], "label" ], <[tokens]>, [index of medical entity], "label" ]] .. py:class:: AddonComponent Bases: :py:obj:`medcat2.components.types.BaseComponent`, :py:obj:`Protocol` Base/abstract addon component class. .. py:attribute:: NAME_PREFIX :type: str :value: 'addon_' .. py:attribute:: NAME_SPLITTER :type: str :value: '.' .. py:attribute:: config :type: medcat2.config.config.ComponentConfig .. py:property:: addon_type :type: str .. py:method:: is_core() Whether the component is a core component or not. :Returns: **bool** -- Whether this is a core component. .. py:method:: get_folder_name() .. py:property:: full_name :type: str Name with the component type (e.g ner, linking, meta). .. py:property:: include_in_output :type: bool .. py:method:: get_output_key_val(ent) .. py:property:: name :type: str The name of the component. .. py:method:: __call__(doc) .. py:method:: get_init_args(tokenizer, cdb, vocab, model_load_path) :classmethod: Get the init arguments for the component. :param tokenizer: The tokenizer. :type tokenizer: BaseTokenizer :param cdb: The CDB. :type cdb: CDB :param vocab: The Vocab. :type vocab: Vocab :param model_load_path: The model load path (or None). :type model_load_path: Optional[str] :Returns: **list[Any]** -- The list of init arguments. .. py:method:: get_init_kwargs(tokenizer, cdb, vocab, model_load_path) :classmethod: Get init keyword arguments for the component. :param tokenizer: The tokenizer. :type tokenizer: BaseTokenizer :param cdb: The CDB. :type cdb: CDB :param vocab: The Vocab. :type vocab: Vocab :param model_load_path: The model load path (or None). :type model_load_path: Optional[str] :Returns: **dict[str, Any]** -- The keywrod arguments. .. py:attribute:: __slots__ :value: () .. py:attribute:: _is_protocol :value: True .. py:attribute:: _is_runtime_protocol :value: False .. py:method:: __init_subclass__(*args, **kwargs) :classmethod: .. py:method:: __class_getitem__(params) :classmethod: .. py:class:: TokenizerWrapperBase(hf_tokenizer = None) Bases: :py:obj:`abc.ABC` Helper class that provides a standard way to create an ABC using inheritance. .. py:attribute:: name :type: str .. py:method:: __init__(hf_tokenizer = None) .. py:attribute:: hf_tokenizers :value: None .. py:method:: __call__(text: str) -> dict __call__(text: list[str]) -> list[dict] .. py:method:: save(dir_path) :abstractmethod: .. py:method:: load(dir_path, model_variant = '', **kwargs) :classmethod: :abstractmethod: .. py:method:: get_size() :abstractmethod: .. py:method:: token_to_id(token) :abstractmethod: .. py:method:: get_pad_id() :abstractmethod: .. py:method:: ensure_tokenizer() .. py:attribute:: __slots__ :value: () .. py:function:: serialise(serialiser_type, obj, target_folder, overwrite = False) Serialise an object based on the specified serialiser type. :param serialiser_type: The serialiser type. :type serialiser_type: Union[str, AvailableSerialisers] :param obj: The object to serialise. :type obj: Serialisable :param target_folder: The folder to serialise into. :type target_folder: str :param overwrite: Whether to allow overwriting. Defaults to False. :type overwrite: bool .. py:function:: deserialise(folder_path, ignore_folders_prefix = set(), ignore_folders_suffix = set(), **init_kwargs) Deserialise contents of a folder. Extra init keyword arguments can be provided if needed. This method finds the serialiser to be used based on the files on disk. :param folder_path: The folder to serialise. :type folder_path: str :param ignore_folders_prefix: The prefixes of folders to ignore. :type ignore_folders_prefix: set[str] :param ignore_folders_suffix: The suffixes of folders to ignore. :type ignore_folders_suffix: set[str] :Returns: **Serialisable** -- The deserialised object. .. py:class:: AbstractSerialisable The abstract serialisable base class. This defines some common defaults. .. py:method:: get_strategy() .. py:method:: get_init_attrs() :classmethod: .. py:method:: ignore_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:method:: __eq__(other) .. py:class:: SerialisingStrategy Bases: :py:obj:`enum.Enum` Describes the strategy for serialising. .. py:attribute:: SERIALISABLE_ONLY Only serialise attributes that are of Serialisable type .. py:attribute:: SERIALISABLES_AND_DICT Serialise attributes that are Serialisable as well as the rest of .__dict__ .. py:attribute:: DICT_ONLY Only include the object's .__dict__ .. py:attribute:: MANUAL Use manual serialisation defined by the object itself. NOTE: In this case, most of the logic defined within here will likely be ignored. .. py:method:: _is_suitable_in_dict(attr_name, attr, obj) .. py:method:: _is_suitable_part(attr_name, part, obj) .. py:method:: _iter_obj_items(obj) .. py:method:: _iter_obj_values(obj) .. py:method:: get_dict(obj) Gets the appropriate parts of the __dict__ of the object. I.e this filters out parts that shouldn't be included. :param obj: The serialisable object. :type obj: Serialisable :Returns: **dict[str, Any]** -- The filtered attributes map. .. py:method:: get_parts(obj) Gets the matching serialisable parts of the object. This includes only serialisable parts, and only if specified by the strategy. :Returns: **list[tuple[Serialisable, str]]** -- The serialisable parts with names. .. py:method:: __new__(value) .. py:method:: _generate_next_value_(start, count, last_values) Generate the next value when not given. name: the name of the member start: the initial start value or None count: the number of existing members last_value: the last value assigned or None .. py:method:: _missing_(value) :classmethod: .. py:method:: __repr__() .. py:method:: __str__() .. py:method:: __dir__() Returns all members and all public methods .. py:method:: __format__(format_spec) Returns format using actual value type unless __str__ has been overridden. .. py:method:: __hash__() .. py:method:: __reduce_ex__(proto) .. py:method:: name() The name of the Enum member. .. py:method:: value() The value of the Enum member. .. py:class:: MutableDocument Bases: :py:obj:`Protocol` The mutable parts of the document. Represents parts of the document that can / should be changed by the various components. .. py:property:: base :type: BaseDocument The base document. .. py:property:: final_ents :type: list[MutableEntity] The linked entities associated with the document. This should be set by the linker. .. py:property:: all_ents :type: list[MutableEntity] All entities recognised by NER. This should be set by the NER component. .. py:method:: __iter__() .. py:method:: __getitem__(index: int) -> MutableToken __getitem__(index: slice) -> MutableEntity .. py:method:: get_tokens(start_index, end_index) Get the tokens that span the specified character indices. :param start_index: The starting character index. :type start_index: int :param end_index: The ending character index. :type end_index: int :Returns: **list[MutableToken]** -- The list of tokens. .. py:method:: set_addon_data(path, val) Used to add arbitrary data to the entity. This is generally used by addons to keep track of their data. NB! The path used needs to be registered using the `register_addon_path` class method. :param path: The data ID / path. :type path: str :param val: The value to be added. :type val: Any .. py:method:: get_addon_data(path) Get data added to the entity. See `add_data` for details. :param path: The data ID / path. :type path: str :Returns: **Any** -- The stored value. .. py:method:: register_addon_path(path, def_val = None, force = True) :classmethod: Register a custom/arbitrary data path. This can be used to store arbitrary data along with the entity for use in an addon (e.g MetaCAT). PS: If using this, it is important to use paths namespaced to the component you're using in order to avoid conflicts. :param path: The path to be used. Should be prefixed by component name (e.g `meta_cat_id` for an ID tied to the `meta_cat` addon) :type path: str :param def_val: Default value. Defaults to `None`. :type def_val: Any :param force: Whether to forcefully add the value. Defaults to True. :type force: bool .. py:attribute:: __slots__ :value: () .. py:attribute:: _is_protocol :value: True .. py:attribute:: _is_runtime_protocol :value: False .. py:method:: __init_subclass__(*args, **kwargs) :classmethod: .. py:method:: __class_getitem__(params) :classmethod: .. py:class:: MutableEntity Bases: :py:obj:`Protocol` The mutable part of an entity. This represent the changeable part of an entnity. That is, parts that should be changed by the various components. .. py:property:: base :type: BaseEntity The base / static entity part. .. py:property:: detected_name :type: str The detected name (if any) for this entity. This should be set by the NER component. .. py:method:: set_addon_data(path, val) Used to add arbitrary data to the entity. This is generally used by addons to keep track of their data. NB! The path used needs to be registered using the `register_addon_path` class method. :param path: The data ID / path. :type path: str :param val: The value to be added. :type val: Any .. py:method:: get_addon_data(path) Get data added to the entity. See `add_data` for details. :param path: The data ID / path. :type path: str :Returns: **Any** -- The stored value. .. py:property:: link_candidates :type: list[str] The candidates for the detected name (if any) for this entity. This should be set by the NER component. .. py:property:: context_similarity :type: float The context similarity of the lnked entity. This should be set by the linker component. .. py:property:: confidence :type: float The confidence for the lnked entity. NOTE: This seems to be unused! .. py:property:: cui :type: str The CUI of the lnked entity. This should be set by the linker component. .. py:property:: id :type: int The ID of the entity within the document. This counts all the entities recognised, not just ones that were successfully linked. This should be set by the NER. .. py:method:: register_addon_path(path, def_val = None, force = True) :classmethod: Register a custom/arbitrary data path. This can be used to store arbitrary data along with the entity for use in an addon (e.g MetaCAT). PS: If using this, it is important to use paths namespaced to the component you're using in order to avoid conflicts. :param path: The path to be used. Should be prefixed by component name (e.g `meta_cat_id` for an ID tied to the `meta_cat` addon) :type path: str :param def_val: Default value. Defaults to `None`. :type def_val: Any :param force: Whether to forcefully add the value. Defaults to True. :type force: bool .. py:method:: __iter__() .. py:method:: __len__() .. py:attribute:: __slots__ :value: () .. py:attribute:: _is_protocol :value: True .. py:attribute:: _is_runtime_protocol :value: False .. py:method:: __init_subclass__(*args, **kwargs) :classmethod: .. py:method:: __class_getitem__(params) :classmethod: .. py:class:: CDB(config) Bases: :py:obj:`medcat2.storage.serialisables.AbstractSerialisable` The abstract serialisable base class. This defines some common defaults. .. py:method:: __init__(config) .. py:attribute:: config .. py:attribute:: cui2info :type: dict[str, medcat2.cdb.concepts.CUIInfo] .. py:attribute:: name2info :type: dict[str, medcat2.cdb.concepts.NameInfo] .. py:attribute:: type_id2info :type: dict[str, medcat2.cdb.concepts.TypeInfo] .. py:attribute:: token_counts :type: dict[str, int] .. py:attribute:: addl_info :type: dict[str, Any] .. py:attribute:: _subnames :type: set[str] .. py:attribute:: is_dirty :value: False .. py:attribute:: has_changed_names :value: False .. py:method:: get_init_attrs() :classmethod: .. py:method:: _reset_subnames() .. py:method:: has_subname(name) Whether the CDB has the specified subname. :param name: The subname to check. :type name: str :Returns: **bool** -- Whether the subname is present in this CDB. .. py:method:: get_name(cui) Returns preferred name if it exists, otherwise it will return the longest name assigned to the concept. :param cui: Concept ID or unique identifier in this database. :type cui: str :Returns: **str** -- The name of the concept. .. py:method:: weighted_average_function(step) Get the weighted average for steop. :param step: The steop. :type step: int :Returns: **float** -- The weighted average. .. py:method:: add_types(types) Add type info to CDB. :param types: The raw type info. :type types: Iterable[tuple[str, str]] .. py:method:: add_names(cui, names, name_status = ST.AUTOMATIC, full_build = False) Adds a name to an existing concept. :param cui: Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally. :type cui: str :param names: 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' :type names: dict[str, NameDescriptor] :param name_status: One of `P`, `N`, `A`. Defaults to 'A'. :type name_status: str :param full_build: 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`). :type full_build: bool .. py:method:: _add_concept_names(cui, names, name_status) .. py:method:: _add_full_build(cui, names, ontologies, description, type_ids) .. py:method:: _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. :param cui: Concept ID or unique identifier in this database, all concepts that have the same CUI will be merged internally. :type cui: str :param names: 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' :type names: dict[str, NameDescriptor] :param ontologies: ontologies in which the concept exists (e.g. SNOMEDCT, HPO) :type ontologies: set[str] :param name_status: One of `P`, `N`, `A` :type name_status: str :param type_ids: Semantic type identifier (have a look at TUIs in UMLS or SNOMED-CT) :type type_ids: set[str] :param description: Description of this concept. :type description: str :param full_build: 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`). :type full_build: bool .. py:method:: 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. .. py:method:: _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. :param cui: Concept ID or unique identifier in this database. :type cui: str :param names: Names to be removed (e.g list, set, or even a dict (in which case keys will be used)). :type names: Iterable[str] .. py:method:: __eq__(other) .. py:method:: get_strategy() .. py:method:: ignore_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:class:: Vocab Bases: :py:obj:`medcat2.storage.serialisables.AbstractSerialisable` Vocabulary used to store word embeddings for context similarity calculation. Also used by the spell checker - but not for fixing the spelling only for checking is something correct. Properties: vocab (dict[str, WordDescriptor]): Map from word to attributes, e.g. {'house': {'vector': , 'count': , ...}, ...} index2word (dict[int, str]): From word to an index - used for negative sampling vec_index2word (dict): Same as index2word but only words that have vectors .. py:method:: __init__() .. py:attribute:: vocab :type: dict[str, WordDescriptor] .. py:attribute:: index2word :type: dict[int, str] .. py:attribute:: vec_index2word :type: dict[int, str] .. py:attribute:: cum_probs :type: numpy.ndarray .. py:method:: inc_or_add(word, cnt = 1, vec = None) Add a word or increase its count. :param word: Word to be added :type word: str :param cnt: By how much should the count be increased, or to what should it be set if a new word. (Default value = 1) :type cnt: int :param vec: Word vector (Default value = None) :type vec: Optional[np.ndarray] .. py:method:: remove_all_vectors() Remove all stored vector representations. .. py:method:: remove_words_below_cnt(cnt) Remove all words with frequency below cnt. :param cnt: Word count limit. :type cnt: int .. py:method:: _rebuild_index() .. py:method:: inc_wc(word, cnt = 1) Incraese word count by cnt. :param word: For which word to increase the count :type word: str :param cnt: By how muhc to increase the count (Default value = 1) :type cnt: int .. py:method:: add_vec(word, vec) Add vector to a word. :param word: To which word to add the vector. :type word: str :param vec: The vector to add. :type vec: np.ndarray .. py:method:: reset_counts(cnt = 1) Reset the count for all word to cnt. :param cnt: New count for all words in the vocab. (Default value = 1) :type cnt: int .. py:method:: update_counts(tokens) Given a list of tokens update counts for words in the vocab. :param tokens: Usually a large block of text split into tokens/words. :type tokens: list[str] .. py:method:: add_word(word, cnt = 1, vec = None, replace = True) Add a word to the vocabulary :param word: The word to be added, it should be lemmatized and lowercased :type word: str :param cnt: Count of this word in your dataset (Default value = 1) :type cnt: int :param vec: The vector representation of the word (Default value = None) :type vec: Optional[np.ndarray] :param replace: Will replace old vector representation (Default value = True) :type replace: bool .. py:method:: add_words(path, replace = True) Adds words to the vocab from a file, the file is required to have the following format (vec being optional): [ ] e.g. one line: the word house with 3 dimensional vectors house 34444 0.3232 0.123213 1.231231 :param path: path to the file with words and vectors :type path: str :param replace: existing words in the vocabulary will be replaced. Defaults to True. :type replace: bool .. py:method:: init_cumsums() Initialise cumulative sums. This is in place of the unigram table. But similarly to it, this approach allows generating a list of indices that match the probabilistic distribution expected as per the word counts of each word. .. py:method:: get_negative_samples(n = 6, ignore_punct_and_num = False) Get N negative samples. :param n: How many words to return (Default value = 6) :type n: int :param ignore_punct_and_num: Whether to ignore punctuation and numbers. Defaults to False. :type ignore_punct_and_num: bool :raises Exception: If no unigram table is present. :Returns: **list[int]** -- Indices for words in this vocabulary. .. py:method:: get_vectors(indices) .. py:method:: __getitem__(word) .. py:method:: vec(word) .. py:method:: count(word) .. py:method:: item(word) .. py:method:: __contains__(word) .. py:method:: __eq__(other) .. py:method:: get_strategy() .. py:method:: get_init_attrs() :classmethod: .. py:method:: ignore_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:data:: logger .. py:data:: _META_ANNS_PATH :value: 'meta_cat_meta_anns' .. py:data:: _SHARE_TOKENS_PATH :value: 'meta_cat_share_tokens' .. py:class:: MedCATTrainerExportDocument Bases: :py:obj:`TypedDict` dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) .. py:attribute:: name :type: str .. py:attribute:: confidence :type: float .. py:attribute:: value :type: str .. py:method:: __contains__() True if the dictionary has the specified key, else False. .. py:method:: __delattr__() Implement delattr(self, name). .. py:method:: __delitem__() Delete self[key]. .. py:method:: __dir__() Default dir() implementation. .. py:method:: __eq__() Return self==value. .. py:method:: __format__() Default object formatter. .. py:method:: __ge__() Return self>=value. .. py:method:: __getattribute__() Return getattr(self, name). .. py:method:: __getitem__() x.__getitem__(y) <==> x[y] .. py:method:: __gt__() Return self>value. .. py:method:: __init__() Initialize self. See help(type(self)) for accurate signature. .. py:method:: __ior__() Return self|=value. .. py:method:: __iter__() Implement iter(self). .. py:method:: __le__() Return self<=value. .. py:method:: __len__() Return len(self). .. py:method:: __lt__() Return self size of D in memory, in bytes .. py:method:: __str__() Return str(self). .. py:method:: __subclasshook__() Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). .. py:method:: clear() D.clear() -> None. Remove all items from D. .. py:method:: copy() D.copy() -> a shallow copy of D .. py:method:: get() Return the value for key if key is in the dictionary, else default. .. py:method:: items() D.items() -> a set-like object providing a view on D's items .. py:method:: keys() D.keys() -> a set-like object providing a view on D's keys .. py:method:: pop() D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If the key is not found, return the default if given; otherwise, raise a KeyError. .. py:method:: popitem() Remove and return a (key, value) pair as a 2-tuple. Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty. .. py:method:: setdefault() Insert key with a value of default if key is not in the dictionary. Return the value for key if key is in the dictionary, else default. .. py:method:: update() D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] .. py:method:: values() D.values() -> an object providing a view on D's values .. py:class:: MetaCATAddon(config, base_tokenizer, meta_cat) Bases: :py:obj:`medcat2.components.addons.addons.AddonComponent` Base/abstract addon component class. .. py:attribute:: addon_type :value: 'meta_cat' .. py:attribute:: output_key :value: 'meta_anns' .. py:attribute:: config :type: medcat2.config.config_meta_cat.ConfigMetaCAT .. py:method:: __init__(config, base_tokenizer, meta_cat) .. py:attribute:: base_tokenizer .. py:attribute:: _mc .. py:attribute:: _name .. py:property:: mc :type: MetaCAT .. py:method:: create_new(config, base_tokenizer, tokenizer) :classmethod: Factory method to create a new MetaCATAddon instance. .. py:method:: load_existing(cnf, base_tokenizer, load_path) :classmethod: Factory method to load an existing MetaCATAddon from disk. .. py:property:: name :type: str The name of the component. .. py:method:: _init_tokenizer(cnf, pack_save_path) .. py:method:: __call__(doc) .. py:method:: get_init_args(tokenizer, cdb, vocab, model_load_path) :classmethod: Get the init arguments for the component. :param tokenizer: The tokenizer. :type tokenizer: BaseTokenizer :param cdb: The CDB. :type cdb: CDB :param vocab: The Vocab. :type vocab: Vocab :param model_load_path: The model load path (or None). :type model_load_path: Optional[str] :Returns: **list[Any]** -- The list of init arguments. .. py:method:: get_init_kwargs(tokenizer, cdb, vocab, model_load_path) :classmethod: Get init keyword arguments for the component. :param tokenizer: The tokenizer. :type tokenizer: BaseTokenizer :param cdb: The CDB. :type cdb: CDB :param vocab: The Vocab. :type vocab: Vocab :param model_load_path: The model load path (or None). :type model_load_path: Optional[str] :Returns: **dict[str, Any]** -- The keywrod arguments. .. py:method:: load(folder_path) .. py:method:: _load_tokenizer(tokenizer_folder) .. py:method:: _get_meta_cat_and_tokenizer_paths(folder_path) :classmethod: .. py:method:: save(folder_path) .. py:method:: _init_data_paths() .. py:property:: include_in_output :type: bool .. py:method:: get_output_key_val(ent) .. py:method:: serialise_to(folder_path) .. py:method:: deserialise_from(folder_path, **init_kwargs) :classmethod: .. py:method:: get_strategy() .. py:method:: get_init_attrs() :classmethod: .. py:method:: ignore_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:attribute:: NAME_PREFIX :type: str :value: 'addon_' .. py:attribute:: NAME_SPLITTER :type: str :value: '.' .. py:method:: is_core() Whether the component is a core component or not. :Returns: **bool** -- Whether this is a core component. .. py:method:: get_folder_name() .. py:property:: full_name :type: str Name with the component type (e.g ner, linking, meta). .. py:attribute:: __slots__ :value: () .. py:attribute:: _is_protocol :value: True .. py:attribute:: _is_runtime_protocol :value: False .. py:method:: __init_subclass__(*args, **kwargs) :classmethod: .. py:method:: __class_getitem__(params) :classmethod: .. py:class:: MetaCAT(tokenizer = None, embeddings = None, config = None, _model_state_dict = None) Bases: :py:obj:`medcat2.storage.serialisables.AbstractSerialisable` The MetaCAT class used for training 'Meta-Annotation' models, i.e. annotations of clinical concept annotations. These are also known as properties or attributes of recognise entities sin similar tools such as MetaMap and cTakes. This is a flexible model agnostic class that can learns any meta-annotation task, i.e. any multi-class classification task for recognised terms. :param tokenizer: The Huggingface tokenizer instance. This can be a pre-trained tokenzier instance from a BERT-style model, or trained from scratch for the Bi-LSTM (w. attention) model that is currentl used in most deployments. :type tokenizer: TokenizerWrapperBase :param embeddings: embedding mapping (sub)word input id n-dim (sub)word embedding. :type embeddings: Tensor, numpy.ndarray :param config: the configuration for MetaCAT. Param descriptions available in ConfigMetaCAT docs. :type config: ConfigMetaCAT .. py:attribute:: name :value: 'meta_cat' .. py:attribute:: _component_lock .. py:method:: get_init_attrs() :classmethod: .. py:method:: ignore_attrs() :classmethod: .. py:method:: include_properties() :classmethod: .. py:property:: _model_state_dict .. py:method:: __init__(tokenizer = None, embeddings = None, config = None, _model_state_dict = None) .. py:attribute:: config :value: None .. py:attribute:: tokenizer :value: None .. py:attribute:: embeddings .. py:attribute:: model .. py:method:: get_model(embeddings) Get the model :param embeddings: The embedding densor :type embeddings: Optional[Tensor] :raises ValueError: If the meta model is not LSTM or BERT :Returns: **nn.Module** -- The module .. py:method:: get_hash() A partial hash trying to catch differences between models. :Returns: **str** -- The hex hash. .. py:method:: train_from_json(json_path, save_dir_path = None, data_oversampled = None, overwrite = False) Train or continue training a model give a json_path containing a MedCATtrainer export. It will continue training if an existing model is loaded or start new training if the model is blank/new. :param json_path: Path/Paths to a MedCATtrainer export containing the meta_annotations we want to train for. :type json_path: Union[str, list] :param save_dir_path: In case we have aut_save_model (meaning during the training the best model will be saved) we need to set a save path. Defaults to `None`. :type save_dir_path: Optional[str] :param data_oversampled: In case of oversampling being performed, the data will be passed in the parameter allowing the model to be trained on original + synthetic data. :type data_oversampled: Optional[list] :param overwrite: Whether to allow overwriting the file if/when appropriate. :type overwrite: bool :Returns: **dict** -- The resulting report. .. py:method:: train_raw(data_loaded, save_dir_path = None, data_oversampled = None, overwrite = False) Train or continue training a model given raw data. It will continue training if an existing model is loaded or start new training if the model is blank/new. The raw data is expected in the following format: { 'projects': [ # list of projects { 'name': '', 'documents': [ # list of documents { 'name': '', 'text': '', 'annotations': [ # list of annotations { # start index of the annotation 'start': -1, 'end': 1, # end index of the annotation 'cui': 'cui', 'value': '' }, ... ], }, ... ] }, ... ] } :param data_loaded: The raw data we want to train for. :type data_loaded: dict :param save_dir_path: In case we have aut_save_model (meaning during the training the best model will be saved) we need to set a save path. Defaults to `None`. :type save_dir_path: Optional[str] :param data_oversampled: In case of oversampling being performed, the data will be passed in the parameter allowing the model to be trained on original + synthetic data. The format of which is expected: [[['text','of','the','document'], [index of medical entity], "label" ], ['text','of','the','document'], [index of medical entity], "label" ]] :type data_oversampled: Optional[list] :param overwrite: Whether to allow overwriting the file if/when appropriate. :type overwrite: bool :Returns: **dict** -- The resulting report. :raises Exception: If no save path is specified, or category name not in data. :raises AssertionError: If no tokeniser is set :raises FileNotFoundError: If phase_number is set to 2 and model.dat file is not found :raises KeyError: If phase_number is set to 2 and model.dat file contains mismatched architecture .. py:method:: eval(json_path) Evaluate from json. :param json_path: The json file ath :type json_path: str :Returns: **dict** -- The resulting model dict :raises AssertionError: If self.tokenizer :raises Exception: If the category name does not exist .. py:method:: get_ents(doc) .. py:method:: prepare_document(doc, input_ids, offset_mapping, lowercase) Prepares document. :param doc: The document :type doc: Doc :param input_ids: Input ids :type input_ids: list :param offset_mapping: Offset mappings :type offset_mapping: list :param lowercase: Whether to use lower case replace center :type lowercase: bool :Returns: **tuple[dict, list]** -- Entity id to index mapping and Samples .. py:method:: batch_generator(stream, batch_size_chars) :staticmethod: Generator for batch of documents. :param stream: The document stream :type stream: Iterable[MutableDocument] :param batch_size_chars: Number of characters per batch :type batch_size_chars: int :Yields: *list[MutableDocument]* -- The batch of documents. .. py:method:: _set_meta_anns(doc, id2category_value) .. py:method:: __call__(doc) Process one document, used in the spacy pipeline for sequential document processing. :param doc: A spacy document :type doc: Doc :Returns: **Doc** -- The same spacy document. .. py:method:: get_model_card(as_dict = False) A minimal model card. :param as_dict: Return the model card as a dictionary instead of a str. Defaults to `False`. :type as_dict: bool :Returns: **Union[str, dict]** -- An indented JSON object. OR A JSON object in dict form. .. py:method:: __repr__() Prints the model_card for this MetaCAT instance. :Returns: * **the 'Model Card' for this MetaCAT instance. This includes NER+L** * **config and any MetaCATs** .. py:method:: get_strategy() .. py:method:: __eq__(other) .. py:exception:: MisconfiguredMetaCATException Bases: :py:obj:`ValueError` Inappropriate argument value (of correct type). .. py:method:: ____(*args) .. py:class:: __cause__ exception cause .. py:class:: __context__ exception context .. py:method:: __delattr__() Implement delattr(self, name). .. py:method:: __dir__() Default dir() implementation. .. py:method:: __eq__() Return self==value. .. py:method:: __format__() Default object formatter. .. py:method:: __ge__() Return self>=value. .. py:method:: __getattribute__() Return getattr(self, name). .. py:method:: __gt__() Return self>value. .. py:method:: __hash__() Return hash(self). .. py:method:: __init__() Initialize self. See help(type(self)) for accurate signature. .. py:method:: __le__() Return self<=value. .. py:method:: __lt__() Return self