Coverage for geoparser/services/recognition.py: 100%
59 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
2import uuid
3from typing import List, Tuple
5from sqlmodel import Session
7from geoparser.db.crud import (
8 RecognitionRepository,
9 RecognizerRepository,
10 ReferenceRepository,
11)
12from geoparser.db.db import get_session
13from geoparser.db.models import RecognitionCreate, RecognizerCreate, ReferenceCreate
15if t.TYPE_CHECKING:
16 from geoparser.db.models import Document
17 from geoparser.modules.recognizers.base import Recognizer
20class RecognitionService:
21 """
22 Service layer that handles all database operations for reference recognition.
24 This service acts as a bridge between recognizer modules (which are DB-agnostic)
25 and the database layer.
26 """
28 def __init__(self, recognizer: "Recognizer"):
29 """
30 Initialize the recognition service.
32 Args:
33 recognizer: The recognizer module to use for predictions
34 """
35 self.recognizer = recognizer
37 def _ensure_recognizer_record(self, recognizer: "Recognizer") -> str:
38 """
39 Ensure a recognizer record exists in the database.
41 Creates a new recognizer record if it doesn't already exist.
43 Args:
44 recognizer: The recognizer module to ensure exists in the database
46 Returns:
47 The recognizer ID from the database
48 """
49 with get_session() as session:
50 recognizer_record = RecognizerRepository.get(session, id=recognizer.id)
51 if recognizer_record is None:
52 recognizer_create = RecognizerCreate(
53 id=recognizer.id,
54 name=recognizer.name,
55 config=recognizer.config,
56 )
57 recognizer_record = RecognizerRepository.create(
58 session, recognizer_create
59 )
60 return recognizer_record.id
62 def predict(self, documents: List["Document"]) -> None:
63 """
64 Run the recognizer on the provided documents and store results in the database.
66 Args:
67 documents: List of Document objects to process
68 """
69 # Ensure recognizer record exists in database and get the ID
70 recognizer_id = self._ensure_recognizer_record(self.recognizer)
72 if not documents:
73 return
75 with get_session() as session:
76 # Filter out documents that have already been processed by this recognizer
77 unprocessed_documents = self._filter_unprocessed_documents(
78 session, documents, recognizer_id
79 )
81 if not unprocessed_documents:
82 return
84 # Extract text from documents for prediction
85 texts = [doc.text for doc in unprocessed_documents]
87 # Only call predict if there are texts to process
88 if texts:
89 # Get predictions from recognizer using raw text
90 predicted_references = self.recognizer.predict(texts)
92 # Process predictions and update database
93 self._record_reference_predictions(
94 session, unprocessed_documents, predicted_references, recognizer_id
95 )
97 def fit(self, documents: List["Document"], **kwargs) -> None:
98 """
99 Train the recognizer using the provided documents.
101 This method prepares training data from documents that have reference annotations
102 and calls the recognizer's fit method if it exists.
104 Args:
105 documents: List of Document objects with reference annotations for training
106 **kwargs: Additional training parameters (e.g., output_path, epochs, batch_size)
108 Raises:
109 ValueError: If the recognizer does not implement a fit method
110 """
111 # Check if the recognizer has a fit method
112 if not hasattr(self.recognizer, "fit"):
113 raise ValueError(
114 f"Recognizer '{self.recognizer.name}' does not implement a fit method"
115 )
117 # Extract texts and references from documents
118 texts = []
119 references = []
121 for doc in documents:
122 # Only include documents that have reference annotations
123 # doc.toponyms returns references filtered by the recognizer context
124 if doc.toponyms:
125 texts.append(doc.text)
126 references.append([(ref.start, ref.end) for ref in doc.toponyms])
128 # Call the recognizer's fit method with the prepared data
129 self.recognizer.fit(texts, references, **kwargs)
131 def _record_reference_predictions(
132 self,
133 session: Session,
134 documents: List["Document"],
135 predicted_references: List[t.Union[List[Tuple[int, int]], None]],
136 recognizer_id: uuid.UUID,
137 ) -> None:
138 """
139 Process reference predictions and update the database.
141 Args:
142 session: Database session
143 documents: List of document objects
144 predicted_references: List where each element is either a list of predicted references
145 or None for documents where predictions are not available
146 recognizer_id: ID of the recognizer that made the predictions
147 """
148 # Process each document with its predicted references
149 for document, references in zip(documents, predicted_references):
150 # Skip documents where predictions are not available
151 # (None indicates the recognizer couldn't process this document)
152 if references is None:
153 continue
155 # Create references with recognizer ID
156 for start, end in references:
157 self._create_reference_record(
158 session, document.id, start, end, recognizer_id
159 )
161 # Mark document as processed
162 self._create_recognition_record(session, document.id, recognizer_id)
164 def _create_reference_record(
165 self,
166 session: Session,
167 document_id: uuid.UUID,
168 start: int,
169 end: int,
170 recognizer_id: uuid.UUID,
171 ) -> None:
172 """
173 Create a reference record with the recognizer ID.
175 Args:
176 session: Database session
177 document_id: ID of the document containing the reference
178 start: Start position of the reference
179 end: End position of the reference
180 recognizer_id: ID of the recognizer
181 """
182 # Create the reference with recognizer ID directly
183 reference_create = ReferenceCreate(
184 start=start, end=end, document_id=document_id, recognizer_id=recognizer_id
185 )
186 ReferenceRepository.create(session, reference_create)
188 def _create_recognition_record(
189 self, session: Session, document_id: uuid.UUID, recognizer_id: uuid.UUID
190 ) -> None:
191 """
192 Create a recognition record for a document processed by a specific recognizer.
194 Args:
195 session: Database session
196 document_id: ID of the document that was processed
197 recognizer_id: ID of the recognizer that processed it
198 """
199 recognition_create = RecognitionCreate(
200 document_id=document_id, recognizer_id=recognizer_id
201 )
202 RecognitionRepository.create(session, recognition_create)
204 def _filter_unprocessed_documents(
205 self, session: Session, documents: List["Document"], recognizer_id: str
206 ) -> List["Document"]:
207 """
208 Filter out documents that have already been processed by this recognizer.
210 Args:
211 session: Database session
212 documents: List of all documents to check
213 recognizer_id: ID of the recognizer to check for
215 Returns:
216 List of documents that haven't been processed by this recognizer
217 """
218 unprocessed_documents = []
219 for doc in documents:
220 # Check if this document has already been processed by this recognizer
221 existing_recognition = RecognitionRepository.get_by_document_and_recognizer(
222 session, doc.id, recognizer_id
223 )
224 if not existing_recognition:
225 unprocessed_documents.append(doc)
226 return unprocessed_documents