Coverage for geoparser/project/project.py: 100%
117 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 json
2import typing as t
3import uuid
4from pathlib import Path
5from typing import List, Union
7from geoparser.context import Context
8from geoparser.db.crud import DocumentRepository, ProjectRepository
9from geoparser.db.db import create_db_and_tables, get_session
10from geoparser.db.models import Document, DocumentCreate, ProjectCreate
11from geoparser.modules.recognizers.manual import ManualRecognizer
12from geoparser.modules.resolvers.manual import ManualResolver
13from geoparser.services.recognition import RecognitionService
14from geoparser.services.resolution import ResolutionService
16if t.TYPE_CHECKING:
17 from geoparser.modules.recognizers import Recognizer
18 from geoparser.modules.resolvers import Resolver
21class Project:
22 """
23 Handles project management and pipeline execution.
25 This class manages project lifecycle, document management, and provides
26 methods to run processing pipelines on project documents.
27 """
29 def __init__(self, name: str):
30 """
31 Initialize a Project instance.
33 Args:
34 name: Name for the project. If the project doesn't exist,
35 it will be created.
36 """
37 # Ensure database tables exist
38 create_db_and_tables()
40 self.name = name
41 self.id = self._ensure_project_record(name)
42 self.context = Context(project_id=self.id)
44 def _ensure_project_record(self, name: str) -> uuid.UUID:
45 """
46 Ensure a project record exists in the database.
48 Creates a new project record if it doesn't already exist.
50 Args:
51 name: Name of the project to load or create
53 Returns:
54 Project ID from the database
55 """
56 with get_session() as session:
57 # Try to load existing project
58 project_record = ProjectRepository.get_by_name(session, name)
60 # Create new project if it doesn't exist
61 if project_record is None:
62 project_create = ProjectCreate(name=name)
63 project_record = ProjectRepository.create(session, project_create)
65 return project_record.id
67 def create_documents(self, texts: t.Sequence[str]) -> List[uuid.UUID]:
68 """
69 Create documents in the project.
71 The returned IDs are in the same order as the texts that were passed in,
72 which lets you relate documents back to whatever they came from. Keep
73 them alongside your own records and pass them to :meth:`get_documents`
74 to retrieve results for specific documents later on.
76 Args:
77 texts: Document texts to create. A single document is created by
78 passing a sequence with one text in it.
80 Returns:
81 IDs of the created documents, in the order the texts were provided
83 Raises:
84 TypeError: If a single text is passed instead of a sequence of texts
85 """
86 # A bare string would be iterated character by character, creating one
87 # document per character, so reject it instead of doing that silently
88 if isinstance(texts, str):
89 raise TypeError(
90 "create_documents() expects a sequence of texts. To create a single "
91 "document, pass a sequence with one text in it: "
92 "create_documents(['...'])."
93 )
95 document_ids = []
97 with get_session() as session:
98 for text in texts:
99 document_create = DocumentCreate(text=text, project_id=self.id)
100 document = DocumentRepository.create(session, document_create)
101 document_ids.append(document.id)
103 return document_ids
105 def create_references(
106 self, texts: List[str], references: List[List[tuple]], tag: str
107 ) -> None:
108 """
109 Create references (toponym spans) using ManualRecognizer.
111 Args:
112 texts: List of document texts
113 references: List of reference tuples (start, end) for each document
114 tag: Tag to identify this recognition set
115 """
116 recognizer = ManualRecognizer(label=tag, texts=texts, references=references)
117 self.run_recognizer(recognizer, tag=tag)
119 def create_referents(
120 self,
121 texts: List[str],
122 references: List[List[tuple]],
123 referents: List[List[tuple]],
124 tag: str,
125 ) -> None:
126 """
127 Create referents (location assignments) using ManualResolver.
129 Args:
130 texts: List of document texts
131 references: List of reference tuples (start, end) for each document
132 referents: List of referent tuples (gazetteer_name, identifier) for each document
133 tag: Tag to identify this resolution set
134 """
135 resolver = ManualResolver(
136 label=tag, texts=texts, references=references, referents=referents
137 )
138 self.run_resolver(resolver, tag=tag)
140 @staticmethod
141 def _normalize_document_ids(
142 ids: Union[uuid.UUID, str, t.Sequence[Union[uuid.UUID, str]]],
143 ) -> List[uuid.UUID]:
144 """
145 Convert document IDs given as UUIDs or strings into a list of UUIDs.
147 Args:
148 ids: A single document ID or a sequence of document IDs
150 Returns:
151 List of document IDs as UUID objects
153 Raises:
154 ValueError: If a value cannot be interpreted as a document ID
155 """
156 # A single ID is accepted as well as a sequence of them
157 if isinstance(ids, (str, uuid.UUID)):
158 ids = [ids]
160 normalized = []
161 for value in ids:
162 if isinstance(value, uuid.UUID):
163 normalized.append(value)
164 continue
165 try:
166 normalized.append(uuid.UUID(str(value)))
167 except (AttributeError, TypeError, ValueError):
168 raise ValueError(
169 f"'{value}' is not a valid document ID. Document IDs are the values "
170 "returned by create_documents(). To select results by tag instead, "
171 "pass the tag as a keyword argument: get_documents(tag='...')."
172 ) from None
174 return normalized
176 def get_documents(
177 self,
178 ids: t.Optional[
179 Union[uuid.UUID, str, t.Sequence[Union[uuid.UUID, str]]]
180 ] = None,
181 tag: str = "latest",
182 ) -> List[Document]:
183 """
184 Retrieve documents in the project with context set for the specified tag.
186 Args:
187 ids: Document IDs to retrieve, as returned by :meth:`create_documents`.
188 The documents are returned in the order given here. If omitted,
189 every document in the project is returned.
190 tag: Tag identifier to determine which recognizer/resolver context to use
191 (default: "latest")
193 Returns:
194 List of Document objects with context set for filtering.
196 Raises:
197 ValueError: If an ID does not belong to a document in this project
198 """
199 # Validate the requested IDs before touching the database
200 requested_ids = None if ids is None else self._normalize_document_ids(ids)
202 # Retrieve recognizer and resolver IDs for the specified tag
203 recognizer_id = self.context.get_recognizer_context(tag)
204 resolver_id = self.context.get_resolver_context(tag)
206 with get_session() as session:
207 if requested_ids is None:
208 # Retrieve all documents for the project
209 documents = DocumentRepository.get_by_project(session, self.id)
210 else:
211 # Retrieve the requested documents in the order they were requested
212 found = {
213 document.id: document
214 for document in DocumentRepository.get_by_ids(
215 session, self.id, requested_ids
216 )
217 }
219 missing = [str(id) for id in requested_ids if id not in found]
220 if missing:
221 raise ValueError(
222 f"No documents with the following IDs exist in project "
223 f"'{self.name}': {', '.join(missing)}"
224 )
226 documents = [found[id] for id in requested_ids]
228 # Always set context on each document (even if None)
229 for doc in documents:
230 doc._set_recognizer_context(recognizer_id)
232 # Always set context on each reference (even if None)
233 for ref in doc.references:
234 ref._set_resolver_context(resolver_id)
236 return documents
238 def run_recognizer(self, recognizer: "Recognizer", tag: str = "latest") -> None:
239 """
240 Run a recognizer module on all documents in this project.
242 This is a convenience method that simplifies the workflow for advanced users
243 by handling service initialization and document retrieval internally.
245 Args:
246 recognizer: The recognizer module to run on all project documents
247 tag: Tag to associate with this recognizer run (default: "latest")
248 """
249 # Get all documents in the project
250 documents = self.get_documents()
252 # Initialize the recognition service with the recognizer
253 recognition_service = RecognitionService(recognizer)
255 # Run the recognizer on all documents
256 recognition_service.predict(documents)
258 # Update the context with this recognizer for the specified tag
259 self.context.update_recognizer_context(tag, recognizer.id)
261 def run_resolver(self, resolver: "Resolver", tag: str = "latest") -> None:
262 """
263 Run a resolver module on all documents in this project.
265 This is a convenience method that simplifies the workflow for advanced users
266 by handling service initialization and document retrieval internally.
268 Args:
269 resolver: The resolver module to run on all project documents
270 tag: Tag to associate with this resolver run (default: "latest")
271 """
272 # Get all documents in the project
273 documents = self.get_documents()
275 # Initialize the resolution service with the resolver
276 resolution_service = ResolutionService(resolver)
278 # Run the resolver on all documents
279 resolution_service.predict(documents)
281 # Update the context with this resolver for the specified tag
282 self.context.update_resolver_context(tag, resolver.id)
284 def train_recognizer(self, recognizer: "Recognizer", tag: str, **kwargs) -> None:
285 """
286 Train a recognizer module using documents with reference annotations from this project.
288 This method retrieves documents that have been processed by a specific recognizer,
289 prepares the training data, and calls the recognizer's fit method if available.
291 Args:
292 recognizer: The recognizer module to train
293 tag: Tag identifying which annotations to use for training
294 **kwargs: Additional training parameters (e.g., output_path, epochs, batch_size)
296 Raises:
297 ValueError: If the recognizer does not implement a fit method
298 """
299 # Get all documents in the project with the specified tag context
300 documents = self.get_documents(tag=tag)
302 # Initialize the recognition service with the recognizer
303 recognition_service = RecognitionService(recognizer)
305 # Train the recognizer using the annotated documents
306 recognition_service.fit(documents, **kwargs)
308 def train_resolver(self, resolver: "Resolver", tag: str, **kwargs) -> None:
309 """
310 Train a resolver module using documents with referent annotations from this project.
312 This method retrieves documents that have been processed by specific recognizer and resolver,
313 prepares the training data, and calls the resolver's fit method if available.
315 Args:
316 resolver: The resolver module to train
317 tag: Tag identifying which annotations to use for training
318 **kwargs: Additional training parameters (e.g., output_path, epochs, batch_size)
320 Raises:
321 ValueError: If the resolver does not implement a fit method
322 """
323 # Get all documents in the project with the specified tag context
324 documents = self.get_documents(tag=tag)
326 # Initialize the resolution service with the resolver
327 resolution_service = ResolutionService(resolver)
329 # Train the resolver using the annotated documents
330 resolution_service.fit(documents, **kwargs)
332 def load_annotations(
333 self, path: str, tag: str, create_documents: bool = False
334 ) -> None:
335 """
336 Load annotations from an annotator JSON file and register them in the project.
338 This method imports annotations from the legacy annotator format and registers
339 them using ManualRecognizer for toponym spans and ManualResolver for location
340 assignments. The annotations are stored with the provided tag to distinguish
341 different annotation sources.
343 Args:
344 path: Path to the JSON file exported from the annotator
345 tag: Tag to identify this annotation set
346 This allows tracking multiple annotation sources separately
347 create_documents: Whether to create new documents from the texts in the JSON
348 (default: False). Set to True if the documents don't exist yet,
349 False to add annotations to existing documents.
350 """
351 # Load JSON file
352 path = Path(path)
353 with open(path, "r") as f:
354 data = json.load(f)
356 # Extract gazetteer name from annotations
357 gazetteer_name = data["gazetteer"]
359 # Prepare aligned lists for ManualRecognizer and ManualResolver
360 texts = []
361 references = [] # All toponyms for both recognizer and resolver
362 referents = [] # Location assignments (with None for non-geocoded toponyms)
364 for doc in data["documents"]:
365 text = doc["text"]
366 texts.append(text)
368 # Extract all toponyms as references
369 doc_references = [(t["start"], t["end"]) for t in doc["toponyms"]]
370 references.append(doc_references)
372 # Create referents list aligned with ALL references
373 # Use None for toponyms that are not geocoded
374 doc_referents = []
375 for toponym in doc["toponyms"]:
376 # Only include toponyms that have been geocoded (loc_id is not "" and not null)
377 if toponym["loc_id"] and toponym["loc_id"] != "":
378 doc_referents.append((gazetteer_name, toponym["loc_id"]))
379 else:
380 # Non-geocoded: use None so resolver skips it
381 doc_referents.append(None)
383 referents.append(doc_referents)
385 # Create documents in the project if requested
386 if create_documents:
387 self.create_documents(texts)
389 # Create references and referents using the extracted methods
390 self.create_references(texts, references, tag)
391 self.create_referents(texts, references, referents, tag)
393 def delete(self) -> None:
394 """
395 Delete this project and all its associated data from the database.
397 This will remove the project, all its documents, references, referents,
398 recognitions, and resolutions due to cascade delete relationships.
399 """
400 with get_session() as session:
401 ProjectRepository.delete(session, id=self.id)