Coverage for geoparser/modules/recognizers/spacy.py: 100%
74 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 18:08 +0000
1import random
2from pathlib import Path
3from typing import List, Tuple, Union
5import spacy
6from spacy.training import Example
8from geoparser.modules.recognizers import Recognizer
11class SpacyRecognizer(Recognizer):
12 """
13 A recognition module that uses spaCy to identify references in document text.
15 This module identifies location-based named entities like GPE (geopolitical entity),
16 LOC (location), and FAC (facility) as potential references.
17 """
19 NAME = "SpacyRecognizer"
21 def __init__(
22 self,
23 model_name: str = "en_core_web_sm",
24 entity_types: List[str] = ["FAC", "GPE", "LOC"],
25 ):
26 """
27 Initialize the SpaCy recognition module.
29 Args:
30 model_name: spaCy model to use (default: "en_core_web_sm")
31 entity_types: List of spaCy entity types to consider as references
32 (default: ["FAC", "GPE", "LOC"])
33 """
34 # Initialize parent with the parameters
35 super().__init__(model_name=model_name, entity_types=entity_types)
37 # Store instance attributes directly from parameters
38 self.model_name = model_name
39 # Convert entity_types to set for efficient lookups
40 self.entity_types = set(entity_types)
42 # Load spaCy model with optimized pipeline
43 self.nlp = self._load_spacy_model()
45 def _load_spacy_model(self) -> spacy.language.Language:
46 """
47 Load and configure the spaCy model with optimized pipeline.
49 Loads the specified model and removes unnecessary pipeline components
50 to optimize performance for NER tasks. If the model is not available,
51 it will be automatically downloaded.
53 Returns:
54 Configured spaCy Language model
55 """
56 # Try to load spaCy model, download if not available
57 try:
58 nlp = spacy.load(self.model_name)
59 except OSError:
60 # Model not found, download it
61 print(f"Downloading spaCy model '{self.model_name}'...")
62 spacy.cli.download(self.model_name)
63 nlp = spacy.load(self.model_name)
65 # Remove non-NER components to optimize performance
66 pipe_components = [
67 "tagger",
68 "parser",
69 "attribute_ruler",
70 "lemmatizer",
71 ]
72 for pipe_name in [p for p in pipe_components if p in nlp.pipe_names]:
73 nlp.remove_pipe(pipe_name)
74 return nlp
76 def predict(self, texts: List[str]) -> List[Union[List[Tuple[int, int]], None]]:
77 """
78 Identify references (location entities) in multiple document texts using spaCy.
80 Args:
81 texts: List of document text strings to process
83 Returns:
84 A list where each element corresponds to one document at the same index in the
85 input list. Each element is either a list of (start, end) tuples containing
86 positions of references found in the document, or None if predictions are not
87 available for that document.
88 """
89 results = []
91 # Process documents in batches using spaCy's nlp.pipe for efficiency
92 docs = list(self.nlp.pipe(texts))
94 # Extract reference offsets for each document
95 for doc in docs:
96 # Find all entities that match our entity types of interest
97 references = [
98 (ent.start_char, ent.end_char)
99 for ent in doc.ents
100 if ent.label_ in self.entity_types
101 ]
102 results.append(references)
104 return results
106 def fit(
107 self,
108 texts: List[str],
109 references: List[List[Tuple[int, int]]],
110 output_path: Union[str, Path],
111 epochs: int = 10,
112 batch_size: int = 8,
113 dropout: float = 0.1,
114 learning_rate: float = 0.001,
115 ) -> None:
116 """
117 Fine-tune the spaCy NER model using documents with reference annotations.
118 This method gathers all references from the provided documents and uses them
119 to create training examples for fine-tuning the underlying spaCy NER model.
121 Args:
122 texts: List of document text strings
123 references: List of lists of (start, end) position tuples
124 output_path: Directory path to save the fine-tuned model
125 epochs: Number of training epochs (default: 10)
126 batch_size: Training batch size (default: 8)
127 dropout: Dropout rate for training (default: 0.1)
128 learning_rate: Learning rate for training (default: 0.001)
130 Raises:
131 ValueError: If no training examples can be created from the provided documents
132 """
133 print("Preparing training data from reference annotations...")
135 # Prepare training data
136 examples = self._prepare_training_data(texts, references)
138 if not examples:
139 raise ValueError(
140 "No training examples found. Ensure documents contain reference annotations."
141 )
143 print(f"Created {len(examples)} training examples")
145 # Initialize optimizer
146 optimizer = self.nlp.resume_training()
147 optimizer.learn_rate = learning_rate
149 print("Starting model fine-tuning...")
151 # Training loop
152 losses = {}
153 for epoch in range(epochs):
154 # Shuffle examples for each epoch
155 epoch_examples = examples.copy()
156 random.shuffle(epoch_examples)
158 # Process in batches
159 for i in range(0, len(epoch_examples), batch_size):
160 batch = epoch_examples[i : i + batch_size]
161 self.nlp.update(batch, drop=dropout, sgd=optimizer, losses=losses)
163 # Save the trained model
164 Path(output_path).mkdir(parents=True, exist_ok=True)
165 self.nlp.to_disk(output_path)
167 print(f"Model fine-tuning completed and saved to: {output_path}")
169 def _get_distilled_label(
170 self, start: int, end: int, base_doc: spacy.tokens.Doc
171 ) -> str:
172 """
173 Efficiently find the best geographical entity label using spaCy's char_span.
175 Args:
176 start: Start character position of the reference span
177 end: End character position of the reference span
178 base_doc: spaCy Doc processed by the frozen base model
180 Returns:
181 The distilled geographical entity label or "LOC" as fallback
182 """
183 # Use spaCy's char_span to efficiently find overlapping span
184 span = base_doc.char_span(start, end, alignment_mode="expand")
186 if span:
187 # Check entities that overlap with our span
188 for ent in span.ents:
189 if ent.label_ in self.entity_types:
190 return ent.label_
192 # If no entities in the exact span, check if span overlaps with any entity
193 for token in span:
194 if token.ent_type_ in self.entity_types:
195 return token.ent_type_
197 return "LOC" # Default fallback
199 def _prepare_training_data(
200 self, texts: List[str], references: List[List[Tuple[int, int]]]
201 ) -> List[Example]:
202 """
203 Convert documents with reference annotations to spaCy training format.
204 Uses label distillation to assign each span the label the base model would choose.
206 Args:
207 texts: List of document text strings
208 references: List of lists of (start, end) position tuples
210 Returns:
211 List of spaCy Example objects for training
212 """
213 # Load frozen base pipeline for label distillation
214 base_nlp = self._load_spacy_model()
216 examples = []
218 for text, doc_references in zip(texts, references):
219 # Create spaCy doc from text (for training)
220 doc = self.nlp.make_doc(text)
222 # Process document with frozen base model for label distillation
223 base_doc = base_nlp(text)
225 # Extract entities from references with distilled labels
226 entities = []
227 for start, end in doc_references:
228 # Get distilled label from base model
229 entity_label = self._get_distilled_label(start, end, base_doc)
230 entities.append((start, end, entity_label))
232 # Create training example
233 entity_dict = {"entities": entities}
234 example = Example.from_dict(doc, entity_dict)
235 examples.append(example)
237 return examples