|
| 1 | +""" |
| 2 | +GLiNER-based PII annotator for DataFog. |
| 3 | +
|
| 4 | +This module provides a GLiNER-based annotator for detecting PII entities in text. |
| 5 | +GLiNER is a Generalist model for Named Entity Recognition that can identify any entity types. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +from typing import Any, Dict, List, Optional |
| 10 | + |
| 11 | +from pydantic import BaseModel, ConfigDict |
| 12 | + |
| 13 | +# Default entity types for PII detection using GLiNER |
| 14 | +# These can be customized based on specific use cases |
| 15 | +DEFAULT_PII_ENTITIES = [ |
| 16 | + "person", |
| 17 | + "organization", |
| 18 | + "email", |
| 19 | + "phone number", |
| 20 | + "address", |
| 21 | + "credit card number", |
| 22 | + "social security number", |
| 23 | + "date of birth", |
| 24 | + "medical record number", |
| 25 | + "account number", |
| 26 | + "license number", |
| 27 | + "passport number", |
| 28 | + "ip address", |
| 29 | + "url", |
| 30 | + "location", |
| 31 | +] |
| 32 | + |
| 33 | +MAXIMAL_STRING_SIZE = 1000000 |
| 34 | + |
| 35 | + |
| 36 | +class GLiNERAnnotator(BaseModel): |
| 37 | + """ |
| 38 | + GLiNER-based annotator for PII detection. |
| 39 | +
|
| 40 | + Uses GLiNER models to detect various types of personally identifiable information |
| 41 | + in text. Supports custom entity types and provides flexible configuration. |
| 42 | + """ |
| 43 | + |
| 44 | + model: Any |
| 45 | + entity_types: List[str] |
| 46 | + model_name: str |
| 47 | + |
| 48 | + model_config = ConfigDict(arbitrary_types_allowed=True, protected_namespaces=()) |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def create( |
| 52 | + cls, |
| 53 | + model_name: str = "urchade/gliner_multi_pii-v1", |
| 54 | + entity_types: Optional[List[str]] = None, |
| 55 | + ) -> "GLiNERAnnotator": |
| 56 | + """ |
| 57 | + Create a GLiNER annotator instance. |
| 58 | +
|
| 59 | + Args: |
| 60 | + model_name: Name of the GLiNER model to use. Defaults to PII-specialized model. |
| 61 | + entity_types: List of entity types to detect. Defaults to common PII types. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + GLiNERAnnotator instance |
| 65 | +
|
| 66 | + Raises: |
| 67 | + ImportError: If GLiNER dependencies are not installed |
| 68 | + """ |
| 69 | + try: |
| 70 | + from gliner import GLiNER |
| 71 | + except ImportError: |
| 72 | + raise ImportError( |
| 73 | + "GLiNER dependencies not available. " |
| 74 | + "Install with: pip install datafog[nlp-advanced]" |
| 75 | + ) |
| 76 | + |
| 77 | + if entity_types is None: |
| 78 | + entity_types = DEFAULT_PII_ENTITIES.copy() |
| 79 | + |
| 80 | + try: |
| 81 | + # Load the GLiNER model |
| 82 | + model = GLiNER.from_pretrained(model_name) |
| 83 | + logging.info(f"Successfully loaded GLiNER model: {model_name}") |
| 84 | + |
| 85 | + return cls(model=model, entity_types=entity_types, model_name=model_name) |
| 86 | + |
| 87 | + except Exception as e: |
| 88 | + logging.error(f"Failed to load GLiNER model {model_name}: {str(e)}") |
| 89 | + raise |
| 90 | + |
| 91 | + def annotate(self, text: str) -> Dict[str, List[str]]: |
| 92 | + """ |
| 93 | + Annotate text for PII entities using GLiNER. |
| 94 | +
|
| 95 | + Args: |
| 96 | + text: Text to analyze for PII entities |
| 97 | +
|
| 98 | + Returns: |
| 99 | + Dictionary mapping entity types to lists of detected entities |
| 100 | + """ |
| 101 | + try: |
| 102 | + if not text: |
| 103 | + return { |
| 104 | + entity_type.upper().replace(" ", "_"): [] |
| 105 | + for entity_type in self.entity_types |
| 106 | + } |
| 107 | + |
| 108 | + if len(text) > MAXIMAL_STRING_SIZE: |
| 109 | + text = text[:MAXIMAL_STRING_SIZE] |
| 110 | + logging.warning(f"Text truncated to {MAXIMAL_STRING_SIZE} characters") |
| 111 | + |
| 112 | + # Predict entities using GLiNER |
| 113 | + entities = self.model.predict_entities(text, self.entity_types) |
| 114 | + |
| 115 | + # Organize results by entity type |
| 116 | + classified_entities: Dict[str, List[str]] = { |
| 117 | + entity_type.upper().replace(" ", "_"): [] |
| 118 | + for entity_type in self.entity_types |
| 119 | + } |
| 120 | + |
| 121 | + for entity in entities: |
| 122 | + entity_label = entity["label"].upper().replace(" ", "_") |
| 123 | + entity_text = entity["text"] |
| 124 | + |
| 125 | + if entity_label in classified_entities: |
| 126 | + classified_entities[entity_label].append(entity_text) |
| 127 | + else: |
| 128 | + # Handle cases where GLiNER returns entity types not in our list |
| 129 | + classified_entities[entity_label] = [entity_text] |
| 130 | + |
| 131 | + return classified_entities |
| 132 | + |
| 133 | + except Exception as e: |
| 134 | + logging.error(f"Error processing text with GLiNER: {str(e)}") |
| 135 | + # Return empty annotations in case of error |
| 136 | + return { |
| 137 | + entity_type.upper().replace(" ", "_"): [] |
| 138 | + for entity_type in self.entity_types |
| 139 | + } |
| 140 | + |
| 141 | + def set_entity_types(self, entity_types: List[str]) -> None: |
| 142 | + """ |
| 143 | + Update the entity types to detect. |
| 144 | +
|
| 145 | + Args: |
| 146 | + entity_types: New list of entity types to detect |
| 147 | + """ |
| 148 | + self.entity_types = entity_types |
| 149 | + logging.info(f"Updated entity types to: {entity_types}") |
| 150 | + |
| 151 | + def get_model_info(self) -> Dict[str, Any]: |
| 152 | + """ |
| 153 | + Get information about the loaded model. |
| 154 | +
|
| 155 | + Returns: |
| 156 | + Dictionary with model information |
| 157 | + """ |
| 158 | + return { |
| 159 | + "model_name": self.model_name, |
| 160 | + "entity_types": self.entity_types, |
| 161 | + "max_text_size": MAXIMAL_STRING_SIZE, |
| 162 | + } |
| 163 | + |
| 164 | + @staticmethod |
| 165 | + def list_available_models() -> List[str]: |
| 166 | + """ |
| 167 | + List popular GLiNER models available for download. |
| 168 | +
|
| 169 | + Returns: |
| 170 | + List of model names |
| 171 | + """ |
| 172 | + return [ |
| 173 | + "urchade/gliner_base", |
| 174 | + "urchade/gliner_multi_pii-v1", |
| 175 | + "urchade/gliner_large-v2", |
| 176 | + "urchade/gliner_medium-v2.1", |
| 177 | + "knowledgator/gliner-bi-large-v1.0", |
| 178 | + "knowledgator/modern-gliner-bi-large-v1.0", |
| 179 | + ] |
| 180 | + |
| 181 | + @staticmethod |
| 182 | + def download_model(model_name: str) -> None: |
| 183 | + """ |
| 184 | + Download and cache a GLiNER model. |
| 185 | +
|
| 186 | + Args: |
| 187 | + model_name: Name of the model to download |
| 188 | +
|
| 189 | + Raises: |
| 190 | + ImportError: If GLiNER dependencies are not installed |
| 191 | + """ |
| 192 | + try: |
| 193 | + from gliner import GLiNER |
| 194 | + except ImportError: |
| 195 | + raise ImportError( |
| 196 | + "GLiNER dependencies not available. " |
| 197 | + "Install with: pip install datafog[nlp-advanced]" |
| 198 | + ) |
| 199 | + |
| 200 | + try: |
| 201 | + # This will download and cache the model |
| 202 | + GLiNER.from_pretrained(model_name) |
| 203 | + logging.info(f"Successfully downloaded GLiNER model: {model_name}") |
| 204 | + except Exception as e: |
| 205 | + logging.error(f"Failed to download GLiNER model {model_name}: {str(e)}") |
| 206 | + raise |
0 commit comments