Coverage for geoparser/modules/resolvers/sentencetransformer.py: 100%
228 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 typing as t
2from pathlib import Path
3from typing import Dict, List, Tuple, Union
5import spacy
6import torch
7from datasets import Dataset
8from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer
9from sentence_transformers.sentence_transformer.losses import ContrastiveLoss
10from sentence_transformers.sentence_transformer.training_args import (
11 SentenceTransformerTrainingArguments,
12)
13from transformers import AutoTokenizer, logging
15from geoparser.gazetteer.gazetteer import Gazetteer
16from geoparser.modules.resolvers import Resolver
18if t.TYPE_CHECKING:
19 from geoparser.gazetteer.feature import Feature
21# Suppress transformers tokenizer token length warnings
22logging.set_verbosity_error()
25class SentenceTransformerResolver(Resolver):
26 """
27 A resolver that uses SentenceTransformer to map reference contexts to gazetteer candidates.
29 This resolver extracts contextual information around each reference, generates embeddings
30 for the context, retrieves candidate features from the gazetteer, generates location
31 descriptions and embeddings for candidates, and finds the best match using cosine similarity.
32 """
34 NAME = "SentenceTransformerResolver"
36 # Gazetteer-specific attribute mappings for location descriptions
37 GAZETTEER_ATTRIBUTE_MAP = {
38 "geonames": {
39 "name": "name",
40 "type": "feature_name",
41 "level1": "country_name",
42 "level2": "admin1_name",
43 "level3": "admin2_name",
44 },
45 "geonames-cities": {
46 "name": "name",
47 "type": "feature_name",
48 "level1": "country_name",
49 "level2": "admin1_name",
50 "level3": "admin2_name",
51 },
52 "swissnames3d": {
53 "name": "NAME",
54 "type": "OBJEKTART",
55 "level1": "KANTON_NAME",
56 "level2": "BEZIRK_NAME",
57 "level3": "GEMEINDE_NAME",
58 },
59 }
61 def __init__(
62 self,
63 model_name: str = "dguzh/geo-all-MiniLM-L6-v2",
64 gazetteer_name: str = "geonames",
65 min_similarity: float = 0.6,
66 max_tiers: int = 3,
67 attribute_map: dict = None,
68 ):
69 """
70 Initialize the SentenceTransformerResolver.
72 Args:
73 model_name: HuggingFace model name for SentenceTransformer
74 gazetteer_name: Name of the gazetteer to search
75 min_similarity: Minimum similarity threshold to stop candidate generation
76 max_tiers: Maximum number of tiers to expand through search methods
77 attribute_map: Optional custom attribute mapping for gazetteer.
78 If None, will look up gazetteer_name in GAZETTEER_ATTRIBUTE_MAP.
79 If provided, will be used directly.
80 Should have keys: "name", "type", "level1", "level2", "level3"
81 """
82 # Initialize parent with the parameters
83 super().__init__(
84 model_name=model_name,
85 gazetteer_name=gazetteer_name,
86 min_similarity=min_similarity,
87 max_tiers=max_tiers,
88 attribute_map=attribute_map,
89 )
91 # Store instance attributes directly from parameters
92 self.model_name = model_name
93 self.gazetteer_name = gazetteer_name
94 self.min_similarity = min_similarity
95 self.max_tiers = max_tiers
97 # Validate and set attribute map
98 self.attribute_map = self._validate_and_set_attribute_map(
99 gazetteer_name, attribute_map
100 )
102 # Initialize gazetteer first, so that a missing one is reported before
103 # any time is spent loading models
104 self.gazetteer = Gazetteer(gazetteer_name)
106 # Initialize transformer and tokenizer
107 self.transformer = SentenceTransformer(model_name)
108 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
110 # Initialize spaCy model for sentence splitting
111 self.nlp = self._load_spacy_model("xx_sent_ud_sm")
113 # Caches for document processing to avoid recomputation
114 self.doc_tokens: Dict[str, int] = {} # text -> token count
115 self.doc_objects: Dict[str, spacy.tokens.Doc] = {} # text -> spaCy doc object
117 # Caches for embeddings to avoid recomputation
118 self.context_embeddings: Dict[str, torch.Tensor] = {} # context -> embedding
119 self.candidate_embeddings: Dict[int, torch.Tensor] = (
120 {}
121 ) # feature_id -> embedding
123 def _validate_and_set_attribute_map(
124 self, gazetteer_name: str, attribute_map: dict = None
125 ) -> dict:
126 """
127 Validate and set the attribute map for the gazetteer.
129 Args:
130 gazetteer_name: Name of the gazetteer
131 attribute_map: Optional custom attribute mapping
133 Returns:
134 The validated attribute map dictionary
136 Raises:
137 ValueError: If gazetteer is not configured and no custom map is provided
138 """
139 if attribute_map is None:
140 # Look up in GAZETTEER_ATTRIBUTE_MAP
141 if gazetteer_name not in self.GAZETTEER_ATTRIBUTE_MAP:
142 raise ValueError(
143 f"Gazetteer '{gazetteer_name}' is not configured in GAZETTEER_ATTRIBUTE_MAP. "
144 f"Please provide a custom attribute_map parameter."
145 )
146 return self.GAZETTEER_ATTRIBUTE_MAP[gazetteer_name]
147 else:
148 return attribute_map
150 def _load_spacy_model(self, model_name: str) -> spacy.language.Language:
151 """
152 Load a spaCy model, downloading it if necessary.
154 Args:
155 model_name: Name of the spaCy model to load
157 Returns:
158 Loaded spaCy Language model
159 """
160 try:
161 nlp = spacy.load(model_name)
162 except OSError:
163 # Model not found, download it
164 print(f"Downloading spaCy model '{model_name}'...")
165 spacy.cli.download(model_name)
166 nlp = spacy.load(model_name)
167 return nlp
169 def predict(
170 self, texts: t.List[str], references: t.List[t.List[t.Tuple[int, int]]]
171 ) -> t.List[t.List[t.Union[t.Tuple[str, str], None]]]:
172 """
173 Predict referents for multiple references using iterative candidate generation.
175 Uses a search strategy that starts with restrictive search methods and
176 progressively expands to less restrictive ones, stopping when candidates
177 with sufficient similarity are found.
179 Args:
180 texts: List of document text strings
181 references: List of lists of tuples containing (start, end) positions of references
183 Returns:
184 A list of lists where each inner list corresponds to referents for references in one
185 document. Each element is either a tuple (gazetteer_name, identifier) for a
186 successfully resolved reference, or None if prediction is not available for that
187 specific reference.
188 """
189 # Check if there are any texts to process
190 if not texts:
191 return []
193 # Step 1: Extract contexts for all references
194 contexts = self._extract_contexts(texts, references)
196 # Step 2: Embed all contexts
197 self._embed_contexts(contexts)
199 # Initialize tracking structures (nested by document)
200 results = [[None for _ in doc_refs] for doc_refs in references]
201 candidates = [[[] for _ in doc_refs] for doc_refs in references]
203 # Define search methods in order of preference
204 search_methods = [
205 "exact",
206 "phrase",
207 "partial",
208 "fuzzy",
209 ]
211 # Iterative search strategy with increasing tiers
212 for tiers in range(1, self.max_tiers + 1):
213 for method in search_methods:
214 # Skip exact method for tiers > 1
215 if method == "exact" and tiers > 1:
216 continue
218 # Step 3: Gather candidates for unresolved references
219 self._gather_candidates(
220 texts, references, candidates, results, method, tiers
221 )
223 # Step 4: Embed new candidates
224 self._embed_candidates(candidates, results)
226 # Step 5: Evaluate candidates and update results
227 self._evaluate_candidates(
228 contexts, candidates, results, self.min_similarity
229 )
231 # If all references resolved, we can stop
232 if all(
233 all(r is not None for r in doc_results) for doc_results in results
234 ):
235 break
237 # If all references resolved, we can stop
238 if all(all(r is not None for r in doc_results) for doc_results in results):
239 break
241 return results
243 def _extract_contexts(
244 self, texts: List[str], references: List[List[Tuple[int, int]]]
245 ) -> List[List[str]]:
246 """
247 Extract contexts for all references.
249 Args:
250 texts: List of document text strings
251 references: List of lists of tuples containing (start, end) positions of references
253 Returns:
254 List of lists of context strings, matching the structure of references
255 """
256 contexts = []
257 for text, doc_references in zip(texts, references):
258 doc_contexts = []
259 for start, end in doc_references:
260 context = self._extract_context(text, start, end)
261 doc_contexts.append(context)
262 contexts.append(doc_contexts)
263 return contexts
265 def _embed_contexts(self, contexts: List[List[str]]) -> None:
266 """
267 Generate embeddings for contexts, avoiding duplicate work.
269 Args:
270 contexts: List of lists of context strings
271 """
272 # Collect unique contexts that need encoding
273 contexts_to_encode = set()
274 for doc_contexts in contexts:
275 for context in doc_contexts:
276 # Only encode contexts we haven't seen before
277 if context not in self.context_embeddings:
278 contexts_to_encode.add(context)
280 # Encode unique contexts in batch
281 if contexts_to_encode:
282 unique_contexts = list(contexts_to_encode)
283 embeddings = self.transformer.encode(
284 unique_contexts,
285 convert_to_tensor=True,
286 batch_size=32,
287 show_progress_bar=True,
288 )
290 # Store embeddings in cache with context as key
291 for context, embedding in zip(unique_contexts, embeddings):
292 self.context_embeddings[context] = embedding
294 def _gather_candidates(
295 self,
296 texts: List[str],
297 references: List[List[Tuple[int, int]]],
298 candidates: List[List[List["Feature"]]],
299 results: List[List[Tuple[str, str]]],
300 method: str,
301 tiers: int,
302 ) -> None:
303 """
304 Gather candidates for unresolved references using the specified search method.
306 Args:
307 texts: List of document text strings
308 references: List of lists of tuples containing (start, end) positions of references
309 candidates: Nested list of candidate lists for each reference (modified in-place)
310 results: Nested list of current results to determine which references need candidates
311 method: Search method to use
312 tiers: Number of rank tiers to include
313 """
314 for doc_idx, (text, doc_references, doc_candidates, doc_results) in enumerate(
315 zip(texts, references, candidates, results)
316 ):
317 for ref_idx, ((start, end), result) in enumerate(
318 zip(doc_references, doc_results)
319 ):
320 # Skip already resolved references
321 if result is not None:
322 continue
324 # Search for new candidates and merge with existing ones, avoiding duplicates
325 reference_text = text[start:end]
326 new_candidates = self.gazetteer.search(
327 reference_text, method, tiers=tiers
328 )
329 existing_ids = {c.id for c in doc_candidates[ref_idx]}
330 for candidate in new_candidates:
331 if candidate.id not in existing_ids:
332 doc_candidates[ref_idx].append(candidate)
334 def _embed_candidates(
335 self,
336 candidates: List[List[List["Feature"]]],
337 results: List[List[Tuple[str, str]]],
338 ) -> None:
339 """
340 Generate embeddings for candidates that need to be processed.
342 Args:
343 candidates: Nested list of candidate lists for each reference
344 results: Nested list of current results to determine which candidates need embedding
345 """
346 # Collect unique candidates that need embedding
347 candidates_to_embed = {} # Use dict to avoid duplicates: id -> candidate
349 for doc_candidates, doc_results in zip(candidates, results):
350 for candidate_list, result in zip(doc_candidates, doc_results):
351 # Skip already resolved references
352 if result is not None:
353 continue
355 # Add candidates that don't have embeddings yet
356 for candidate in candidate_list:
357 if candidate.id not in self.candidate_embeddings:
358 candidates_to_embed[candidate.id] = candidate
360 if not candidates_to_embed:
361 return
363 # Convert to list for consistent ordering
364 candidates_list = list(candidates_to_embed.values())
366 # Generate descriptions for candidates
367 descriptions = [
368 self._generate_description(candidate) for candidate in candidates_list
369 ]
371 # Generate embeddings in batch
372 if descriptions:
373 embeddings = self.transformer.encode(
374 descriptions,
375 convert_to_tensor=True,
376 batch_size=32,
377 show_progress_bar=True,
378 )
380 # Store embeddings in cache
381 for candidate, embedding in zip(candidates_list, embeddings):
382 self.candidate_embeddings[candidate.id] = embedding
384 def _evaluate_candidates(
385 self,
386 contexts: List[List[str]],
387 candidates: List[List[List["Feature"]]],
388 results: List[List[Tuple[str, str]]],
389 min_similarity: float = 0.0,
390 ) -> None:
391 """
392 Evaluate candidates against reference contexts and update results.
394 Args:
395 contexts: List of lists of context strings
396 candidates: Nested list of candidate lists for each reference
397 results: Nested list of current results (modified in-place)
398 min_similarity: Minimum similarity threshold (default: 0.0)
399 """
400 for doc_idx, (doc_contexts, doc_candidates, doc_results) in enumerate(
401 zip(contexts, candidates, results)
402 ):
403 for ref_idx, (context, candidate_list, result) in enumerate(
404 zip(doc_contexts, doc_candidates, doc_results)
405 ):
406 # Skip already resolved references
407 if result is not None:
408 continue
410 # Skip if no candidates
411 if not candidate_list:
412 continue
414 # Get reference context embedding using context as key
415 context_embedding = self.context_embeddings[context]
417 # Get candidate embeddings
418 candidate_embeddings = [
419 self.candidate_embeddings[candidate.id]
420 for candidate in candidate_list
421 ]
423 # Calculate similarities
424 similarities = self._calculate_similarities(
425 context_embedding, candidate_embeddings
426 )
428 # Find best candidate
429 best_idx = max(range(len(similarities)), key=lambda j: similarities[j])
430 best_similarity = similarities[best_idx]
431 best_candidate = candidate_list[best_idx]
433 # Check if similarity meets threshold
434 if best_similarity >= min_similarity:
435 doc_results[ref_idx] = (
436 self.gazetteer_name,
437 best_candidate.identifier,
438 )
440 def _extract_context(self, text: str, start: int, end: int) -> str:
441 """
442 Extract context around a single reference, respecting model token limits.
444 Args:
445 text: Full document text
446 start: Start position of the reference
447 end: End position of the reference
449 Returns:
450 Context string for the reference
451 """
452 max_seq_length = self.transformer.get_max_seq_length()
453 # Reserve space for special tokens ([CLS] and [SEP] for BERT-like models)
454 token_limit = max_seq_length - 2
456 # Check if entire document fits within token limit
457 # Use cached token count if available
458 if text not in self.doc_tokens:
459 self.doc_tokens[text] = len(self.tokenizer.tokenize(text))
460 doc_tokens = self.doc_tokens[text]
462 if doc_tokens <= token_limit:
463 return text
465 # Use spaCy to get sentence boundaries
466 # Use cached spaCy doc if available
467 if text not in self.doc_objects:
468 self.doc_objects[text] = self.nlp(text)
469 doc = self.doc_objects[text]
470 sentences = list(doc.sents)
472 # Find the sentence containing the reference
473 target_sentence = None
474 for sent in sentences:
475 if sent.start_char <= start < sent.end_char:
476 target_sentence = sent
477 break
479 # Get sentence index
480 target_idx = sentences.index(target_sentence)
481 context_sentences = [target_sentence]
483 # Calculate tokens for target sentence
484 tokens_count = len(self.tokenizer.tokenize(target_sentence.text))
486 # Expand context bidirectionally while respecting token limit
487 i, j = target_idx, target_idx
489 while True:
490 expanded = False
492 # Try to add previous sentence
493 if i > 0:
494 prev_sentence = sentences[i - 1]
495 prev_tokens = len(self.tokenizer.tokenize(prev_sentence.text))
496 if tokens_count + prev_tokens <= token_limit:
497 context_sentences.insert(0, prev_sentence)
498 tokens_count += prev_tokens
499 i -= 1
500 expanded = True
502 # Try to add next sentence
503 if j < len(sentences) - 1:
504 next_sentence = sentences[j + 1]
505 next_tokens = len(self.tokenizer.tokenize(next_sentence.text))
506 if tokens_count + next_tokens <= token_limit:
507 context_sentences.append(next_sentence)
508 tokens_count += next_tokens
509 j += 1
510 expanded = True
512 if not expanded:
513 break
515 # Combine sentences to form context
516 context = " ".join(sent.text for sent in context_sentences)
517 return context
519 def _generate_description(self, candidate: "Feature") -> str:
520 """
521 Generate a textual description for a single candidate location.
523 Args:
524 candidate: Feature object
526 Returns:
527 Location description string
528 """
529 # Get location data
530 location_data = candidate.data
532 # Use the attribute map that was set during initialization
533 attr_map = self.attribute_map
535 # Extract attributes
536 feature_name = location_data.get(attr_map["name"])
537 feature_type = location_data.get(attr_map["type"])
539 # Build description components
540 description_parts = []
542 # Add feature name if available
543 if feature_name:
544 description_parts.append(feature_name)
546 # Add feature type in brackets if available
547 if feature_type:
548 description_parts.append(f"({feature_type})")
550 # Build hierarchical context from admin levels
551 admin_levels = []
552 for level in ["level3", "level2", "level1"]:
553 if level in attr_map:
554 admin_value = location_data.get(attr_map[level])
555 if admin_value:
556 admin_levels.append(admin_value)
558 # Combine description parts
559 if admin_levels:
560 description_parts.append("in")
561 description_parts.append(", ".join(admin_levels))
563 description = " ".join(description_parts).strip()
565 return description
567 def _calculate_similarities(
568 self,
569 context_embedding: torch.Tensor,
570 candidate_embeddings: List[torch.Tensor],
571 ) -> List[float]:
572 """
573 Calculate cosine similarities between context and candidate embeddings.
575 Args:
576 context_embedding: Embedding tensor for the reference context
577 candidate_embeddings: List of embedding tensors for candidates
579 Returns:
580 List of similarity scores
581 """
582 if not candidate_embeddings:
583 return []
585 # Stack candidate embeddings
586 candidate_tensor = torch.stack(candidate_embeddings)
588 # Calculate cosine similarities
589 similarities = torch.nn.functional.cosine_similarity(
590 context_embedding.unsqueeze(0), candidate_tensor, dim=1
591 )
593 return similarities.tolist()
595 def fit(
596 self,
597 texts: List[str],
598 references: List[List[Tuple[int, int]]],
599 referents: List[List[Tuple[str, str]]],
600 output_path: Union[str, Path],
601 epochs: int = 1,
602 batch_size: int = 8,
603 learning_rate: float = 2e-5,
604 warmup_ratio: float = 0.1,
605 save_strategy: str = "epoch",
606 ) -> None:
607 """
608 Fine-tune the SentenceTransformer model using references and their resolved referents as training data.
610 This method gathers all references that have been resolved (i.e., have referents), extracts
611 their contexts and all candidate descriptions, and uses them to create positive and negative
612 training examples for fine-tuning the underlying SentenceTransformer model using ContrastiveLoss.
614 Args:
615 texts: List of document text strings
616 references: List of lists of (start, end) position tuples
617 referents: List of lists of (gazetteer_name, identifier) tuples
618 output_path: Directory path to save the fine-tuned model
619 epochs: Number of training epochs (default: 1)
620 batch_size: Training batch size (default: 8)
621 learning_rate: Learning rate for training (default: 2e-5)
622 warmup_ratio: Warmup ratio for learning rate scheduler (default: 0.1)
623 save_strategy: When to save the model during training (default: "epoch")
625 Raises:
626 ValueError: If no training examples can be created from the provided documents
627 """
628 print("Preparing training data from referent annotations...")
630 # Step 1: Gather training data from resolved references
631 training_data = self._prepare_training_data(texts, references, referents)
633 if not training_data["sentence1"] or len(training_data["sentence1"]) == 0:
634 raise ValueError(
635 "No training examples found. Ensure documents contain references with referent annotations."
636 )
638 print(f"Created {len(training_data['sentence1'])} training examples")
640 # Step 2: Create training dataset
641 train_dataset = Dataset.from_dict(training_data)
643 # Step 3: Setup training loss
644 train_loss = ContrastiveLoss(self.transformer)
646 # Step 4: Configure training arguments
647 training_args = SentenceTransformerTrainingArguments(
648 output_dir=str(output_path),
649 num_train_epochs=epochs,
650 per_device_train_batch_size=batch_size,
651 learning_rate=learning_rate,
652 warmup_ratio=warmup_ratio,
653 save_strategy=save_strategy,
654 logging_strategy="steps",
655 logging_steps=max(1, len(training_data["sentence1"]) // (batch_size * 10)),
656 eval_strategy="no", # No evaluation for now
657 save_total_limit=2, # Keep only 2 checkpoints
658 load_best_model_at_end=False,
659 )
661 # Step 5: Create trainer
662 trainer = SentenceTransformerTrainer(
663 model=self.transformer,
664 args=training_args,
665 train_dataset=train_dataset,
666 loss=train_loss,
667 )
669 print("Starting model fine-tuning...")
671 # Step 6: Train the model
672 trainer.train()
674 # Step 7: Save the final model
675 self.transformer.save_pretrained(str(output_path))
677 print(f"Model fine-tuning completed and saved to: {output_path}")
679 def _prepare_training_data(
680 self,
681 texts: List[str],
682 references: List[List[Tuple[int, int]]],
683 referents: List[List[Tuple[str, str]]],
684 ) -> Dict[str, List]:
685 """
686 Prepare training data from documents with resolved references.
688 This method extracts all references that have been resolved (have referents),
689 gets their contexts and all candidate descriptions to create both positive
690 and negative training examples for ContrastiveLoss.
692 Args:
693 texts: List of document text strings
694 references: List of lists of (start, end) position tuples
695 referents: List of lists of (gazetteer_name, identifier) tuples
697 Returns:
698 Dictionary with 'sentence1', 'sentence2', and 'label' lists for training
699 """
700 sentence1_texts = [] # contexts
701 sentence2_texts = [] # candidate descriptions
702 labels = [] # 1 for positive, 0 for negative
704 for text, doc_references, doc_referents in zip(texts, references, referents):
705 for (start, end), (gazetteer_name, identifier) in zip(
706 doc_references, doc_referents
707 ):
708 # Extract context for this reference
709 context = self._extract_context(text, start, end)
711 # Get all candidates for this reference text to create negative examples
712 reference_text = text[start:end]
713 candidates = self.gazetteer.search(reference_text)
715 for candidate in candidates:
716 # Generate description for this candidate
717 description = self._generate_description(candidate)
719 # Determine if this is a positive or negative example
720 label = 1 if candidate.identifier == identifier else 0
722 # Add as training example
723 sentence1_texts.append(context)
724 sentence2_texts.append(description)
725 labels.append(label)
727 return {
728 "sentence1": sentence1_texts,
729 "sentence2": sentence2_texts,
730 "label": labels,
731 }