|
| 1 | +import logging |
| 2 | +import pandas as pd |
| 3 | +from typing import Dict, Optional, final, List |
| 4 | + |
| 5 | +from app import __version__ as app_version |
| 6 | +from app.model_services.medcat_model import MedCATModel |
| 7 | +from app.config import Settings |
| 8 | +from app.domain import ModelCard, ModelType |
| 9 | + |
| 10 | +logger = logging.getLogger("cms") |
| 11 | + |
| 12 | + |
| 13 | +@final |
| 14 | +class MedCATModelOpcs4(MedCATModel): |
| 15 | + """A model service for MedCAT OPCS-4 models.""" |
| 16 | + |
| 17 | + OPCS4_KEY = "opcs4" |
| 18 | + |
| 19 | + def __init__( |
| 20 | + self, |
| 21 | + config: Settings, |
| 22 | + model_parent_dir: Optional[str] = None, |
| 23 | + enable_trainer: Optional[bool] = None, |
| 24 | + model_name: Optional[str] = None, |
| 25 | + base_model_file: Optional[str] = None, |
| 26 | + ) -> None: |
| 27 | + """ |
| 28 | + Initialises the MedCAT OPCS-4 model service with specified configurations. |
| 29 | +
|
| 30 | + Args: |
| 31 | + config (Settings): The configuration for the model service. |
| 32 | + model_parent_dir (Optional[str]): The directory where the model package is stored. Defaults to None. |
| 33 | + enable_trainer (Optional[bool]): The flag to enable or disable trainers. Defaults to None. |
| 34 | + model_name (Optional[str]): The name of the model. Defaults to None. |
| 35 | + base_model_file (Optional[str]): The model package file name. Defaults to None. |
| 36 | + """ |
| 37 | + super().__init__( |
| 38 | + config, |
| 39 | + model_parent_dir=model_parent_dir, |
| 40 | + enable_trainer=enable_trainer, |
| 41 | + model_name=model_name, |
| 42 | + base_model_file=base_model_file, |
| 43 | + ) |
| 44 | + self.model_name = model_name or "OPCS-4 MedCAT model" |
| 45 | + |
| 46 | + @property |
| 47 | + def api_version(self) -> str: |
| 48 | + """Getter for the API version of the model service.""" |
| 49 | + |
| 50 | + # APP version is used although each model service could have its own API versioning |
| 51 | + return app_version |
| 52 | + |
| 53 | + def info(self) -> ModelCard: |
| 54 | + """ |
| 55 | + Retrieves information about the MedCAT OPCS-4 model. |
| 56 | +
|
| 57 | + Returns: |
| 58 | + ModelCard: A card containing information about the MedCAT OPCS-4 model. |
| 59 | + """ |
| 60 | + |
| 61 | + return ModelCard( |
| 62 | + model_description=self.model_name, |
| 63 | + model_type=ModelType.MEDCAT_OPCS4, |
| 64 | + api_version=self.api_version, |
| 65 | + model_card=self.model.get_model_card(as_dict=True), |
| 66 | + ) |
| 67 | + |
| 68 | + def get_records_from_doc(self, doc: Dict) -> List[Dict]: |
| 69 | + """ |
| 70 | + Extracts and formats entity records from a document dictionary. |
| 71 | +
|
| 72 | + Args: |
| 73 | + doc (Dict): The document dictionary containing extracted named entities. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + List[Dict]: A list of formatted entity records. |
| 77 | + """ |
| 78 | + |
| 79 | + df = pd.DataFrame(doc["entities"].values()) |
| 80 | + |
| 81 | + if df.empty: |
| 82 | + df = pd.DataFrame(columns=["label_name", "label_id", "start", "end", "accuracy"]) |
| 83 | + else: |
| 84 | + new_rows = [] |
| 85 | + for _, row in df.iterrows(): |
| 86 | + if self.OPCS4_KEY not in row or not row[self.OPCS4_KEY]: |
| 87 | + logger.debug("No mapped OPCS-4 code associated with the entity: %s", row) |
| 88 | + else: |
| 89 | + for opcs4 in row[self.OPCS4_KEY]: |
| 90 | + output_row = row.copy() |
| 91 | + if isinstance(opcs4, str): |
| 92 | + output_row[self.OPCS4_KEY] = opcs4 |
| 93 | + elif isinstance(opcs4, dict): |
| 94 | + output_row[self.OPCS4_KEY] = opcs4.get("code") |
| 95 | + output_row["pretty_name"] = opcs4.get("name") |
| 96 | + elif isinstance(opcs4, list) and opcs4: |
| 97 | + output_row[self.OPCS4_KEY] = opcs4[-1] |
| 98 | + else: |
| 99 | + logger.error("Unknown format for the OPCS-4 code(s): %s", opcs4) |
| 100 | + if "athena_ids" in output_row and output_row["athena_ids"]: |
| 101 | + output_row["athena_ids"] = [ |
| 102 | + athena_id["code"] for athena_id in output_row["athena_ids"] |
| 103 | + ] |
| 104 | + new_rows.append(output_row) |
| 105 | + if new_rows: |
| 106 | + df = pd.DataFrame(new_rows) |
| 107 | + df.rename( |
| 108 | + columns={ |
| 109 | + "pretty_name": "label_name", |
| 110 | + self.OPCS4_KEY: "label_id", |
| 111 | + "types": "categories", |
| 112 | + "acc": "accuracy", |
| 113 | + "athena_ids": "athena_ids", |
| 114 | + }, |
| 115 | + inplace=True, |
| 116 | + ) |
| 117 | + df = self._retrieve_meta_annotations(df) |
| 118 | + else: |
| 119 | + df = pd.DataFrame(columns=["label_name", "label_id", "start", "end", "accuracy"]) |
| 120 | + records = df.to_dict("records") |
| 121 | + return records |
0 commit comments