Coverage for geoparser/geoparser/geoparser.py: 100%
26 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 uuid
2from typing import List, Optional, Sequence, Union, overload
4from geoparser.db.models import Document
5from geoparser.modules.recognizers import Recognizer
6from geoparser.modules.resolvers import Resolver
7from geoparser.project import Project
10class Geoparser:
11 """
12 User-facing interface for the geoparser functionality.
14 Provides a simple parse method for processing texts with configured recognizer and resolver.
15 The Geoparser creates a new project for each parse operation, making it stateless by default.
17 The recognizer and resolver have to be provided explicitly, so that it is
18 always clear which modules a pipeline is built from::
20 from geoparser import Geoparser
21 from geoparser.modules import SentenceTransformerResolver, SpacyRecognizer
23 geoparser = Geoparser(
24 recognizer=SpacyRecognizer(),
25 resolver=SentenceTransformerResolver(gazetteer_name="geonames"),
26 )
27 """
29 def __init__(
30 self,
31 recognizer: Optional[Recognizer],
32 resolver: Optional[Resolver],
33 ):
34 """
35 Initialize a Geoparser instance.
37 Args:
38 recognizer: The recognizer module to use for identifying references,
39 or None to skip the recognition step.
40 resolver: The resolver module to use for resolving references to referents,
41 or None to skip the resolution step.
42 """
43 self.recognizer = recognizer
44 self.resolver = resolver
46 @overload
47 def parse(self, texts: str, save: bool = False) -> Document: ...
49 @overload
50 def parse(self, texts: Sequence[str], save: bool = False) -> List[Document]: ...
52 def parse(
53 self, texts: Union[str, Sequence[str]], save: bool = False
54 ) -> Union[Document, List[Document]]:
55 """
56 Parse one or more texts with the configured recognizer and resolver.
58 The result mirrors the input: a single text is parsed into a single
59 document, while a sequence of texts is parsed into a list of documents
60 in the same order as the texts that were passed in.
62 This method creates a new project for each parse operation, processes the texts,
63 and returns the results. By default, the project is deleted after processing
64 to keep the parse method stateless.
66 Args:
67 texts: Either a single document text or a sequence of texts
68 save: If True, preserve the project after processing. If False (default),
69 delete the project to maintain stateless behavior.
71 Returns:
72 A single Document if a single text was passed, or a list of Documents
73 if a sequence of texts was passed, with processed references and
74 referents from the configured recognizer and resolver.
75 """
76 # A single text is parsed into a single document, so remember which
77 # shape was asked for before normalizing the input
78 single_text = isinstance(texts, str)
80 # Create a new project for this parse operation
81 project_name = uuid.uuid4().hex[:8]
82 project = Project(project_name)
84 try:
85 # Create documents in the project
86 document_ids = project.create_documents([texts] if single_text else texts)
88 # Run the recognizer on all documents (if provided)
89 if self.recognizer is not None:
90 project.run_recognizer(self.recognizer)
92 # Run the resolver on all documents (if provided)
93 if self.resolver is not None:
94 project.run_resolver(self.resolver)
96 # Get the documents back in input order, with results from our
97 # specific recognizer and resolver
98 documents = project.get_documents(ids=document_ids)
100 # If save is True, inform the user about the project name
101 if save:
102 print(f"Results saved under project name: {project_name}")
104 return documents[0] if single_text else documents
106 finally:
107 # Clean up the project unless the user wants to save it
108 if not save:
109 project.delete()