etter

etter - Natural language geographic query parsing using LLMs.

Parse location queries into structured geographic queries using LLM.

 1"""
 2etter - Natural language geographic query parsing using LLMs.
 3
 4Parse location queries into structured geographic queries using LLM.
 5"""
 6
 7from importlib.metadata import PackageNotFoundError, version
 8
 9try:
10    __version__ = version("etter")
11except PackageNotFoundError:  # running from source without install
12    __version__ = "unknown"
13
14# Main API
15# Exceptions
16# Datasources
17from .datasources import (
18    CompositeDataSource,
19    GeoDataSource,
20    IGNBDCartoSource,
21    PostGISDataSource,
22    SwissBoundaries3DSource,
23    SwissNames3DSource,
24)
25from .exceptions import (
26    GeoFilterError,
27    LLMInvocationError,
28    LowConfidenceError,
29    LowConfidenceWarning,
30    NoReferenceLocationError,
31    ParsingError,
32    UnknownRelationError,
33    ValidationError,
34)
35from .geometry_format import convert_feature_geometry, convert_geometry
36
37# Models (for type hints and result access)
38from .models import (
39    BufferConfig,
40    ConfidenceLevel,
41    ConfidenceScore,
42    GeometryFormat,
43    GeoQuery,
44    ReferenceLocation,
45    SpatialRelation,
46)
47from .parser import GeoFilterParser
48
49# Prompts
50from .prompts import build_geo_prompt_template
51
52# Spatial operations
53from .spatial import apply_spatial_relation
54
55# Configuration
56from .spatial_config import RelationConfig, SpatialRelationConfig
57
58# Validation
59from .validators import finalize_geo_query
60
61__all__ = [
62    # Main API
63    "GeoFilterParser",
64    # Prompts
65    "build_geo_prompt_template",
66    # Validation
67    "finalize_geo_query",
68    # Models
69    "GeoQuery",
70    "SpatialRelation",
71    "ReferenceLocation",
72    "BufferConfig",
73    "ConfidenceScore",
74    "ConfidenceLevel",
75    "GeometryFormat",
76    # Configuration
77    "SpatialRelationConfig",
78    "RelationConfig",
79    # Exceptions
80    "GeoFilterError",
81    "ParsingError",
82    "LLMInvocationError",
83    "ValidationError",
84    "NoReferenceLocationError",
85    "UnknownRelationError",
86    "LowConfidenceError",
87    "LowConfidenceWarning",
88    # Datasources
89    "GeoDataSource",
90    "SwissNames3DSource",
91    "SwissBoundaries3DSource",
92    "IGNBDCartoSource",
93    "CompositeDataSource",
94    "PostGISDataSource",
95    # Spatial
96    "apply_spatial_relation",
97    "convert_geometry",
98    "convert_feature_geometry",
99]
class GeoFilterParser:
 20class GeoFilterParser:
 21    """
 22    Main entry point for parsing natural language location queries.
 23
 24    This class orchestrates the entire parsing pipeline:
 25    1. Initialize LLM with structured output
 26    2. Build prompt with spatial relations and examples
 27    3. Parse query through LLM
 28    4. Validate and enrich with defaults
 29    5. Return structured GeoQuery
 30
 31    Examples:
 32        Basic usage:
 33        >>> from langchain.chat_models import init_chat_model
 34        >>> llm = init_chat_model(model="gpt-4o", api_key="sk-...")
 35        >>> parser = GeoFilterParser(llm=llm)
 36        >>> result = parser.parse("restaurants in Lausanne")
 37        >>> print(result.reference_location.name)
 38        'Lausanne'
 39
 40        With strict confidence mode:
 41        >>> parser = GeoFilterParser(llm=llm, confidence_threshold=0.8, strict_mode=True)
 42        >>> result = parser.parse("near the station")  # May raise LowConfidenceError
 43    """
 44
 45    def __init__(
 46        self,
 47        llm: BaseChatModel,
 48        spatial_config: SpatialRelationConfig | None = None,
 49        confidence_threshold: float = 0.6,
 50        strict_mode: bool = False,
 51        include_examples: bool = True,
 52        datasource: GeoDataSource | None = None,
 53        additional_instructions: str | None = None,
 54    ):
 55        """
 56        Initialize the parser.
 57
 58        Args:
 59            llm: LangChain LLM instance (required).
 60            spatial_config: Spatial relation configuration. If None, uses defaults
 61            confidence_threshold: Minimum confidence to accept (0-1)
 62            strict_mode: If True, raise error on low confidence. If False, warn only
 63            include_examples: Whether to include few-shot examples in prompt
 64            datasource: Optional GeoDataSource instance. If provided, the LLM will be informed
 65                       about the concrete types available in that datasource for better type inference.
 66            additional_instructions: Free-form text injected as a system message after the main
 67                       system prompt and before few-shot examples. Use this to add caller-specific
 68                       rules such as region-specific endonyms, domain aliases, or
 69                       organization-specific place names without forking the default prompt.
 70
 71        Example:
 72            >>> from langchain.chat_models import init_chat_model
 73            >>> from etter.datasources.swissnames3d import SwissNames3DSource
 74            >>> llm = init_chat_model(model="gpt-4o", temperature=0)
 75            >>> datasource = SwissNames3DSource("data/")
 76            >>> parser = GeoFilterParser(llm=llm, datasource=datasource)
 77        """
 78        self.llm = llm
 79
 80        # Initialize spatial config
 81        self.spatial_config = spatial_config or SpatialRelationConfig()
 82
 83        # Settings
 84        self.confidence_threshold = confidence_threshold
 85        self.strict_mode = strict_mode
 86        self.include_examples = include_examples
 87        self.datasource = datasource
 88        self.additional_instructions = additional_instructions
 89
 90        # Build structured LLM
 91        self.structured_llm = self._build_structured_llm()
 92
 93        # Build prompt template
 94        self.prompt = self._build_prompt()
 95
 96    def _build_structured_llm(self):
 97        """Create LLM with structured output using Pydantic model."""
 98
 99        return self.llm.with_structured_output(
100            GeoQuery,
101            method="function_calling",  # Use function_calling for broader schema support
102            include_raw=True,  # For error debugging
103        )
104
105    def _build_prompt(self) -> ChatPromptTemplate:
106        """Build prompt template with spatial relations, examples, and available types."""
107        available_types = None
108        if self.datasource is not None:
109            available_types = self.datasource.get_available_types()
110
111        return build_geo_prompt_template(
112            spatial_config=self.spatial_config,
113            include_examples=self.include_examples,
114            available_types=available_types,
115            additional_instructions=self.additional_instructions,
116        )
117
118    def _unpack_response(self, response) -> GeoQuery:
119        """Extract and validate the GeoQuery from a structured-LLM response."""
120        parsed = response.get("parsed") if isinstance(response, dict) else response
121
122        if parsed is None:
123            raw = response.get("raw", "") if isinstance(response, dict) else ""
124            error = response.get("parsing_error") if isinstance(response, dict) else None
125            raise ParsingError(
126                message="Failed to parse query into structured format. "
127                "LLM may have returned invalid JSON or missed required fields.",
128                raw_response=str(raw),
129                original_error=error,
130            )
131
132        if not isinstance(parsed, GeoQuery):
133            raise ParsingError(
134                message=f"Expected GeoQuery, got {type(parsed).__name__}",
135                raw_response=str(parsed),
136            )
137        return parsed
138
139    def _finalize(self, geo_query: GeoQuery, query: str) -> GeoQuery:
140        """Set original_query and run the validation pipeline."""
141        return finalize_geo_query(
142            geo_query,
143            self.spatial_config,
144            query,
145            confidence_threshold=self.confidence_threshold,
146            strict_mode=self.strict_mode,
147        )
148
149    def parse(self, query: str) -> GeoQuery:
150        """
151        Parse a natural language location query into structured format.
152
153        This is the main method for parsing queries. It:
154        1. Invokes the LLM with structured output
155        2. Validates the spatial relation is registered
156        3. Enriches with default parameters
157        4. Checks confidence threshold
158
159        Args:
160            query: Natural language query in any language
161
162        Returns:
163            GeoQuery: Structured query representation with confidence scores
164
165        Raises:
166            ParsingError: If LLM fails to parse query into valid structure
167            ValidationError: If parsed query fails business logic validation
168            UnknownRelationError: If spatial relation is not registered
169            LowConfidenceError: If confidence below threshold (strict mode only)
170
171        Warns:
172            LowConfidenceWarning: If confidence below threshold (permissive mode)
173
174        Examples:
175            Simple containment query:
176            >>> result = parser.parse("in Bern")
177            >>> result.reference_location.name
178            'Bern'
179            >>> result.spatial_relation.relation
180            'in'
181
182            Buffer query:
183            >>> result = parser.parse("near Lake Geneva")
184            >>> result.spatial_relation.relation
185            'near'
186            >>> result.buffer_config.distance_m
187            5000
188
189            Directional query:
190            >>> result = parser.parse("north of Lausanne")
191            >>> result.spatial_relation.relation
192            'north_of'
193            >>> result.reference_location.name
194            'Lausanne'
195
196            Multilingual:
197            >>> result = parser.parse("près de Genève")
198            >>> result.spatial_relation.relation
199            'near'
200            >>> result.reference_location.name
201            'Genève'
202        """
203        formatted_messages = self.prompt.format_messages(query=query)
204
205        try:
206            response = self.structured_llm.invoke(formatted_messages)
207        except Exception as e:
208            raise LLMInvocationError(
209                message=f"LLM invocation failed: {str(e)}",
210                raw_response="",
211                original_error=e,
212            ) from e
213
214        return self._finalize(self._unpack_response(response), query)
215
216    async def aparse(self, query: str) -> GeoQuery:
217        """
218        Asynchronously parse a natural language location query into structured format.
219
220        Async counterpart to :meth:`parse`. Uses ``ainvoke`` on the structured LLM
221        so it can be awaited inside event loops (e.g. FastAPI endpoints) without
222        blocking. Validation is synchronous and runs after the LLM call.
223        """
224        formatted_messages = self.prompt.format_messages(query=query)
225
226        try:
227            response = await self.structured_llm.ainvoke(formatted_messages)
228        except Exception as e:
229            raise LLMInvocationError(
230                message=f"LLM invocation failed: {str(e)}",
231                raw_response="",
232                original_error=e,
233            ) from e
234
235        return self._finalize(self._unpack_response(response), query)
236
237    async def parse_stream(self, query: str) -> AsyncGenerator[dict]:
238        """
239        Parse a natural language location query with streaming reasoning and results.
240
241        This method provides real-time feedback during the parsing process by yielding
242        intermediate reasoning steps and the final GeoQuery result. This is useful for
243        providing users with transparency into the LLM's decision-making process and
244        for building responsive UIs.
245
246        The stream yields dictionaries with the following event types:
247        - {"type": "start"} - Stream started
248        - {"type": "reasoning", "content": str} - Intermediate processing steps
249        - {"type": "data-response", "content": dict} - Final GeoQuery as JSON
250        - {"type": "error", "content": str} - Errors encountered during processing
251        - {"type": "finish"} - Stream completed successfully
252
253        Args:
254            query: Natural language query in any language
255
256        Yields:
257            dict: Stream events with type and optional content fields
258
259        Raises:
260            ParsingError: If LLM fails to parse query into valid structure
261            ValidationError: If parsed query fails business logic validation
262            UnknownRelationError: If spatial relation is not registered
263            LowConfidenceError: If confidence below threshold (strict mode only)
264
265        Examples:
266            Basic usage with async iteration:
267            >>> async for event in parser.parse_stream("restaurants near Lake Geneva"):
268            ...     if event["type"] == "reasoning":
269            ...         print(f"Reasoning: {event['content']}")
270            ...     elif event["type"] == "data-response":
271            ...         geo_query = event["content"]
272            ...         print(f"Location: {geo_query['reference_location']['name']}")
273            ...     elif event["type"] == "error":
274            ...         print(f"Error: {event['content']}")
275
276            Using in a FastAPI streaming endpoint:
277            >>> from fastapi.responses import StreamingResponse
278            >>> @app.get("/stream")
279            >>> async def stream_endpoint(q: str):
280            ...     async def event_stream():
281            ...         async for event in parser.parse_stream(q):
282            ...             yield f"data: {json.dumps(event)}\\n\\n"
283            ...     return StreamingResponse(event_stream(), media_type="text/event-stream")
284        """
285        try:
286            # Signal start of stream
287            yield {"type": "start"}
288
289            yield {"type": "reasoning", "content": "Preparing query for LLM processing"}
290            formatted_messages = self.prompt.format_messages(query=query)
291
292            yield {"type": "reasoning", "content": "Analyzing spatial relationship and location"}
293            try:
294                response = await self.structured_llm.ainvoke(formatted_messages)
295            except Exception as e:
296                yield {"type": "error", "content": f"LLM invocation failed: {str(e)}"}
297                raise LLMInvocationError(
298                    message=f"LLM invocation failed: {str(e)}",
299                    raw_response="",
300                    original_error=e,
301                ) from e
302
303            yield {"type": "reasoning", "content": "Parsing LLM response into structured format"}
304            try:
305                geo_query = self._unpack_response(response)
306            except ParsingError:
307                yield {"type": "error", "content": "Failed to parse response - invalid JSON or missing fields"}
308                raise
309
310            if geo_query.confidence_breakdown.reasoning:
311                yield {
312                    "type": "reasoning",
313                    "content": f"LLM reasoning: {geo_query.confidence_breakdown.reasoning}",
314                }
315
316            yield {"type": "reasoning", "content": "Validating spatial relation configuration"}
317            geo_query = self._finalize(geo_query, query)
318
319            yield {"type": "reasoning", "content": "Query parsing completed successfully"}
320            yield {"type": "data-response", "content": geo_query.model_dump()}
321
322            # Signal successful completion
323            yield {"type": "finish"}
324
325        except ParsingError:
326            # Already reported by a specific error event above
327            raise
328        except Exception as e:
329            # Emit error event before re-raising
330            yield {"type": "error", "content": f"Error during parsing: {str(e)}"}
331            raise
332
333    def parse_batch(self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
334        """
335        Parse multiple queries.
336
337        Args:
338            queries: List of natural language queries
339            max_concurrency: Number of queries parsed in parallel (threads). Keep it within
340                the provider's rate limit and configure retries on the LLM (e.g.
341                ``max_retries``) before raising it above 1.
342
343        Returns:
344            List of GeoQuery objects (same order as input)
345
346        Raises:
347            Same exceptions as parse() for any failing query
348        """
349        return RunnableLambda(self.parse).batch(queries, config={"max_concurrency": max_concurrency})
350
351    async def aparse_batch(self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
352        """
353        Async counterpart to :meth:`parse_batch`, built on :meth:`aparse`.
354
355        Args:
356            queries: List of natural language queries
357            max_concurrency: Number of LLM calls in flight at once
358
359        Returns:
360            List of GeoQuery objects (same order as input)
361        """
362        return await RunnableLambda(self.aparse).abatch(queries, config={"max_concurrency": max_concurrency})
363
364    def get_available_relations(self, category: RelationCategory | None = None) -> list[str]:
365        """
366        Get list of available spatial relations.
367
368        Args:
369            category: Optional filter by category ("containment", "buffer", "directional")
370
371        Returns:
372            List of relation names
373        """
374        return self.spatial_config.list_relations(category=category)
375
376    def describe_relation(self, relation_name: str) -> str:
377        """
378        Get description of a spatial relation.
379
380        Args:
381            relation_name: Name of the relation
382
383        Returns:
384            Human-readable description
385
386        Raises:
387            UnknownRelationError: If relation is not registered
388        """
389        config = self.spatial_config.get_config(relation_name)
390        return config.description

Main entry point for parsing natural language location queries.

This class orchestrates the entire parsing pipeline:

  1. Initialize LLM with structured output
  2. Build prompt with spatial relations and examples
  3. Parse query through LLM
  4. Validate and enrich with defaults
  5. Return structured GeoQuery
Examples:

Basic usage:

>>> from langchain.chat_models import init_chat_model
>>> llm = init_chat_model(model="gpt-4o", api_key="sk-...")
>>> parser = GeoFilterParser(llm=llm)
>>> result = parser.parse("restaurants in Lausanne")
>>> print(result.reference_location.name)
'Lausanne'

With strict confidence mode:

>>> parser = GeoFilterParser(llm=llm, confidence_threshold=0.8, strict_mode=True)
>>> result = parser.parse("near the station")  # May raise LowConfidenceError
GeoFilterParser( llm: langchain_core.language_models.chat_models.BaseChatModel, spatial_config: SpatialRelationConfig | None = None, confidence_threshold: float = 0.6, strict_mode: bool = False, include_examples: bool = True, datasource: GeoDataSource | None = None, additional_instructions: str | None = None)
45    def __init__(
46        self,
47        llm: BaseChatModel,
48        spatial_config: SpatialRelationConfig | None = None,
49        confidence_threshold: float = 0.6,
50        strict_mode: bool = False,
51        include_examples: bool = True,
52        datasource: GeoDataSource | None = None,
53        additional_instructions: str | None = None,
54    ):
55        """
56        Initialize the parser.
57
58        Args:
59            llm: LangChain LLM instance (required).
60            spatial_config: Spatial relation configuration. If None, uses defaults
61            confidence_threshold: Minimum confidence to accept (0-1)
62            strict_mode: If True, raise error on low confidence. If False, warn only
63            include_examples: Whether to include few-shot examples in prompt
64            datasource: Optional GeoDataSource instance. If provided, the LLM will be informed
65                       about the concrete types available in that datasource for better type inference.
66            additional_instructions: Free-form text injected as a system message after the main
67                       system prompt and before few-shot examples. Use this to add caller-specific
68                       rules such as region-specific endonyms, domain aliases, or
69                       organization-specific place names without forking the default prompt.
70
71        Example:
72            >>> from langchain.chat_models import init_chat_model
73            >>> from etter.datasources.swissnames3d import SwissNames3DSource
74            >>> llm = init_chat_model(model="gpt-4o", temperature=0)
75            >>> datasource = SwissNames3DSource("data/")
76            >>> parser = GeoFilterParser(llm=llm, datasource=datasource)
77        """
78        self.llm = llm
79
80        # Initialize spatial config
81        self.spatial_config = spatial_config or SpatialRelationConfig()
82
83        # Settings
84        self.confidence_threshold = confidence_threshold
85        self.strict_mode = strict_mode
86        self.include_examples = include_examples
87        self.datasource = datasource
88        self.additional_instructions = additional_instructions
89
90        # Build structured LLM
91        self.structured_llm = self._build_structured_llm()
92
93        # Build prompt template
94        self.prompt = self._build_prompt()

Initialize the parser.

Arguments:
  • llm: LangChain LLM instance (required).
  • spatial_config: Spatial relation configuration. If None, uses defaults
  • confidence_threshold: Minimum confidence to accept (0-1)
  • strict_mode: If True, raise error on low confidence. If False, warn only
  • include_examples: Whether to include few-shot examples in prompt
  • datasource: Optional GeoDataSource instance. If provided, the LLM will be informed about the concrete types available in that datasource for better type inference.
  • additional_instructions: Free-form text injected as a system message after the main system prompt and before few-shot examples. Use this to add caller-specific rules such as region-specific endonyms, domain aliases, or organization-specific place names without forking the default prompt.
Example:
>>> from langchain.chat_models import init_chat_model
>>> from etter.datasources.swissnames3d import SwissNames3DSource
>>> llm = init_chat_model(model="gpt-4o", temperature=0)
>>> datasource = SwissNames3DSource("data/")
>>> parser = GeoFilterParser(llm=llm, datasource=datasource)
llm
spatial_config
confidence_threshold
strict_mode
include_examples
datasource
additional_instructions
structured_llm
prompt
def parse(self, query: str) -> GeoQuery:
149    def parse(self, query: str) -> GeoQuery:
150        """
151        Parse a natural language location query into structured format.
152
153        This is the main method for parsing queries. It:
154        1. Invokes the LLM with structured output
155        2. Validates the spatial relation is registered
156        3. Enriches with default parameters
157        4. Checks confidence threshold
158
159        Args:
160            query: Natural language query in any language
161
162        Returns:
163            GeoQuery: Structured query representation with confidence scores
164
165        Raises:
166            ParsingError: If LLM fails to parse query into valid structure
167            ValidationError: If parsed query fails business logic validation
168            UnknownRelationError: If spatial relation is not registered
169            LowConfidenceError: If confidence below threshold (strict mode only)
170
171        Warns:
172            LowConfidenceWarning: If confidence below threshold (permissive mode)
173
174        Examples:
175            Simple containment query:
176            >>> result = parser.parse("in Bern")
177            >>> result.reference_location.name
178            'Bern'
179            >>> result.spatial_relation.relation
180            'in'
181
182            Buffer query:
183            >>> result = parser.parse("near Lake Geneva")
184            >>> result.spatial_relation.relation
185            'near'
186            >>> result.buffer_config.distance_m
187            5000
188
189            Directional query:
190            >>> result = parser.parse("north of Lausanne")
191            >>> result.spatial_relation.relation
192            'north_of'
193            >>> result.reference_location.name
194            'Lausanne'
195
196            Multilingual:
197            >>> result = parser.parse("près de Genève")
198            >>> result.spatial_relation.relation
199            'near'
200            >>> result.reference_location.name
201            'Genève'
202        """
203        formatted_messages = self.prompt.format_messages(query=query)
204
205        try:
206            response = self.structured_llm.invoke(formatted_messages)
207        except Exception as e:
208            raise LLMInvocationError(
209                message=f"LLM invocation failed: {str(e)}",
210                raw_response="",
211                original_error=e,
212            ) from e
213
214        return self._finalize(self._unpack_response(response), query)

Parse a natural language location query into structured format.

This is the main method for parsing queries. It:

  1. Invokes the LLM with structured output
  2. Validates the spatial relation is registered
  3. Enriches with default parameters
  4. Checks confidence threshold
Arguments:
  • query: Natural language query in any language
Returns:

GeoQuery: Structured query representation with confidence scores

Raises:
  • ParsingError: If LLM fails to parse query into valid structure
  • ValidationError: If parsed query fails business logic validation
  • UnknownRelationError: If spatial relation is not registered
  • LowConfidenceError: If confidence below threshold (strict mode only)
Warns:

LowConfidenceWarning: If confidence below threshold (permissive mode)

Examples:

Simple containment query:

>>> result = parser.parse("in Bern")
>>> result.reference_location.name
'Bern'
>>> result.spatial_relation.relation
'in'

Buffer query:

>>> result = parser.parse("near Lake Geneva")
>>> result.spatial_relation.relation
'near'
>>> result.buffer_config.distance_m
5000

Directional query:

>>> result = parser.parse("north of Lausanne")
>>> result.spatial_relation.relation
'north_of'
>>> result.reference_location.name
'Lausanne'

Multilingual:

>>> result = parser.parse("près de Genève")
>>> result.spatial_relation.relation
'near'
>>> result.reference_location.name
'Genève'
async def aparse(self, query: str) -> GeoQuery:
216    async def aparse(self, query: str) -> GeoQuery:
217        """
218        Asynchronously parse a natural language location query into structured format.
219
220        Async counterpart to :meth:`parse`. Uses ``ainvoke`` on the structured LLM
221        so it can be awaited inside event loops (e.g. FastAPI endpoints) without
222        blocking. Validation is synchronous and runs after the LLM call.
223        """
224        formatted_messages = self.prompt.format_messages(query=query)
225
226        try:
227            response = await self.structured_llm.ainvoke(formatted_messages)
228        except Exception as e:
229            raise LLMInvocationError(
230                message=f"LLM invocation failed: {str(e)}",
231                raw_response="",
232                original_error=e,
233            ) from e
234
235        return self._finalize(self._unpack_response(response), query)

Asynchronously parse a natural language location query into structured format.

Async counterpart to parse(). Uses ainvoke on the structured LLM so it can be awaited inside event loops (e.g. FastAPI endpoints) without blocking. Validation is synchronous and runs after the LLM call.

async def parse_stream(self, query: str) -> AsyncGenerator[dict]:
237    async def parse_stream(self, query: str) -> AsyncGenerator[dict]:
238        """
239        Parse a natural language location query with streaming reasoning and results.
240
241        This method provides real-time feedback during the parsing process by yielding
242        intermediate reasoning steps and the final GeoQuery result. This is useful for
243        providing users with transparency into the LLM's decision-making process and
244        for building responsive UIs.
245
246        The stream yields dictionaries with the following event types:
247        - {"type": "start"} - Stream started
248        - {"type": "reasoning", "content": str} - Intermediate processing steps
249        - {"type": "data-response", "content": dict} - Final GeoQuery as JSON
250        - {"type": "error", "content": str} - Errors encountered during processing
251        - {"type": "finish"} - Stream completed successfully
252
253        Args:
254            query: Natural language query in any language
255
256        Yields:
257            dict: Stream events with type and optional content fields
258
259        Raises:
260            ParsingError: If LLM fails to parse query into valid structure
261            ValidationError: If parsed query fails business logic validation
262            UnknownRelationError: If spatial relation is not registered
263            LowConfidenceError: If confidence below threshold (strict mode only)
264
265        Examples:
266            Basic usage with async iteration:
267            >>> async for event in parser.parse_stream("restaurants near Lake Geneva"):
268            ...     if event["type"] == "reasoning":
269            ...         print(f"Reasoning: {event['content']}")
270            ...     elif event["type"] == "data-response":
271            ...         geo_query = event["content"]
272            ...         print(f"Location: {geo_query['reference_location']['name']}")
273            ...     elif event["type"] == "error":
274            ...         print(f"Error: {event['content']}")
275
276            Using in a FastAPI streaming endpoint:
277            >>> from fastapi.responses import StreamingResponse
278            >>> @app.get("/stream")
279            >>> async def stream_endpoint(q: str):
280            ...     async def event_stream():
281            ...         async for event in parser.parse_stream(q):
282            ...             yield f"data: {json.dumps(event)}\\n\\n"
283            ...     return StreamingResponse(event_stream(), media_type="text/event-stream")
284        """
285        try:
286            # Signal start of stream
287            yield {"type": "start"}
288
289            yield {"type": "reasoning", "content": "Preparing query for LLM processing"}
290            formatted_messages = self.prompt.format_messages(query=query)
291
292            yield {"type": "reasoning", "content": "Analyzing spatial relationship and location"}
293            try:
294                response = await self.structured_llm.ainvoke(formatted_messages)
295            except Exception as e:
296                yield {"type": "error", "content": f"LLM invocation failed: {str(e)}"}
297                raise LLMInvocationError(
298                    message=f"LLM invocation failed: {str(e)}",
299                    raw_response="",
300                    original_error=e,
301                ) from e
302
303            yield {"type": "reasoning", "content": "Parsing LLM response into structured format"}
304            try:
305                geo_query = self._unpack_response(response)
306            except ParsingError:
307                yield {"type": "error", "content": "Failed to parse response - invalid JSON or missing fields"}
308                raise
309
310            if geo_query.confidence_breakdown.reasoning:
311                yield {
312                    "type": "reasoning",
313                    "content": f"LLM reasoning: {geo_query.confidence_breakdown.reasoning}",
314                }
315
316            yield {"type": "reasoning", "content": "Validating spatial relation configuration"}
317            geo_query = self._finalize(geo_query, query)
318
319            yield {"type": "reasoning", "content": "Query parsing completed successfully"}
320            yield {"type": "data-response", "content": geo_query.model_dump()}
321
322            # Signal successful completion
323            yield {"type": "finish"}
324
325        except ParsingError:
326            # Already reported by a specific error event above
327            raise
328        except Exception as e:
329            # Emit error event before re-raising
330            yield {"type": "error", "content": f"Error during parsing: {str(e)}"}
331            raise

Parse a natural language location query with streaming reasoning and results.

This method provides real-time feedback during the parsing process by yielding intermediate reasoning steps and the final GeoQuery result. This is useful for providing users with transparency into the LLM's decision-making process and for building responsive UIs.

The stream yields dictionaries with the following event types:

  • {"type": "start"} - Stream started
  • {"type": "reasoning", "content": str} - Intermediate processing steps
  • {"type": "data-response", "content": dict} - Final GeoQuery as JSON
  • {"type": "error", "content": str} - Errors encountered during processing
  • {"type": "finish"} - Stream completed successfully
Arguments:
  • query: Natural language query in any language
Yields:

dict: Stream events with type and optional content fields

Raises:
  • ParsingError: If LLM fails to parse query into valid structure
  • ValidationError: If parsed query fails business logic validation
  • UnknownRelationError: If spatial relation is not registered
  • LowConfidenceError: If confidence below threshold (strict mode only)
Examples:

Basic usage with async iteration:

>>> async for event in parser.parse_stream("restaurants near Lake Geneva"):
...     if event["type"] == "reasoning":
...         print(f"Reasoning: {event['content']}")
...     elif event["type"] == "data-response":
...         geo_query = event["content"]
...         print(f"Location: {geo_query['reference_location']['name']}")
...     elif event["type"] == "error":
...         print(f"Error: {event['content']}")

Using in a FastAPI streaming endpoint:

>>> from fastapi.responses import StreamingResponse
>>> @app.get("/stream")
>>> async def stream_endpoint(q: str):
...     async def event_stream():
...         async for event in parser.parse_stream(q):
...             yield f"data: {json.dumps(event)}\n\n"
...     return StreamingResponse(event_stream(), media_type="text/event-stream")
def parse_batch( self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
333    def parse_batch(self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
334        """
335        Parse multiple queries.
336
337        Args:
338            queries: List of natural language queries
339            max_concurrency: Number of queries parsed in parallel (threads). Keep it within
340                the provider's rate limit and configure retries on the LLM (e.g.
341                ``max_retries``) before raising it above 1.
342
343        Returns:
344            List of GeoQuery objects (same order as input)
345
346        Raises:
347            Same exceptions as parse() for any failing query
348        """
349        return RunnableLambda(self.parse).batch(queries, config={"max_concurrency": max_concurrency})

Parse multiple queries.

Arguments:
  • queries: List of natural language queries
  • max_concurrency: Number of queries parsed in parallel (threads). Keep it within the provider's rate limit and configure retries on the LLM (e.g. max_retries) before raising it above 1.
Returns:

List of GeoQuery objects (same order as input)

Raises:
  • Same exceptions as parse() for any failing query
async def aparse_batch( self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
351    async def aparse_batch(self, queries: list[str], max_concurrency: int = 1) -> list[GeoQuery]:
352        """
353        Async counterpart to :meth:`parse_batch`, built on :meth:`aparse`.
354
355        Args:
356            queries: List of natural language queries
357            max_concurrency: Number of LLM calls in flight at once
358
359        Returns:
360            List of GeoQuery objects (same order as input)
361        """
362        return await RunnableLambda(self.aparse).abatch(queries, config={"max_concurrency": max_concurrency})

Async counterpart to parse_batch(), built on aparse().

Arguments:
  • queries: List of natural language queries
  • max_concurrency: Number of LLM calls in flight at once
Returns:

List of GeoQuery objects (same order as input)

def get_available_relations( self, category: Optional[Literal['containment', 'buffer', 'directional', 'clipping']] = None) -> list[str]:
364    def get_available_relations(self, category: RelationCategory | None = None) -> list[str]:
365        """
366        Get list of available spatial relations.
367
368        Args:
369            category: Optional filter by category ("containment", "buffer", "directional")
370
371        Returns:
372            List of relation names
373        """
374        return self.spatial_config.list_relations(category=category)

Get list of available spatial relations.

Arguments:
  • category: Optional filter by category ("containment", "buffer", "directional")
Returns:

List of relation names

def describe_relation(self, relation_name: str) -> str:
376    def describe_relation(self, relation_name: str) -> str:
377        """
378        Get description of a spatial relation.
379
380        Args:
381            relation_name: Name of the relation
382
383        Returns:
384            Human-readable description
385
386        Raises:
387            UnknownRelationError: If relation is not registered
388        """
389        config = self.spatial_config.get_config(relation_name)
390        return config.description

Get description of a spatial relation.

Arguments:
  • relation_name: Name of the relation
Returns:

Human-readable description

Raises:
  • UnknownRelationError: If relation is not registered
def build_geo_prompt_template( spatial_config: SpatialRelationConfig, include_examples: bool = True, available_types: list[str] | None = None, additional_instructions: str | None = None) -> langchain_core.prompts.chat.ChatPromptTemplate:
127def build_geo_prompt_template(
128    spatial_config: SpatialRelationConfig,
129    include_examples: bool = True,
130    available_types: list[str] | None = None,
131    additional_instructions: str | None = None,
132) -> ChatPromptTemplate:
133    """
134    Build complete prompt template with system message, examples, and user message.
135
136    Args:
137        spatial_config: Spatial relation configuration for injecting available relations
138        include_examples: Whether to include few-shot examples (default: True)
139        available_types: Concrete types available in the datasource (e.g., ["lake", "river", "city"]).
140                        If provided, will be included in the prompt to help the LLM choose appropriate types.
141        additional_instructions: Free-form text injected as a system message after the main system prompt. Use this to inject
142                                 caller-specific rules (region-specific endonyms, domain aliases,
143                                 organization-specific place names) without forking the default prompt.
144
145    Returns:
146        ChatPromptTemplate ready for formatting
147    """
148    messages = []
149
150    # System message with spatial relations - inject the spatial_relations here
151    spatial_relations_text = format_spatial_relations(spatial_config)
152
153    # Format available types info if provided
154    available_types_info = ""
155    if available_types:
156        available_types_info = f"""
157Available Concrete Types in This Datasource:
158The following {len(available_types)} concrete types are available in the datasource:
159{", ".join(sorted(available_types))}
160
161When inferring type, prefer these concrete types for better matching."""
162
163    system_prompt = SYSTEM_PROMPT.format(
164        spatial_relations=spatial_relations_text, available_types_info=available_types_info
165    )
166    # Escape braces for ChatPromptTemplate
167    system_prompt = system_prompt.replace("{", "{{").replace("}", "}}")
168    messages.append(("system", system_prompt))
169
170    if additional_instructions:
171        escaped = additional_instructions.replace("{", "{{").replace("}", "}}")
172        messages.append(("system", escaped))
173
174    # Few-shot examples (optional but recommended)
175    if include_examples:
176        examples_text = format_examples_for_prompt()
177        examples_message = f"""EXAMPLES:
178
179The following examples demonstrate correct parsing for various query types:
180
181{examples_text}"""
182        # Escape braces for ChatPromptTemplate
183        examples_message = examples_message.replace("{", "{{").replace("}", "}}")
184        messages.append(("system", examples_message))
185
186    # User message template - only this has a placeholder for format_messages
187    messages.append(("user", USER_TEMPLATE))
188
189    return ChatPromptTemplate.from_messages(messages)

Build complete prompt template with system message, examples, and user message.

Arguments:
  • spatial_config: Spatial relation configuration for injecting available relations
  • include_examples: Whether to include few-shot examples (default: True)
  • available_types: Concrete types available in the datasource (e.g., ["lake", "river", "city"]). If provided, will be included in the prompt to help the LLM choose appropriate types.
  • additional_instructions: Free-form text injected as a system message after the main system prompt. Use this to inject caller-specific rules (region-specific endonyms, domain aliases, organization-specific place names) without forking the default prompt.
Returns:

ChatPromptTemplate ready for formatting

def finalize_geo_query( geo_query: GeoQuery, spatial_config: SpatialRelationConfig, query: str, confidence_threshold: float = 0.6, strict_mode: bool = False) -> GeoQuery:
173def finalize_geo_query(
174    geo_query: GeoQuery,
175    spatial_config: SpatialRelationConfig,
176    query: str,
177    confidence_threshold: float = 0.6,
178    strict_mode: bool = False,
179) -> GeoQuery:
180    """
181    Set original_query and run the complete validation pipeline on a parsed query.
182
183    This is a convenience function that runs all steps in order:
184    0. Set original_query to the caller-provided query string
185    1. Validate reference location is present
186    2. Validate spatial relation is registered
187    3. Enrich with defaults from config
188    4. Validate buffer config consistency
189    5. Check confidence threshold
190
191    Args:
192        geo_query: Parsed query to finalize
193        spatial_config: Spatial relation configuration
194        query: Original natural-language query text, as provided by the caller
195        confidence_threshold: Minimum acceptable confidence
196        strict_mode: If True, raise error on low confidence. If False, warn.
197
198    Returns:
199        Validated and enriched GeoQuery
200
201    Raises:
202        NoReferenceLocationError: If reference_location is None
203        UnknownRelationError: If spatial relation not registered
204        ValidationError: If validation checks fail
205        LowConfidenceError: If strict mode and confidence below threshold
206    """
207    # 0. Set original_query
208    geo_query.original_query = query
209
210    # 1. Validate reference location is present
211    validate_reference_location_present(geo_query)
212
213    # 2. Validate spatial relation
214    validate_spatial_relation(geo_query, spatial_config)
215
216    # 3. Enrich with defaults
217    geo_query = enrich_with_defaults(geo_query, spatial_config)
218
219    # 4. Validate buffer config
220    validate_buffer_config_consistency(geo_query)
221
222    # 5. Check confidence
223    check_confidence_threshold(geo_query, confidence_threshold, strict_mode)
224
225    return geo_query

Set original_query and run the complete validation pipeline on a parsed query.

This is a convenience function that runs all steps in order:

  1. Set original_query to the caller-provided query string
  2. Validate reference location is present
  3. Validate spatial relation is registered
  4. Enrich with defaults from config
  5. Validate buffer config consistency
  6. Check confidence threshold
Arguments:
  • geo_query: Parsed query to finalize
  • spatial_config: Spatial relation configuration
  • query: Original natural-language query text, as provided by the caller
  • confidence_threshold: Minimum acceptable confidence
  • strict_mode: If True, raise error on low confidence. If False, warn.
Returns:

Validated and enriched GeoQuery

Raises:
  • NoReferenceLocationError: If reference_location is None
  • UnknownRelationError: If spatial relation not registered
  • ValidationError: If validation checks fail
  • LowConfidenceError: If strict mode and confidence below threshold
class GeoQuery(pydantic.main.BaseModel):
123class GeoQuery(BaseModel):
124    """
125    Root model representing a parsed geographic query.
126    This is the main output structure returned by the parser.
127    """
128
129    query_type: Literal["simple", "compound", "split", "boolean"] = Field(
130        "simple",
131        description="Type of query. Phase 1 only supports 'simple'. "
132        "Future: 'compound' = multi-step, 'split' = area division, 'boolean' = AND/OR/NOT operations",
133    )
134    spatial_relation: SpatialRelation = Field(description="Spatial relationship to reference location")
135    reference_location: ReferenceLocation | None = Field(
136        None,
137        description="Reference location for the spatial query. "
138        "None when the query contains no named geographic location.",
139    )
140    buffer_config: BufferConfig | None = Field(
141        None,
142        description="Buffer configuration for buffer and directional relations. "
143        "Auto-generated with defaults by enrich_with_defaults() if not provided. "
144        "Required for 'near', 'around', 'north_of', etc. "
145        "Set to None for containment relations ('in').",
146    )
147    confidence_breakdown: ConfidenceScore = Field(description="Confidence scores for different aspects of the parse")
148    original_query: str = Field(
149        default="",
150        description="Original query text exactly as provided by the user",
151    )
152
153    @model_validator(mode="after")
154    def validate_buffer_config_consistency(self) -> "GeoQuery":
155        """Validate buffer_config consistency with relation category."""
156        # Buffer and directional relations must have buffer_config. Skipped when there is no
157        # reference location: the query is rejected with NoReferenceLocationError downstream,
158        # which is the useful error, and the LLM legitimately omits buffer_config in that case.
159        if (
160            self.spatial_relation.category in ("buffer", "directional")
161            and self.buffer_config is None
162            and self.reference_location is not None
163        ):
164            raise ValueError(
165                f"{self.spatial_relation.category} relation '{self.spatial_relation.relation}' requires buffer_config"
166            )
167
168        # Containment and clipping relations should not have buffer_config
169        if self.spatial_relation.category in ("containment", "clipping") and self.buffer_config is not None:
170            raise ValueError(
171                f"{self.spatial_relation.category} relation '{self.spatial_relation.relation}' "
172                f"should not have buffer_config"
173            )
174
175        return self

Root model representing a parsed geographic query. This is the main output structure returned by the parser.

query_type: Literal['simple', 'compound', 'split', 'boolean'] = 'simple'

Type of query. Phase 1 only supports 'simple'. Future: 'compound' = multi-step, 'split' = area division, 'boolean' = AND/OR/NOT operations

spatial_relation: SpatialRelation = PydanticUndefined

Spatial relationship to reference location

reference_location: ReferenceLocation | None = None

Reference location for the spatial query. None when the query contains no named geographic location.

buffer_config: BufferConfig | None = None

Buffer configuration for buffer and directional relations. Auto-generated with defaults by enrich_with_defaults() if not provided. Required for 'near', 'around', 'north_of', etc. Set to None for containment relations ('in').

confidence_breakdown: ConfidenceScore = PydanticUndefined

Confidence scores for different aspects of the parse

original_query: str = ''

Original query text exactly as provided by the user

@model_validator(mode='after')
def validate_buffer_config_consistency(self) -> GeoQuery:
153    @model_validator(mode="after")
154    def validate_buffer_config_consistency(self) -> "GeoQuery":
155        """Validate buffer_config consistency with relation category."""
156        # Buffer and directional relations must have buffer_config. Skipped when there is no
157        # reference location: the query is rejected with NoReferenceLocationError downstream,
158        # which is the useful error, and the LLM legitimately omits buffer_config in that case.
159        if (
160            self.spatial_relation.category in ("buffer", "directional")
161            and self.buffer_config is None
162            and self.reference_location is not None
163        ):
164            raise ValueError(
165                f"{self.spatial_relation.category} relation '{self.spatial_relation.relation}' requires buffer_config"
166            )
167
168        # Containment and clipping relations should not have buffer_config
169        if self.spatial_relation.category in ("containment", "clipping") and self.buffer_config is not None:
170            raise ValueError(
171                f"{self.spatial_relation.category} relation '{self.spatial_relation.relation}' "
172                f"should not have buffer_config"
173            )
174
175        return self

Validate buffer_config consistency with relation category.

class SpatialRelation(pydantic.main.BaseModel):
101class SpatialRelation(BaseModel):
102    """A spatial relationship between target and reference."""
103
104    relation: str = Field(
105        description="Spatial relation keyword. Examples: 'in', 'near', 'around', 'north_of', "
106        "'on_shores_of', 'in_the_heart_of', etc. Use the exact relation name from the available list."
107    )
108    category: RelationCategory = Field(
109        description="Category of spatial relation. "
110        "'containment' = exact boundary matching (in), "
111        "'buffer' = proximity or erosion operations (near, around, on_shores_of, in_the_heart_of, bordering), "
112        "'directional' = sector-based queries (north_of, south_of, east_of, west_of), "
113        "'clipping' = clip reference to a directional half (northern_part_of, southern_part_of, etc.)"
114    )
115    explicit_distance: float | None = Field(
116        None,
117        description="Distance in meters if explicitly mentioned by user. "
118        "For example: 'within 5km' → 5000, 'within 500 meters' → 500. "
119        "Leave null if not explicitly stated.",
120    )

A spatial relationship between target and reference.

relation: str = PydanticUndefined

Spatial relation keyword. Examples: 'in', 'near', 'around', 'north_of', 'on_shores_of', 'in_the_heart_of', etc. Use the exact relation name from the available list.

category: Literal['containment', 'buffer', 'directional', 'clipping'] = PydanticUndefined

Category of spatial relation. 'containment' = exact boundary matching (in), 'buffer' = proximity or erosion operations (near, around, on_shores_of, in_the_heart_of, bordering), 'directional' = sector-based queries (north_of, south_of, east_of, west_of), 'clipping' = clip reference to a directional half (northern_part_of, southern_part_of, etc.)

explicit_distance: float | None = None

Distance in meters if explicitly mentioned by user. For example: 'within 5km' → 5000, 'within 500 meters' → 500. Leave null if not explicitly stated.

class ReferenceLocation(pydantic.main.BaseModel):
41class ReferenceLocation(BaseModel):
42    """A geographic reference location extracted from the query."""
43
44    name: str = Field(description="Location name as mentioned in the query (e.g., 'Lausanne', 'Lake Geneva')")
45    # FIXME: enum ?
46    type: str | None = Field(
47        None,
48        description="Type hint for geographic feature (city, lake, mountain, canton, country, "
49        "train_station, airport, river, road, etc.). This is a HINT for ranking results, "
50        "NOT a strict filter. For ambiguous cases (e.g., 'Bern' could be city or canton, "
51        "'Rhone' could be river or road), provide your best guess or leave null. "
52        "The datasource will return multiple types ranked by relevance.",
53    )
54    type_confidence: ConfidenceLevel | None = Field(
55        None,
56        description="Confidence in the type inference (0-1). High confidence (>0.8) when type is "
57        "explicit in query (e.g., 'Lake Geneva'). Low confidence (<0.6) when ambiguous "
58        "(e.g., 'Bern', 'Rhone'). Use spatial relation as hint: 'along X' → river/road, "
59        "'in X' → city/region, 'on X' → lake/mountain.",
60    )

A geographic reference location extracted from the query.

name: str = PydanticUndefined

Location name as mentioned in the query (e.g., 'Lausanne', 'Lake Geneva')

type: str | None = None

Type hint for geographic feature (city, lake, mountain, canton, country, train_station, airport, river, road, etc.). This is a HINT for ranking results, NOT a strict filter. For ambiguous cases (e.g., 'Bern' could be city or canton, 'Rhone' could be river or road), provide your best guess or leave null. The datasource will return multiple types ranked by relevance.

type_confidence: Optional[Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Confidence score between 0 and 1', metadata=[Ge(ge=0.0), Le(le=1.0)])]] = None

Confidence in the type inference (0-1). High confidence (>0.8) when type is explicit in query (e.g., 'Lake Geneva'). Low confidence (<0.6) when ambiguous (e.g., 'Bern', 'Rhone'). Use spatial relation as hint: 'along X' → river/road, 'in X' → city/region, 'on X' → lake/mountain.

class BufferConfig(pydantic.main.BaseModel):
63class BufferConfig(BaseModel):
64    """Configuration for buffer-based spatial operations."""
65
66    distance_m: float = Field(
67        description="Buffer distance in meters. Positive values expand outward (proximity), "
68        "negative values erode inward (e.g., 'in the heart of'). "
69        "Examples: 5000 = 5km radius, -500 = 500m erosion"
70    )
71    buffer_from: Literal["center", "boundary"] = Field(
72        description="Buffer origin. 'center' = buffer from centroid point (for proximity), "
73        "'boundary' = buffer from polygon boundary (for shores, along roads, erosion)"
74    )
75    ring_only: bool = Field(
76        False,
77        description="If True, exclude the reference feature itself to create a ring/donut shape. "
78        "Used for queries like 'on the shores of Lake X' (exclude the lake water itself). "
79        "Only valid with buffer_from='boundary'.",
80    )
81    side: Literal["left", "right"] | None = Field(
82        None,
83        description="Side of a linear feature for one-sided buffer. "
84        "'left' = left side relative to line direction, 'right' = right side. "
85        "None = both sides (symmetric buffer). Populated from relation config by enrich_with_defaults().",
86    )
87    inferred: bool = Field(
88        True,
89        description="True if this configuration was inferred from relation defaults. "
90        "False if the user explicitly specified distance or buffer parameters.",
91    )
92
93    @model_validator(mode="after")
94    def validate_ring_only(self) -> "BufferConfig":
95        """Validate that ring_only is only used with boundary buffers."""
96        if self.ring_only and self.buffer_from == "center":
97            raise ValueError("ring_only=True requires buffer_from='boundary' (cannot create ring from center point)")
98        return self

Configuration for buffer-based spatial operations.

distance_m: float = PydanticUndefined

Buffer distance in meters. Positive values expand outward (proximity), negative values erode inward (e.g., 'in the heart of'). Examples: 5000 = 5km radius, -500 = 500m erosion

buffer_from: Literal['center', 'boundary'] = PydanticUndefined

Buffer origin. 'center' = buffer from centroid point (for proximity), 'boundary' = buffer from polygon boundary (for shores, along roads, erosion)

ring_only: bool = False

If True, exclude the reference feature itself to create a ring/donut shape. Used for queries like 'on the shores of Lake X' (exclude the lake water itself). Only valid with buffer_from='boundary'.

side: Optional[Literal['left', 'right']] = None

Side of a linear feature for one-sided buffer. 'left' = left side relative to line direction, 'right' = right side. None = both sides (symmetric buffer). Populated from relation config by enrich_with_defaults().

inferred: bool = True

True if this configuration was inferred from relation defaults. False if the user explicitly specified distance or buffer parameters.

@model_validator(mode='after')
def validate_ring_only(self) -> BufferConfig:
93    @model_validator(mode="after")
94    def validate_ring_only(self) -> "BufferConfig":
95        """Validate that ring_only is only used with boundary buffers."""
96        if self.ring_only and self.buffer_from == "center":
97            raise ValueError("ring_only=True requires buffer_from='boundary' (cannot create ring from center point)")
98        return self

Validate that ring_only is only used with boundary buffers.

class ConfidenceScore(pydantic.main.BaseModel):
21class ConfidenceScore(BaseModel):
22    """Confidence scores for different aspects of the parsed query."""
23
24    overall: ConfidenceLevel = Field(
25        description="Overall confidence score for the entire query parse. "
26        "0.9-1.0 = highly confident, 0.7-0.9 = confident, 0.5-0.7 = uncertain, <0.5 = very uncertain",
27    )
28    location_confidence: ConfidenceLevel = Field(
29        description="Confidence in correctly identifying the reference location",
30    )
31    relation_confidence: ConfidenceLevel = Field(
32        description="Confidence in correctly identifying the spatial relation",
33    )
34    reasoning: str | None = Field(
35        None,
36        description="Explanation for confidence scores. Always include reasoning for clarity and debugging. "
37        "For example: 'Ambiguous location name', 'Unclear spatial relationship', 'High confidence in location matching', etc.",
38    )

Confidence scores for different aspects of the parsed query.

overall: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Confidence score between 0 and 1', metadata=[Ge(ge=0.0), Le(le=1.0)])] = PydanticUndefined

Overall confidence score for the entire query parse. 0.9-1.0 = highly confident, 0.7-0.9 = confident, 0.5-0.7 = uncertain, <0.5 = very uncertain

location_confidence: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Confidence score between 0 and 1', metadata=[Ge(ge=0.0), Le(le=1.0)])] = PydanticUndefined

Confidence in correctly identifying the reference location

relation_confidence: Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Confidence score between 0 and 1', metadata=[Ge(ge=0.0), Le(le=1.0)])] = PydanticUndefined

Confidence in correctly identifying the spatial relation

reasoning: str | None = None

Explanation for confidence scores. Always include reasoning for clarity and debugging. For example: 'Ambiguous location name', 'Unclear spatial relationship', 'High confidence in location matching', etc.

ConfidenceLevel = typing.Annotated[float, FieldInfo(annotation=NoneType, required=True, description='Confidence score between 0 and 1', metadata=[Ge(ge=0.0), Le(le=1.0)])]
GeometryFormat = typing.Literal['geojson', 'wkt', 'wkb', 'shapely']
class SpatialRelationConfig:
 44class SpatialRelationConfig:
 45    """
 46    Registry and configuration for spatial relations.
 47
 48    Manages built-in and custom spatial relations with their default parameters.
 49    """
 50
 51    def __init__(self):
 52        """Initialize with built-in spatial relations."""
 53        self.relations: dict[str, RelationConfig] = {}
 54        self._initialize_defaults()
 55
 56    def _initialize_defaults(self):
 57        """Register built-in spatial relations from ARCHITECTURE.md."""
 58
 59        # ===== CONTAINMENT RELATIONS =====
 60        self.register_relation(
 61            RelationConfig(
 62                name="in",
 63                category="containment",
 64                description="Feature is within the reference boundary",
 65            )
 66        )
 67
 68        # ===== BUFFER/PROXIMITY RELATIONS =====
 69        self.register_relation(
 70            RelationConfig(
 71                name="around",
 72                category="buffer",
 73                description="Proximity search around a point with default 1km radius",
 74                default_distance_m=1000,
 75                buffer_from="center",
 76            )
 77        )
 78
 79        self.register_relation(
 80            RelationConfig(
 81                name="near",
 82                category="buffer",
 83                description="Proximity search with default 5km radius",
 84                default_distance_m=5000,
 85                buffer_from="center",
 86                scale_with_area=True,
 87            )
 88        )
 89
 90        self.register_relation(
 91            RelationConfig(
 92                name="on_shores_of",
 93                category="buffer",
 94                description="Ring buffer around lake/water boundary, excluding the water body itself",
 95                default_distance_m=1000,
 96                buffer_from="boundary",
 97                ring_only=True,
 98            )
 99        )
100
101        self.register_relation(
102            RelationConfig(
103                name="along",
104                category="buffer",
105                description="Buffer following a linear feature like a river or road",
106                default_distance_m=500,
107                buffer_from="boundary",
108            )
109        )
110
111        self.register_relation(
112            RelationConfig(
113                name="left_bank",
114                category="buffer",
115                description="Left bank of a linear feature (river, road) relative to its direction/flow",
116                default_distance_m=500,
117                buffer_from="boundary",
118                side="left",
119            )
120        )
121
122        self.register_relation(
123            RelationConfig(
124                name="right_bank",
125                category="buffer",
126                description="Right bank of a linear feature (river, road) relative to its direction/flow",
127                default_distance_m=500,
128                buffer_from="boundary",
129                side="right",
130            )
131        )
132
133        self.register_relation(
134            RelationConfig(
135                name="in_the_heart_of",
136                category="buffer",
137                description="Central area excluding periphery (negative buffer - erosion)",
138                default_distance_m=-500,
139                buffer_from="boundary",
140                scale_with_area=True,
141            )
142        )
143
144        self.register_relation(
145            RelationConfig(
146                name="bordering",
147                category="buffer",
148                description="Thin ring just outside the reference boundary, for land-border adjacency queries (e.g. 'cities bordering Germany')",
149                default_distance_m=2000,
150                buffer_from="boundary",
151                ring_only=True,
152            )
153        )
154
155        # ===== CLIPPING RELATIONS =====
156        # Clip the reference geometry to a directional half-plane using bbox intersection.
157        # These answer "what is in the northern/southern/eastern/western portion of X?"
158        # as opposed to directional relations which answer "what is north/south/etc. of X?".
159        self.register_relation(
160            RelationConfig(
161                name="northern_part_of",
162                category="clipping",
163                description="Northern half of the reference geometry (bbox clip to upper half)",
164                clip_direction="north",
165            )
166        )
167
168        self.register_relation(
169            RelationConfig(
170                name="southern_part_of",
171                category="clipping",
172                description="Southern half of the reference geometry (bbox clip to lower half)",
173                clip_direction="south",
174            )
175        )
176
177        self.register_relation(
178            RelationConfig(
179                name="eastern_part_of",
180                category="clipping",
181                description="Eastern half of the reference geometry (bbox clip to right half)",
182                clip_direction="east",
183            )
184        )
185
186        self.register_relation(
187            RelationConfig(
188                name="western_part_of",
189                category="clipping",
190                description="Western half of the reference geometry (bbox clip to left half)",
191                clip_direction="west",
192            )
193        )
194
195        # ===== DIRECTIONAL RELATIONS =====
196        # All directional relations use consistent defaults:
197        # - Distance: 10km radius (default_distance_m=10000)
198        # - Sector: 90° angular wedge (sector_angle_degrees=90)
199        # - Origin: Centroid of reference location (buffer_from="center" set in enrich_with_defaults)
200        # These defaults are applied automatically by enrich_with_defaults() for any directional query.
201        # Convention: 0° = North, angles increase clockwise (90° = East, 180° = South, 270° = West)
202        self.register_relation(
203            RelationConfig(
204                name="north_of",
205                category="directional",
206                description="Directional sector north of reference",
207                default_distance_m=10000,
208                scale_with_area=True,
209                sector_angle_degrees=90,
210                direction_angle_degrees=0,
211            )
212        )
213
214        self.register_relation(
215            RelationConfig(
216                name="south_of",
217                category="directional",
218                description="Directional sector south of reference",
219                default_distance_m=10000,
220                scale_with_area=True,
221                sector_angle_degrees=90,
222                direction_angle_degrees=180,
223            )
224        )
225
226        self.register_relation(
227            RelationConfig(
228                name="east_of",
229                category="directional",
230                description="Directional sector east of reference",
231                default_distance_m=10000,
232                scale_with_area=True,
233                sector_angle_degrees=90,
234                direction_angle_degrees=90,
235            )
236        )
237
238        self.register_relation(
239            RelationConfig(
240                name="west_of",
241                category="directional",
242                description="Directional sector west of reference",
243                default_distance_m=10000,
244                scale_with_area=True,
245                sector_angle_degrees=90,
246                direction_angle_degrees=270,
247            )
248        )
249
250        # ===== DIAGONAL DIRECTIONAL RELATIONS =====
251        self.register_relation(
252            RelationConfig(
253                name="northeast_of",
254                category="directional",
255                description="Directional sector northeast of reference",
256                default_distance_m=10000,
257                scale_with_area=True,
258                sector_angle_degrees=90,
259                direction_angle_degrees=45,
260            )
261        )
262
263        self.register_relation(
264            RelationConfig(
265                name="southeast_of",
266                category="directional",
267                description="Directional sector southeast of reference",
268                default_distance_m=10000,
269                scale_with_area=True,
270                sector_angle_degrees=90,
271                direction_angle_degrees=135,
272            )
273        )
274
275        self.register_relation(
276            RelationConfig(
277                name="southwest_of",
278                category="directional",
279                description="Directional sector southwest of reference",
280                default_distance_m=10000,
281                scale_with_area=True,
282                sector_angle_degrees=90,
283                direction_angle_degrees=225,
284            )
285        )
286
287        self.register_relation(
288            RelationConfig(
289                name="northwest_of",
290                category="directional",
291                description="Directional sector northwest of reference",
292                default_distance_m=10000,
293                scale_with_area=True,
294                sector_angle_degrees=90,
295                direction_angle_degrees=315,
296            )
297        )
298
299    def register_relation(self, config: RelationConfig) -> None:
300        """Register a new spatial relation."""
301        self.relations[config.name] = config
302
303    def has_relation(self, name: str) -> bool:
304        """Check if a relation is registered."""
305        return name in self.relations
306
307    def get_config(self, name: str) -> RelationConfig:
308        """Get configuration for a relation. Raises UnknownRelationError if not found."""
309        if not self.has_relation(name):
310            raise UnknownRelationError(
311                f"Unknown spatial relation: '{name}'. Available relations: {', '.join(sorted(self.relations.keys()))}",
312                relation_name=name,
313            )
314        return self.relations[name]
315
316    def list_relations(self, category: RelationCategory | None = None) -> list[str]:
317        """List available relation names."""
318        if category is None:
319            return sorted(self.relations.keys())
320        return sorted(r.name for r in self.relations.values() if r.category == category)
321
322    def format_for_prompt(self) -> str:
323        """Format relations for inclusion in LLM prompt."""
324        lines = []
325
326        # Group by category
327        for category in get_args(RelationCategory):
328            category_relations = [r for r in self.relations.values() if r.category == category]
329            if not category_relations:
330                continue
331
332            lines.append(f"\n{category.upper()} RELATIONS:")
333
334            for rel in sorted(category_relations, key=lambda r: r.name):
335                # Build distance info
336                dist_info = ""
337                if rel.default_distance_m is not None:
338                    dist_str = f"{abs(rel.default_distance_m)}m"
339                    if rel.default_distance_m < 0:
340                        dist_info = f" (default: {dist_str} erosion)"
341                    else:
342                        dist_info = f" (default: {dist_str})"
343
344                # Build special flags
345                flags = []
346                if rel.ring_only:
347                    flags.append("ring buffer")
348                if rel.buffer_from:
349                    flags.append(f"from {rel.buffer_from}")
350                if rel.side:
351                    flags.append(f"{rel.side} side only")
352                flag_info = f" [{', '.join(flags)}]" if flags else ""
353
354                # Format line
355                lines.append(f"  • {rel.name}{dist_info}{flag_info}")
356                lines.append(f"    {rel.description}")
357
358        # Add notes
359        lines.append("\nNOTES:")
360        lines.append("  • Negative distances indicate erosion/shrinking (e.g., in_the_heart_of)")
361        lines.append("  • Ring buffers exclude the reference feature itself (e.g., shores of lake, bordering)")
362        lines.append("  • Buffer from 'center' vs 'boundary' determines buffer origin")
363        lines.append("  • Clipping relations return a sub-area of the reference geometry (not a buffer outward)")
364
365        return "\n".join(lines)

Registry and configuration for spatial relations.

Manages built-in and custom spatial relations with their default parameters.

SpatialRelationConfig()
51    def __init__(self):
52        """Initialize with built-in spatial relations."""
53        self.relations: dict[str, RelationConfig] = {}
54        self._initialize_defaults()

Initialize with built-in spatial relations.

relations: dict[str, RelationConfig]
def register_relation(self, config: RelationConfig) -> None:
299    def register_relation(self, config: RelationConfig) -> None:
300        """Register a new spatial relation."""
301        self.relations[config.name] = config

Register a new spatial relation.

def has_relation(self, name: str) -> bool:
303    def has_relation(self, name: str) -> bool:
304        """Check if a relation is registered."""
305        return name in self.relations

Check if a relation is registered.

def get_config(self, name: str) -> RelationConfig:
307    def get_config(self, name: str) -> RelationConfig:
308        """Get configuration for a relation. Raises UnknownRelationError if not found."""
309        if not self.has_relation(name):
310            raise UnknownRelationError(
311                f"Unknown spatial relation: '{name}'. Available relations: {', '.join(sorted(self.relations.keys()))}",
312                relation_name=name,
313            )
314        return self.relations[name]

Get configuration for a relation. Raises UnknownRelationError if not found.

def list_relations( self, category: Optional[Literal['containment', 'buffer', 'directional', 'clipping']] = None) -> list[str]:
316    def list_relations(self, category: RelationCategory | None = None) -> list[str]:
317        """List available relation names."""
318        if category is None:
319            return sorted(self.relations.keys())
320        return sorted(r.name for r in self.relations.values() if r.category == category)

List available relation names.

def format_for_prompt(self) -> str:
322    def format_for_prompt(self) -> str:
323        """Format relations for inclusion in LLM prompt."""
324        lines = []
325
326        # Group by category
327        for category in get_args(RelationCategory):
328            category_relations = [r for r in self.relations.values() if r.category == category]
329            if not category_relations:
330                continue
331
332            lines.append(f"\n{category.upper()} RELATIONS:")
333
334            for rel in sorted(category_relations, key=lambda r: r.name):
335                # Build distance info
336                dist_info = ""
337                if rel.default_distance_m is not None:
338                    dist_str = f"{abs(rel.default_distance_m)}m"
339                    if rel.default_distance_m < 0:
340                        dist_info = f" (default: {dist_str} erosion)"
341                    else:
342                        dist_info = f" (default: {dist_str})"
343
344                # Build special flags
345                flags = []
346                if rel.ring_only:
347                    flags.append("ring buffer")
348                if rel.buffer_from:
349                    flags.append(f"from {rel.buffer_from}")
350                if rel.side:
351                    flags.append(f"{rel.side} side only")
352                flag_info = f" [{', '.join(flags)}]" if flags else ""
353
354                # Format line
355                lines.append(f"  • {rel.name}{dist_info}{flag_info}")
356                lines.append(f"    {rel.description}")
357
358        # Add notes
359        lines.append("\nNOTES:")
360        lines.append("  • Negative distances indicate erosion/shrinking (e.g., in_the_heart_of)")
361        lines.append("  • Ring buffers exclude the reference feature itself (e.g., shores of lake, bordering)")
362        lines.append("  • Buffer from 'center' vs 'boundary' determines buffer origin")
363        lines.append("  • Clipping relations return a sub-area of the reference geometry (not a buffer outward)")
364
365        return "\n".join(lines)

Format relations for inclusion in LLM prompt.

@dataclass
class RelationConfig:
13@dataclass
14class RelationConfig:
15    """
16    Configuration for a single spatial relation.
17
18    Attributes:
19        name: Relation identifier (e.g., "in", "near", "north_of")
20        category: Type of spatial operation
21        description: Human-readable description for LLM prompt
22        default_distance_m: Default buffer distance in meters
23        buffer_from: Buffer origin
24        ring_only: Exclude reference feature to create ring buffer
25        sector_angle_degrees: Angular sector for directional queries
26        direction_angle_degrees: Direction angle in degrees (0=North, 90=East, 180=South, 270=West, clockwise)
27        scale_with_area: When the query states no distance, size it to the reference polygon's area
28            instead of using default_distance_m (see apply_spatial_relation)
29    """
30
31    name: str
32    category: RelationCategory
33    description: str
34    default_distance_m: float | None = None
35    buffer_from: Literal["center", "boundary"] | None = None
36    ring_only: bool = False
37    side: Literal["left", "right"] | None = None
38    sector_angle_degrees: float | None = None
39    direction_angle_degrees: float | None = None
40    clip_direction: Literal["north", "south", "east", "west"] | None = None
41    scale_with_area: bool = False

Configuration for a single spatial relation.

Attributes:
  • name: Relation identifier (e.g., "in", "near", "north_of")
  • category: Type of spatial operation
  • description: Human-readable description for LLM prompt
  • default_distance_m: Default buffer distance in meters
  • buffer_from: Buffer origin
  • ring_only: Exclude reference feature to create ring buffer
  • sector_angle_degrees: Angular sector for directional queries
  • direction_angle_degrees: Direction angle in degrees (0=North, 90=East, 180=South, 270=West, clockwise)
  • scale_with_area: When the query states no distance, size it to the reference polygon's area instead of using default_distance_m (see apply_spatial_relation)
RelationConfig( name: str, category: Literal['containment', 'buffer', 'directional', 'clipping'], description: str, default_distance_m: float | None = None, buffer_from: Optional[Literal['center', 'boundary']] = None, ring_only: bool = False, side: Optional[Literal['left', 'right']] = None, sector_angle_degrees: float | None = None, direction_angle_degrees: float | None = None, clip_direction: Optional[Literal['north', 'south', 'east', 'west']] = None, scale_with_area: bool = False)
name: str
category: Literal['containment', 'buffer', 'directional', 'clipping']
description: str
default_distance_m: float | None = None
buffer_from: Optional[Literal['center', 'boundary']] = None
ring_only: bool = False
side: Optional[Literal['left', 'right']] = None
sector_angle_degrees: float | None = None
direction_angle_degrees: float | None = None
clip_direction: Optional[Literal['north', 'south', 'east', 'west']] = None
scale_with_area: bool = False
class GeoFilterError(builtins.Exception):
 7class GeoFilterError(Exception):
 8    """Base exception for all GeoFilter errors."""
 9
10    pass

Base exception for all GeoFilter errors.

class ParsingError(etter.GeoFilterError):
13class ParsingError(GeoFilterError):
14    """LLM failed to parse query into valid structure."""
15
16    def __init__(self, message: str, raw_response: str = "", original_error: Exception | None = None):
17        """
18        Initialize parsing error.
19
20        Args:
21            message: Error description
22            raw_response: Raw response from LLM
23            original_error: Original exception that caused parsing failure
24        """
25        self.raw_response = raw_response
26        self.original_error = original_error
27        super().__init__(message)

LLM failed to parse query into valid structure.

ParsingError( message: str, raw_response: str = '', original_error: Exception | None = None)
16    def __init__(self, message: str, raw_response: str = "", original_error: Exception | None = None):
17        """
18        Initialize parsing error.
19
20        Args:
21            message: Error description
22            raw_response: Raw response from LLM
23            original_error: Original exception that caused parsing failure
24        """
25        self.raw_response = raw_response
26        self.original_error = original_error
27        super().__init__(message)

Initialize parsing error.

Arguments:
  • message: Error description
  • raw_response: Raw response from LLM
  • original_error: Original exception that caused parsing failure
raw_response
original_error
class LLMInvocationError(etter.ParsingError):
30class LLMInvocationError(ParsingError):
31    """The LLM call itself failed (network, rate limit, provider error) before any output was produced."""

The LLM call itself failed (network, rate limit, provider error) before any output was produced.

class ValidationError(etter.GeoFilterError):
34class ValidationError(GeoFilterError):
35    """Structured output is valid but fails business logic validation."""
36
37    def __init__(self, message: str, field: str | None = None, detail: str | None = None):
38        """
39        Initialize validation error.
40
41        Args:
42            message: Error description
43            field: Field name that failed validation
44            detail: Additional detail about the validation failure
45        """
46        self.field = field
47        self.detail = detail
48        super().__init__(message)

Structured output is valid but fails business logic validation.

ValidationError(message: str, field: str | None = None, detail: str | None = None)
37    def __init__(self, message: str, field: str | None = None, detail: str | None = None):
38        """
39        Initialize validation error.
40
41        Args:
42            message: Error description
43            field: Field name that failed validation
44            detail: Additional detail about the validation failure
45        """
46        self.field = field
47        self.detail = detail
48        super().__init__(message)

Initialize validation error.

Arguments:
  • message: Error description
  • field: Field name that failed validation
  • detail: Additional detail about the validation failure
field
detail
class NoReferenceLocationError(etter.ValidationError):
51class NoReferenceLocationError(ValidationError):
52    """Query contains no named geographic reference location."""
53
54    def __init__(self, message: str):
55        super().__init__(message, field="reference_location")

Query contains no named geographic reference location.

NoReferenceLocationError(message: str)
54    def __init__(self, message: str):
55        super().__init__(message, field="reference_location")

Initialize validation error.

Arguments:
  • message: Error description
  • field: Field name that failed validation
  • detail: Additional detail about the validation failure
class UnknownRelationError(etter.ValidationError):
58class UnknownRelationError(ValidationError):
59    """Spatial relation is not registered in configuration."""
60
61    def __init__(self, message: str, relation_name: str):
62        """
63        Initialize unknown relation error.
64
65        Args:
66            message: Error description
67            relation_name: The unknown relation name
68        """
69        self.relation_name = relation_name
70        super().__init__(message, field="spatial_relation")

Spatial relation is not registered in configuration.

UnknownRelationError(message: str, relation_name: str)
61    def __init__(self, message: str, relation_name: str):
62        """
63        Initialize unknown relation error.
64
65        Args:
66            message: Error description
67            relation_name: The unknown relation name
68        """
69        self.relation_name = relation_name
70        super().__init__(message, field="spatial_relation")

Initialize unknown relation error.

Arguments:
  • message: Error description
  • relation_name: The unknown relation name
relation_name
class LowConfidenceError(etter.GeoFilterError):
73class LowConfidenceError(GeoFilterError):
74    """Query confidence is below threshold (strict mode)."""
75
76    def __init__(self, message: str, confidence: float, reasoning: str | None = None):
77        """
78        Initialize low confidence error.
79
80        Args:
81            message: Error description
82            confidence: Confidence score (0-1)
83            reasoning: Optional explanation for low confidence
84        """
85        self.confidence = confidence
86        self.reasoning = reasoning
87        super().__init__(message)

Query confidence is below threshold (strict mode).

LowConfidenceError(message: str, confidence: float, reasoning: str | None = None)
76    def __init__(self, message: str, confidence: float, reasoning: str | None = None):
77        """
78        Initialize low confidence error.
79
80        Args:
81            message: Error description
82            confidence: Confidence score (0-1)
83            reasoning: Optional explanation for low confidence
84        """
85        self.confidence = confidence
86        self.reasoning = reasoning
87        super().__init__(message)

Initialize low confidence error.

Arguments:
  • message: Error description
  • confidence: Confidence score (0-1)
  • reasoning: Optional explanation for low confidence
confidence
reasoning
class LowConfidenceWarning(builtins.UserWarning):
 90class LowConfidenceWarning(UserWarning):
 91    """Query confidence is below threshold (permissive mode)."""
 92
 93    def __init__(self, confidence: float, message: str = ""):
 94        """
 95        Initialize low confidence warning.
 96
 97        Args:
 98            confidence: Confidence score (0-1)
 99            message: Warning message
100        """
101        self.confidence = confidence
102        super().__init__(message)

Query confidence is below threshold (permissive mode).

LowConfidenceWarning(confidence: float, message: str = '')
 93    def __init__(self, confidence: float, message: str = ""):
 94        """
 95        Initialize low confidence warning.
 96
 97        Args:
 98            confidence: Confidence score (0-1)
 99            message: Warning message
100        """
101        self.confidence = confidence
102        super().__init__(message)

Initialize low confidence warning.

Arguments:
  • confidence: Confidence score (0-1)
  • message: Warning message
confidence
class GeoDataSource(typing.Protocol):
14class GeoDataSource(Protocol):
15    """
16    Protocol for geographic data sources.
17
18    Implementations resolve location names to geographic features.
19    Features are returned as standard GeoJSON Feature objects (dicts) in WGS84 (EPSG:4326).
20
21    Example of returned feature:
22        {
23            "type": "Feature",
24            "id": "uuid-123",
25            "geometry": {"type": "Point", "coordinates": [8.5, 47.3]},
26            "bbox": [8.4, 47.3, 8.6, 47.4],
27            "properties": {
28                "name": "Zürich",
29                "type": "city",
30                "confidence": 1.0,
31                ...
32            }
33        }
34    """
35
36    def search(
37        self,
38        name: str,
39        type: str | None = None,
40        max_results: int = 10,
41    ) -> list[Feature]:
42        """
43        Search for geographic features by name.
44
45        Args:
46            name: Location name to search for (e.g., "Lake Geneva", "Bern").
47            type: Optional type filter. Accepts a concrete type or a category
48                  (e.g. "lake", "city", "water"); a category matches all concrete
49                  types within it. When provided, only features of matching types
50                  are returned.
51            max_results: Maximum number of results to return.
52
53        Returns:
54            List of matching GeoJSON Feature dicts, ranked by relevance.
55            Returns empty list if no matches found.
56        """
57        ...
58
59    def get_by_id(self, feature_id: str) -> Feature | None:
60        """
61        Get a specific feature by its unique identifier.
62
63        Args:
64            feature_id: Unique identifier from the data source.
65
66        Returns:
67            The matching GeoJSON Feature dict, or None if not found.
68        """
69        ...
70
71    def get_available_types(self) -> list[str]:
72        """
73        Get list of concrete geographic types this datasource can return.
74
75        Returns a list of concrete type values (e.g., "lake", "city", "restaurant")
76        that this datasource uses in the "type" property of returned features.
77        These types can be matched against the location type hierarchy for fuzzy matching.
78
79        The returned types should be a subset of or mapped to the standard location
80        type hierarchy defined in location_types.TYPE_HIERARCHY.
81
82        Returns:
83            List of concrete type strings (e.g., ["lake", "river", "city", "mountain"]).
84            Empty list if this datasource does not provide type information.
85
86        Example:
87            >>> source = SwissNames3DSource("data/")
88            >>> types = source.get_available_types()
89            >>> print(types)
90            ['lake', 'river', 'city', 'mountain', 'peak', 'hill', ...]
91        """
92        ...

Protocol for geographic data sources.

Implementations resolve location names to geographic features. Features are returned as standard GeoJSON Feature objects (dicts) in WGS84 (EPSG:4326).

Example of returned feature:

{ "type": "Feature", "id": "uuid-123", "geometry": {"type": "Point", "coordinates": [8.5, 47.3]}, "bbox": [8.4, 47.3, 8.6, 47.4], "properties": { "name": "Zürich", "type": "city", "confidence": 1.0, ... } }

GeoDataSource(*args, **kwargs)
1968def _no_init_or_replace_init(self, *args, **kwargs):
1969    cls = type(self)
1970
1971    if cls._is_protocol:
1972        raise TypeError('Protocols cannot be instantiated')
1973
1974    # Already using a custom `__init__`. No need to calculate correct
1975    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1976    if cls.__init__ is not _no_init_or_replace_init:
1977        return
1978
1979    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1980    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1981    # searches for a proper new `__init__` in the MRO. The new `__init__`
1982    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1983    # instantiation of the protocol subclass will thus use the new
1984    # `__init__` and no longer call `_no_init_or_replace_init`.
1985    for base in cls.__mro__:
1986        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1987        if init is not _no_init_or_replace_init:
1988            cls.__init__ = init
1989            break
1990    else:
1991        # should not happen
1992        cls.__init__ = object.__init__
1993
1994    cls.__init__(self, *args, **kwargs)
def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
36    def search(
37        self,
38        name: str,
39        type: str | None = None,
40        max_results: int = 10,
41    ) -> list[Feature]:
42        """
43        Search for geographic features by name.
44
45        Args:
46            name: Location name to search for (e.g., "Lake Geneva", "Bern").
47            type: Optional type filter. Accepts a concrete type or a category
48                  (e.g. "lake", "city", "water"); a category matches all concrete
49                  types within it. When provided, only features of matching types
50                  are returned.
51            max_results: Maximum number of results to return.
52
53        Returns:
54            List of matching GeoJSON Feature dicts, ranked by relevance.
55            Returns empty list if no matches found.
56        """
57        ...

Search for geographic features by name.

Arguments:
  • name: Location name to search for (e.g., "Lake Geneva", "Bern").
  • type: Optional type filter. Accepts a concrete type or a category (e.g. "lake", "city", "water"); a category matches all concrete types within it. When provided, only features of matching types are returned.
  • max_results: Maximum number of results to return.
Returns:

List of matching GeoJSON Feature dicts, ranked by relevance. Returns empty list if no matches found.

def get_by_id(self, feature_id: str) -> geojson.feature.Feature | None:
59    def get_by_id(self, feature_id: str) -> Feature | None:
60        """
61        Get a specific feature by its unique identifier.
62
63        Args:
64            feature_id: Unique identifier from the data source.
65
66        Returns:
67            The matching GeoJSON Feature dict, or None if not found.
68        """
69        ...

Get a specific feature by its unique identifier.

Arguments:
  • feature_id: Unique identifier from the data source.
Returns:

The matching GeoJSON Feature dict, or None if not found.

def get_available_types(self) -> list[str]:
71    def get_available_types(self) -> list[str]:
72        """
73        Get list of concrete geographic types this datasource can return.
74
75        Returns a list of concrete type values (e.g., "lake", "city", "restaurant")
76        that this datasource uses in the "type" property of returned features.
77        These types can be matched against the location type hierarchy for fuzzy matching.
78
79        The returned types should be a subset of or mapped to the standard location
80        type hierarchy defined in location_types.TYPE_HIERARCHY.
81
82        Returns:
83            List of concrete type strings (e.g., ["lake", "river", "city", "mountain"]).
84            Empty list if this datasource does not provide type information.
85
86        Example:
87            >>> source = SwissNames3DSource("data/")
88            >>> types = source.get_available_types()
89            >>> print(types)
90            ['lake', 'river', 'city', 'mountain', 'peak', 'hill', ...]
91        """
92        ...

Get list of concrete geographic types this datasource can return.

Returns a list of concrete type values (e.g., "lake", "city", "restaurant") that this datasource uses in the "type" property of returned features. These types can be matched against the location type hierarchy for fuzzy matching.

The returned types should be a subset of or mapped to the standard location type hierarchy defined in location_types.TYPE_HIERARCHY.

Returns:

List of concrete type strings (e.g., ["lake", "river", "city", "mountain"]). Empty list if this datasource does not provide type information.

Example:
>>> source = SwissNames3DSource("data/")
>>> types = source.get_available_types()
>>> print(types)
['lake', 'river', 'city', 'mountain', 'peak', 'hill', ...]
class SwissNames3DSource(etter.datasources.geo_dataframe_source.GeoDataFrameSource):
147class SwissNames3DSource(GeoDataFrameSource):
148    """
149    Geographic data source backed by swisstopo's swissNAMES3D dataset.
150
151    Loads geographic names from a Shapefile, GeoPackage, or ESRI File Geodatabase
152    and provides search by name with optional type filtering.
153
154    If data_path is a directory, automatically loads and concatenates all SwissNames3D
155    shapefiles (swissNAMES3D_PKT, swissNAMES3D_LIN, swissNAMES3D_PLY) found within.
156
157    All geometries are returned as GeoJSON in WGS84 (EPSG:4326).
158
159    Args:
160        data_path: Path to SwissNames3D data file or directory containing SwissNames3D shapefiles.
161        layer: Layer name within the data source (for multi-layer formats like GDB).
162
163    Example:
164        >>> source = SwissNames3DSource("data/")  # Load all 3 geometry types
165        >>> results = source.search("Lac Léman", type="lake")
166        >>> print(results[0].geometry)  # GeoJSON in WGS84
167    """
168
169    def __init__(self, data_path: str | Path, layer: str | None = None) -> None:
170        _require_files_extra()
171        self._data_path = Path(data_path)
172        self._layer = layer
173        self._gdf: gpd.GeoDataFrame | None = None
174        self._name_index: dict[str, list[int]] = {}
175        self._token_index: dict[str, set[str]] = {}
176        self._name_col: str = ""
177        self._type_col: str | None = None
178        self._id_col: str | None = None
179        self._extra_cols: list[str] = []
180
181    def _load_data(self) -> None:
182        """Load SwissNames3D data and build the name index."""
183        import geopandas as gpd
184
185        if self._data_path.is_dir():
186            self._load_from_directory()
187        else:
188            kwargs: dict[str, Any] = {}
189            if self._layer is not None:
190                kwargs["layer"] = self._layer
191            self._gdf = gpd.read_file(str(self._data_path), **kwargs)
192
193        assert self._gdf is not None
194
195        # Drop Z coordinates once — vectorized; the source has LN02 height and
196        # single_sided buffers reject 3D geometries
197        self._gdf.geometry = force_2d(self._gdf.geometry.values)
198
199        # Reproject to WGS84 once — avoids per-query coordinate transform
200        self._gdf = self._gdf.to_crs("EPSG:4326")
201
202        # Cache column names once — reused on every _row_to_feature() call
203        self._name_col = self._detect_name_column()
204        self._type_col = self._detect_type_column()
205        self._id_col = self._detect_id_column()
206        skip = {self._name_col, "geometry"}
207        if self._type_col:
208            skip.add(self._type_col)
209        if self._id_col:
210            skip.add(self._id_col)
211        self._extra_cols = [c for c in self._gdf.columns if c not in skip]
212
213        self._build_name_index()
214
215    def _load_from_directory(self) -> None:
216        """Load and concatenate all SwissNames3D shapefiles from a directory."""
217        import geopandas as gpd
218        import pandas as pd
219
220        # Look for the 3 standard SwissNames3D shapefiles
221        shapefile_names = ["swissNAMES3D_PKT", "swissNAMES3D_LIN", "swissNAMES3D_PLY"]
222        gdfs: list[gpd.GeoDataFrame] = []
223
224        for name in shapefile_names:
225            shp_path = self._data_path / f"{name}.shp"
226            if shp_path.exists():
227                gdf = gpd.read_file(str(shp_path))
228                gdfs.append(gdf)
229
230        if not gdfs:
231            raise ValueError(
232                f"No SwissNames3D shapefiles found in {self._data_path}. Expected: {', '.join(shapefile_names)}"
233            )
234
235        # Find common columns across all loaded GeoDataFrames
236        common_cols = set(gdfs[0].columns)
237        for gdf in gdfs[1:]:
238            common_cols &= set(gdf.columns)
239
240        # Keep only common columns and concatenate
241        gdfs_filtered = [gdf[sorted(common_cols)] for gdf in gdfs]
242        self._gdf = gpd.GeoDataFrame(pd.concat(gdfs_filtered, ignore_index=True), crs=gdfs[0].crs, geometry="geometry")
243
244    def _build_name_index(self) -> None:
245        """Build normalized name → row indices and token → candidate names indexes."""
246        assert self._gdf is not None
247        self._name_index = {}
248        self._token_index = {}
249
250        for idx, name in enumerate(self._gdf[self._name_col]):
251            if not isinstance(name, str) or not name.strip():
252                continue
253            normalized = normalize_name(name)
254            if normalized not in self._name_index:
255                self._name_index[normalized] = []
256            self._name_index[normalized].append(idx)
257            for token in normalized.split():
258                if token not in self._token_index:
259                    self._token_index[token] = set()
260                self._token_index[token].add(normalized)
261
262    def _detect_name_column(self) -> str:
263        """Detect the name column in the data."""
264        assert self._gdf is not None
265        for col in self._gdf.columns:
266            if col.upper() in ("NAME", "BEZEICHNUNG"):
267                return col
268        raise ValueError(f"Cannot find name column in data. Available columns: {list(self._gdf.columns)}")
269
270    def _detect_type_column(self) -> str | None:
271        """Detect the feature type column in the data."""
272        assert self._gdf is not None
273        for col in self._gdf.columns:
274            if col.upper() == "OBJEKTART":
275                return col
276        return None
277
278    def _detect_id_column(self) -> str | None:
279        """Detect the unique ID column in the data."""
280        assert self._gdf is not None
281        for candidate in ("UUID", "FID", "OBJECTID", "ID"):
282            for col in self._gdf.columns:
283                if col.upper() == candidate:
284                    return col
285        return None
286
287    def _row_type(self, idx: int) -> str:
288        """Return a row's normalized type without building its full Feature (geometry, etc.)."""
289        assert self._gdf is not None
290        row = self._gdf.iloc[idx]
291        raw_type = str(row[self._type_col]) if self._type_col and row.get(self._type_col) else "unknown"
292        return _objektart_to_type(raw_type)
293
294    def _row_to_feature(self, idx: int) -> Feature:
295        """Convert a GeoDataFrame row to a GeoJSON Feature dict with WGS84 geometry."""
296        assert self._gdf is not None
297        row = self._gdf.iloc[idx]
298
299        name = str(row[self._name_col])
300        normalized_type = self._row_type(idx)
301
302        feature_id = str(row[self._id_col]) if self._id_col and row.get(self._id_col) else str(idx)
303
304        # Geometry is already in WGS84 (2D) — pre-converted at load time
305        geom = row.geometry
306        if geom is None or geom.is_empty:
307            geometry = {"type": "Point", "coordinates": [0, 0]}
308            bbox = None
309        else:
310            geometry = mapping(geom)
311            bounds = geom.bounds
312            bbox = (bounds[0], bounds[1], bounds[2], bounds[3])
313
314        properties: dict[str, Any] = {
315            "name": name,
316            "type": normalized_type,
317            "confidence": 1.0,
318        }
319        for col in self._extra_cols:
320            val = to_serializable(row.get(col))
321            if val is not None:
322                properties[col] = val
323
324        return Feature(geometry=geometry, properties=properties, id=feature_id, bbox=bbox)
325
326    def search(
327        self,
328        name: str,
329        type: str | None = None,
330        max_results: int = 10,
331    ) -> list[Feature]:
332        """
333        Search for geographic features by name.
334
335        Uses case-insensitive, accent-normalized matching with fuzzy fallback.
336        First tries exact matching, then falls back to fuzzy matching if no exact
337        matches found.
338
339        Args:
340            name: Location name to search for.
341            type: Optional type hint to filter results. If provided, only features
342                  of this type are returned.
343            max_results: Maximum number of results to return.
344
345        Returns:
346            List of matching GeoJSON Feature dicts. If type is provided, only
347            features of that type are returned. Empty list if no matches found.
348        """
349        self._ensure_loaded()
350
351        normalized = normalize_name(name)
352        indices = self._name_index.get(normalized, [])
353
354        # If no exact match, try fuzzy matching
355        if not indices:
356            indices = self._fuzzy_search(normalized)
357
358        # Filter by type if type hint provided, before building the (geometry-heavy) Feature
359        # for each row — so rows dropped by the filter skip that work entirely.
360        # Expand via the type hierarchy so that category hints (e.g. "water") match
361        # all concrete types within that category ("lake", "river", "pond", ...).
362        if type is not None:
363            matching_types = get_matching_types(type)
364            if matching_types:
365                indices = [idx for idx in indices if self._row_type(idx) in matching_types]
366            else:
367                # Unknown type hint, fall back to exact string match
368                indices = [idx for idx in indices if self._row_type(idx) == type.lower()]
369
370        features = [self._row_to_feature(idx) for idx in indices]
371
372        features = merge_segments(features)
373        return features[:max_results]
374
375    def get_available_types(self) -> list[str]:
376        """
377        Get list of concrete geographic types this datasource can return.
378
379        Returns all normalized types from the OBJEKTART_TYPE_MAP keys,
380        representing all possible types that SwissNames3D data can be classified as.
381
382        Returns:
383            Sorted list of type strings (e.g., ["lake", "city", "river", ...])
384        """
385        return sorted(OBJEKTART_TYPE_MAP.keys())

Geographic data source backed by swisstopo's swissNAMES3D dataset.

Loads geographic names from a Shapefile, GeoPackage, or ESRI File Geodatabase and provides search by name with optional type filtering.

If data_path is a directory, automatically loads and concatenates all SwissNames3D shapefiles (swissNAMES3D_PKT, swissNAMES3D_LIN, swissNAMES3D_PLY) found within.

All geometries are returned as GeoJSON in WGS84 (EPSG:4326).

Arguments:
  • data_path: Path to SwissNames3D data file or directory containing SwissNames3D shapefiles.
  • layer: Layer name within the data source (for multi-layer formats like GDB).
Example:
>>> source = SwissNames3DSource("data/")  # Load all 3 geometry types
>>> results = source.search("Lac Léman", type="lake")
>>> print(results[0].geometry)  # GeoJSON in WGS84
SwissNames3DSource(data_path: str | pathlib._local.Path, layer: str | None = None)
169    def __init__(self, data_path: str | Path, layer: str | None = None) -> None:
170        _require_files_extra()
171        self._data_path = Path(data_path)
172        self._layer = layer
173        self._gdf: gpd.GeoDataFrame | None = None
174        self._name_index: dict[str, list[int]] = {}
175        self._token_index: dict[str, set[str]] = {}
176        self._name_col: str = ""
177        self._type_col: str | None = None
178        self._id_col: str | None = None
179        self._extra_cols: list[str] = []
def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
326    def search(
327        self,
328        name: str,
329        type: str | None = None,
330        max_results: int = 10,
331    ) -> list[Feature]:
332        """
333        Search for geographic features by name.
334
335        Uses case-insensitive, accent-normalized matching with fuzzy fallback.
336        First tries exact matching, then falls back to fuzzy matching if no exact
337        matches found.
338
339        Args:
340            name: Location name to search for.
341            type: Optional type hint to filter results. If provided, only features
342                  of this type are returned.
343            max_results: Maximum number of results to return.
344
345        Returns:
346            List of matching GeoJSON Feature dicts. If type is provided, only
347            features of that type are returned. Empty list if no matches found.
348        """
349        self._ensure_loaded()
350
351        normalized = normalize_name(name)
352        indices = self._name_index.get(normalized, [])
353
354        # If no exact match, try fuzzy matching
355        if not indices:
356            indices = self._fuzzy_search(normalized)
357
358        # Filter by type if type hint provided, before building the (geometry-heavy) Feature
359        # for each row — so rows dropped by the filter skip that work entirely.
360        # Expand via the type hierarchy so that category hints (e.g. "water") match
361        # all concrete types within that category ("lake", "river", "pond", ...).
362        if type is not None:
363            matching_types = get_matching_types(type)
364            if matching_types:
365                indices = [idx for idx in indices if self._row_type(idx) in matching_types]
366            else:
367                # Unknown type hint, fall back to exact string match
368                indices = [idx for idx in indices if self._row_type(idx) == type.lower()]
369
370        features = [self._row_to_feature(idx) for idx in indices]
371
372        features = merge_segments(features)
373        return features[:max_results]

Search for geographic features by name.

Uses case-insensitive, accent-normalized matching with fuzzy fallback. First tries exact matching, then falls back to fuzzy matching if no exact matches found.

Arguments:
  • name: Location name to search for.
  • type: Optional type hint to filter results. If provided, only features of this type are returned.
  • max_results: Maximum number of results to return.
Returns:

List of matching GeoJSON Feature dicts. If type is provided, only features of that type are returned. Empty list if no matches found.

def get_available_types(self) -> list[str]:
375    def get_available_types(self) -> list[str]:
376        """
377        Get list of concrete geographic types this datasource can return.
378
379        Returns all normalized types from the OBJEKTART_TYPE_MAP keys,
380        representing all possible types that SwissNames3D data can be classified as.
381
382        Returns:
383            Sorted list of type strings (e.g., ["lake", "city", "river", ...])
384        """
385        return sorted(OBJEKTART_TYPE_MAP.keys())

Get list of concrete geographic types this datasource can return.

Returns all normalized types from the OBJEKTART_TYPE_MAP keys, representing all possible types that SwissNames3D data can be classified as.

Returns:

Sorted list of type strings (e.g., ["lake", "city", "river", ...])

class SwissBoundaries3DSource(etter.datasources.geo_dataframe_source.GeoDataFrameSource):
 56class SwissBoundaries3DSource(GeoDataFrameSource):
 57    """
 58    Geographic data source backed by swisstopo's swissBOUNDARIES3D dataset.
 59
 60    Loads geographic names from a Shapefile, GeoPackage, or ESRI File Geodatabase
 61    and provides search by name with optional type filtering.
 62
 63    If data_path is a directory, automatically loads and concatenates all swissBoundaries3D
 64    shapefiles (swissBOUNDARIES3D_1_5_TLM_BEZIRKSGEBIET, swissBOUNDARIES3D_1_5_TLM_HOHEITSGEBIET, swissBOUNDARIES3D_1_5_TLM_KANTONSGEBIET) found within.
 65
 66    IMPORTANT:
 67        The swissBOUNDARIES3D_1_5_TLM_LANDESGEBIET is NOT read because it contains enclaves of Germany which are not relevant for Swiss geographic names.
 68        The swissBOUNDARIES3D_1_5_TLM_HOHEITSGRENZE is NOT read because it contains lines already in swissBOUNDARIES3D_1_5_TLM_HOHEITSGEBIET.
 69    All geometries are returned as GeoJSON in WGS84 (EPSG:4326).
 70
 71    Args:
 72        data_path: Path to swissBoundaries3D data file or directory containing swissBoundaries3D shapefiles.
 73        layer: Layer name within the data source (for multi-layer formats like GDB).
 74
 75    Example:
 76        >>> source = SwissBoundaries3DSource("data/")  # Load all 3 geometry types
 77        >>> results = source.search("Bern", type="canton")
 78        >>> print(results[0].geometry)  # GeoJSON in WGS84
 79    """
 80
 81    def __init__(self, data_path: str | Path, layer: str | None = None) -> None:
 82        _require_files_extra()
 83        self._data_path = Path(data_path)
 84        self._layer = layer
 85        self._gdf: gpd.GeoDataFrame | None = None
 86        self._name_index: dict[str, list[int]] = {}
 87        self._token_index: dict[str, set[str]] = {}
 88        self._name_col: str = ""
 89        self._type_col: str | None = None
 90        self._id_col: str | None = None
 91        self._extra_cols: list[str] = []
 92
 93    def _load_data(self) -> None:
 94        """Load swissBoundaries3D data and build the name index."""
 95        import geopandas as gpd
 96
 97        if self._data_path.is_dir():
 98            self._load_from_directory()
 99        else:
100            kwargs: dict[str, Any] = {}
101            if self._layer is not None:
102                kwargs["layer"] = self._layer
103            self._gdf = gpd.read_file(str(self._data_path), **kwargs)
104
105        assert self._gdf is not None
106
107        # Drop Z coordinates once — vectorized; the source has LN02 height and
108        # single_sided buffers reject 3D geometries
109        self._gdf.geometry = force_2d(self._gdf.geometry.values)
110
111        # Reproject to WGS84 once — avoids per-query coordinate transform
112        self._gdf = self._gdf.to_crs("EPSG:4326")
113
114        # Cache column names once — reused on every _row_to_feature() call
115        self._name_col = self._detect_name_column()
116        self._type_col = self._detect_type_column()
117        self._id_col = self._detect_id_column()
118        skip = {self._name_col, "geometry"}
119        if self._type_col:
120            skip.add(self._type_col)
121        if self._id_col:
122            skip.add(self._id_col)
123        self._extra_cols = [c for c in self._gdf.columns if c not in skip]
124
125        self._build_name_index()
126
127    def _load_from_directory(self) -> None:
128        """Load and concatenate all swissBoundaries3D shapefiles from a directory."""
129        import geopandas as gpd
130        import pandas as pd
131
132        # Look for the 3 standard swissBoundaries3D shapefiles
133        shapefile_names = [
134            "swissBOUNDARIES3D_1_5_TLM_BEZIRKSGEBIET",
135            "swissBOUNDARIES3D_1_5_TLM_HOHEITSGEBIET",
136            "swissBOUNDARIES3D_1_5_TLM_KANTONSGEBIET",
137        ]
138        gdfs: list[gpd.GeoDataFrame] = []
139
140        for name in shapefile_names:
141            shp_path = self._data_path / f"{name}.shp"
142            if shp_path.exists():
143                gdf = gpd.read_file(str(shp_path))
144                gdfs.append(gdf)
145
146        if not gdfs:
147            raise ValueError(
148                f"No swissBoundaries3D shapefiles found in {self._data_path}. Expected: {', '.join(shapefile_names)}"
149            )
150
151        # Find common columns across all loaded GeoDataFrames
152        common_cols = set(gdfs[0].columns)
153        for gdf in gdfs[1:]:
154            common_cols &= set(gdf.columns)
155
156        # Keep only common columns and concatenate
157        gdfs_filtered = [gdf[sorted(common_cols)] for gdf in gdfs]
158        self._gdf = gpd.GeoDataFrame(pd.concat(gdfs_filtered, ignore_index=True), crs=gdfs[0].crs, geometry="geometry")
159
160    def _build_name_index(self) -> None:
161        """Build normalized name → row indices and token → candidate names indexes."""
162        assert self._gdf is not None
163        self._name_index = {}
164        self._token_index = {}
165
166        for idx, name in enumerate(self._gdf[self._name_col]):
167            if not isinstance(name, str) or not name.strip():
168                continue
169            normalized = normalize_name(name)
170            if normalized not in self._name_index:
171                self._name_index[normalized] = []
172            self._name_index[normalized].append(idx)
173            for token in normalized.split():
174                if token not in self._token_index:
175                    self._token_index[token] = set()
176                self._token_index[token].add(normalized)
177
178    def _detect_name_column(self) -> str:
179        """Detect the name column in the data."""
180        assert self._gdf is not None
181        for col in self._gdf.columns:
182            if col.upper() in ("NAME", "BEZEICHNUNG"):
183                return col
184        raise ValueError(f"Cannot find name column in data. Available columns: {list(self._gdf.columns)}")
185
186    def _detect_type_column(self) -> str | None:
187        """Detect the feature type column in the data."""
188        assert self._gdf is not None
189        for col in self._gdf.columns:
190            if col.upper() == "OBJEKTART":
191                return col
192        return None
193
194    def _detect_id_column(self) -> str | None:
195        """Detect the unique ID column in the data."""
196        assert self._gdf is not None
197        for candidate in ("UUID", "FID", "OBJECTID", "ID"):
198            for col in self._gdf.columns:
199                if col.upper() == candidate:
200                    return col
201        return None
202
203    def _row_to_feature(self, idx: int) -> Feature:
204        """Convert a GeoDataFrame row to a GeoJSON Feature dict with WGS84 geometry."""
205        assert self._gdf is not None
206        row = self._gdf.iloc[idx]
207
208        name = str(row[self._name_col])
209
210        raw_type = str(row[self._type_col]) if self._type_col and row.get(self._type_col) else "unknown"
211        normalized_type = _objektart_to_type(raw_type)
212
213        feature_id = str(row[self._id_col]) if self._id_col and row.get(self._id_col) else str(idx)
214
215        # Geometry is already in WGS84 (2D) — pre-converted at load time
216        geom = row.geometry
217        if geom is None or geom.is_empty:
218            geometry = {"type": "Point", "coordinates": [0, 0]}
219            bbox = None
220        else:
221            geometry = mapping(geom)
222            bounds = geom.bounds
223            bbox = (bounds[0], bounds[1], bounds[2], bounds[3])
224
225        properties: dict[str, Any] = {
226            "name": name,
227            "type": normalized_type,
228            "confidence": 1.0,
229        }
230        for col in self._extra_cols:
231            val = to_serializable(row.get(col))
232            if val is not None:
233                properties[col] = val
234
235        return Feature(geometry=geometry, properties=properties, id=feature_id, bbox=bbox)
236
237    def search(
238        self,
239        name: str,
240        type: str | None = None,
241        max_results: int = 10,
242    ) -> list[Feature]:
243        """
244        Search for geographic features by name.
245
246        Uses case-insensitive, accent-normalized matching with fuzzy fallback.
247        First tries exact matching, then falls back to fuzzy matching if no exact
248        matches found.
249
250        Args:
251            name: Location name to search for.
252            type: Optional type hint to filter results. If provided, only features
253                  of this type are returned.
254            max_results: Maximum number of results to return.
255
256        Returns:
257            List of matching GeoJSON Feature dicts. If type is provided, only
258            features of that type are returned. Empty list if no matches found.
259        """
260        self._ensure_loaded()
261
262        normalized = normalize_name(name)
263        indices = self._name_index.get(normalized, [])
264
265        # If no exact match, try fuzzy matching
266        if not indices:
267            indices = self._fuzzy_search(normalized)
268
269        features = [self._row_to_feature(idx) for idx in indices]
270
271        # Filter by type if type hint provided.
272        # Expand via the type hierarchy so that category hints (e.g. "water") match
273        # all concrete types within that category ("lake", "river", "pond", ...).
274        if type is not None:
275            matching_types = get_matching_types(type)
276            if matching_types:
277                features = [f for f in features if f["properties"].get("type") in matching_types]
278            else:
279                # Unknown type hint, fall back to exact string match
280                features = [f for f in features if f["properties"].get("type") == type.lower()]
281
282        return features[:max_results]
283
284    def get_available_types(self) -> list[str]:
285        """
286        Get list of concrete geographic types this datasource can return.
287
288        Returns all normalized types from the OBJEKTART_TYPE_MAP keys,
289        representing all possible types that swissBoundaries3D data can be classified as.
290
291        Returns:
292            Sorted list of type strings (e.g., ["canton", "municipality", "district", ...])
293        """
294        return sorted(OBJEKTART_TYPE_MAP.keys())

Geographic data source backed by swisstopo's swissBOUNDARIES3D dataset.

Loads geographic names from a Shapefile, GeoPackage, or ESRI File Geodatabase and provides search by name with optional type filtering.

If data_path is a directory, automatically loads and concatenates all swissBoundaries3D shapefiles (swissBOUNDARIES3D_1_5_TLM_BEZIRKSGEBIET, swissBOUNDARIES3D_1_5_TLM_HOHEITSGEBIET, swissBOUNDARIES3D_1_5_TLM_KANTONSGEBIET) found within.

IMPORTANT:

The swissBOUNDARIES3D_1_5_TLM_LANDESGEBIET is NOT read because it contains enclaves of Germany which are not relevant for Swiss geographic names. The swissBOUNDARIES3D_1_5_TLM_HOHEITSGRENZE is NOT read because it contains lines already in swissBOUNDARIES3D_1_5_TLM_HOHEITSGEBIET.

All geometries are returned as GeoJSON in WGS84 (EPSG:4326).

Arguments:
  • data_path: Path to swissBoundaries3D data file or directory containing swissBoundaries3D shapefiles.
  • layer: Layer name within the data source (for multi-layer formats like GDB).
Example:
>>> source = SwissBoundaries3DSource("data/")  # Load all 3 geometry types
>>> results = source.search("Bern", type="canton")
>>> print(results[0].geometry)  # GeoJSON in WGS84
SwissBoundaries3DSource(data_path: str | pathlib._local.Path, layer: str | None = None)
81    def __init__(self, data_path: str | Path, layer: str | None = None) -> None:
82        _require_files_extra()
83        self._data_path = Path(data_path)
84        self._layer = layer
85        self._gdf: gpd.GeoDataFrame | None = None
86        self._name_index: dict[str, list[int]] = {}
87        self._token_index: dict[str, set[str]] = {}
88        self._name_col: str = ""
89        self._type_col: str | None = None
90        self._id_col: str | None = None
91        self._extra_cols: list[str] = []
def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
237    def search(
238        self,
239        name: str,
240        type: str | None = None,
241        max_results: int = 10,
242    ) -> list[Feature]:
243        """
244        Search for geographic features by name.
245
246        Uses case-insensitive, accent-normalized matching with fuzzy fallback.
247        First tries exact matching, then falls back to fuzzy matching if no exact
248        matches found.
249
250        Args:
251            name: Location name to search for.
252            type: Optional type hint to filter results. If provided, only features
253                  of this type are returned.
254            max_results: Maximum number of results to return.
255
256        Returns:
257            List of matching GeoJSON Feature dicts. If type is provided, only
258            features of that type are returned. Empty list if no matches found.
259        """
260        self._ensure_loaded()
261
262        normalized = normalize_name(name)
263        indices = self._name_index.get(normalized, [])
264
265        # If no exact match, try fuzzy matching
266        if not indices:
267            indices = self._fuzzy_search(normalized)
268
269        features = [self._row_to_feature(idx) for idx in indices]
270
271        # Filter by type if type hint provided.
272        # Expand via the type hierarchy so that category hints (e.g. "water") match
273        # all concrete types within that category ("lake", "river", "pond", ...).
274        if type is not None:
275            matching_types = get_matching_types(type)
276            if matching_types:
277                features = [f for f in features if f["properties"].get("type") in matching_types]
278            else:
279                # Unknown type hint, fall back to exact string match
280                features = [f for f in features if f["properties"].get("type") == type.lower()]
281
282        return features[:max_results]

Search for geographic features by name.

Uses case-insensitive, accent-normalized matching with fuzzy fallback. First tries exact matching, then falls back to fuzzy matching if no exact matches found.

Arguments:
  • name: Location name to search for.
  • type: Optional type hint to filter results. If provided, only features of this type are returned.
  • max_results: Maximum number of results to return.
Returns:

List of matching GeoJSON Feature dicts. If type is provided, only features of that type are returned. Empty list if no matches found.

def get_available_types(self) -> list[str]:
284    def get_available_types(self) -> list[str]:
285        """
286        Get list of concrete geographic types this datasource can return.
287
288        Returns all normalized types from the OBJEKTART_TYPE_MAP keys,
289        representing all possible types that swissBoundaries3D data can be classified as.
290
291        Returns:
292            Sorted list of type strings (e.g., ["canton", "municipality", "district", ...])
293        """
294        return sorted(OBJEKTART_TYPE_MAP.keys())

Get list of concrete geographic types this datasource can return.

Returns all normalized types from the OBJEKTART_TYPE_MAP keys, representing all possible types that swissBoundaries3D data can be classified as.

Returns:

Sorted list of type strings (e.g., ["canton", "municipality", "district", ...])

class IGNBDCartoSource(etter.datasources.geo_dataframe_source.GeoDataFrameSource):
243class IGNBDCartoSource(GeoDataFrameSource):
244    """
245    Geographic data source backed by IGN's BD-CARTO 5.0 dataset.
246
247    Loads French geographic data from GeoPackage files extracted to a directory.
248    Supports administrative boundaries (communes, departments, regions, …),
249    hydrography (rivers, lakes, …), named places (quarters, hamlets, …),
250    orographic features (peaks, passes, valleys, …) and protected areas.
251
252    Data must first be downloaded with ``make download-data-ign``, which places
253    the GeoPackage files in ``data/bdcarto/``.
254
255    All geometries are reprojected from EPSG:2154 (Lambert-93) to WGS84
256    (EPSG:4326) and returned as standard GeoJSON Feature dicts.
257
258    Args:
259        data_path: Directory containing the ``.gpkg`` files (e.g. ``"data/bdcarto"``).
260
261    Example:
262        >>> source = IGNBDCartoSource("data/bdcarto")
263        >>> results = source.search("Ardèche", type="department")
264        >>> results = source.search("Lyon", type="city")
265        >>> results = source.search("Rhône", type="river")
266    """
267
268    def __init__(self, data_path: str | Path) -> None:
269        _require_files_extra()
270        self._data_path = Path(data_path)
271        self._gdf: gpd.GeoDataFrame | None = None
272        self._name_index: dict[str, list[int]] = {}
273        self._token_index: dict[str, set[str]] = {}
274        self._id_col: str | None = "cleabs"
275
276    def _load_data(self) -> None:
277        if self._data_path.is_dir():
278            self._gdf = self._load_from_directory()
279        else:
280            self._gdf = self._load_from_file(self._data_path)
281
282        self._build_name_index()
283
284    def _load_from_file(self, path: Path) -> gpd.GeoDataFrame:
285        """Load from a GeoJSON fixture file. Features must include a ``_layer`` column."""
286        import geopandas as gpd
287        import pandas as pd
288
289        full_gdf = gpd.read_file(str(path))
290        if "_layer" not in full_gdf.columns:
291            raise ValueError(f"GeoJSON fixture {path} must include a '_layer' column")
292
293        gdfs: list[gpd.GeoDataFrame] = []
294        for layer_name, cfg in _LAYER_CONFIGS.items():
295            rows = full_gdf[full_gdf["_layer"] == layer_name].copy()
296            if rows.empty:
297                continue
298            name_col: str = cfg["name_col"]
299            if name_col not in rows.columns:
300                continue
301            rows[_NAME_COL] = rows[name_col].astype(str)
302            _assign_type_col(rows, cfg)
303            rows = rows.to_crs("EPSG:4326")
304            gdfs.append(rows)
305
306        if not gdfs:
307            raise ValueError(f"No matching BD-CARTO features found in {path}")
308
309        combined = pd.concat(gdfs, ignore_index=True)
310        return gpd.GeoDataFrame(combined, crs="EPSG:4326", geometry="geometry")
311
312    def _load_from_directory(self) -> gpd.GeoDataFrame:
313        """Load and concatenate all configured layers from the data directory."""
314        import geopandas as gpd
315        import pandas as pd
316
317        gdfs: list[gpd.GeoDataFrame] = []
318
319        for layer_name, cfg in _LAYER_CONFIGS.items():
320            gpkg_path = self._data_path / f"{layer_name}.gpkg"
321            if not gpkg_path.exists():
322                continue
323
324            gdf = gpd.read_file(str(gpkg_path))
325
326            name_col: str = cfg["name_col"]
327            if name_col not in gdf.columns:
328                continue
329
330            gdf[_NAME_COL] = gdf[name_col].astype(str)
331            _assign_type_col(gdf, cfg)
332            gdf["_layer"] = layer_name
333            gdf = gdf.to_crs("EPSG:4326")
334
335            gdfs.append(gdf)
336
337        if not gdfs:
338            raise ValueError(
339                f"No BD-CARTO GeoPackage files found in {self._data_path}. "
340                f"Run 'make download-data-ign' to download the dataset."
341            )
342
343        combined = pd.concat(gdfs, ignore_index=True)
344        return gpd.GeoDataFrame(combined, crs="EPSG:4326", geometry="geometry")
345
346    def _build_name_index(self) -> None:
347        """Build normalized name → row indices and token → candidate names indexes."""
348        assert self._gdf is not None
349        self._name_index = {}
350        self._token_index = {}
351        for idx, name in enumerate(self._gdf[_NAME_COL]):
352            if not isinstance(name, str) or not name.strip() or name == "nan":
353                continue
354            for key in _index_keys(name):
355                if key not in self._name_index:
356                    self._name_index[key] = []
357                self._name_index[key].append(idx)
358                for token in key.split():
359                    if token not in self._token_index:
360                        self._token_index[token] = set()
361                    self._token_index[token].add(key)
362
363    def _row_type(self, idx: int) -> str:
364        """Return a row's normalized type without building its full Feature (geometry, etc.)."""
365        assert self._gdf is not None
366        row = self._gdf.iloc[idx]
367        return str(row[_TYPE_COL]) if not _is_missing(row.get(_TYPE_COL)) else "unknown"
368
369    def _row_to_feature(self, idx: int) -> Feature:
370        """Convert a GeoDataFrame row to a GeoJSON Feature dict (WGS84)."""
371        assert self._gdf is not None
372        row = self._gdf.iloc[idx]
373
374        name = str(row[_NAME_COL])
375        normalized_type = self._row_type(idx)
376        feature_id = str(row["cleabs"]) if not _is_missing(row.get("cleabs")) else str(idx)
377
378        geom = row.geometry
379        if geom is None or geom.is_empty:
380            geometry: dict[str, Any] = {"type": "Point", "coordinates": [0, 0]}
381            bbox = None
382        else:
383            geometry = mapping(geom)
384            bounds = geom.bounds
385            bbox: tuple[float, float, float, float] | None = (bounds[0], bounds[1], bounds[2], bounds[3])
386
387        skip_cols = {_NAME_COL, _TYPE_COL, "geometry", "cleabs"}
388        properties: dict[str, Any] = {
389            "name": name,
390            "type": normalized_type,
391            "confidence": 1.0,
392        }
393        for col in self._gdf.columns:
394            if col not in skip_cols:
395                val = to_serializable(row.get(col))
396                if val is not None:
397                    properties[col] = val
398
399        return Feature(geometry=geometry, properties=properties, id=feature_id, bbox=bbox)
400
401    def search(
402        self,
403        name: str,
404        type: str | None = None,
405        max_results: int = 10,
406    ) -> list[Feature]:
407        """
408        Search for geographic features by name.
409
410        Uses case-insensitive, accent-normalized exact matching with fuzzy
411        fallback when no exact match is found.
412
413        Args:
414            name: Location name to search for (e.g. ``"Ardèche"``, ``"Lyon"``,
415                  ``"Rhône"``).
416            type: Optional type hint for filtering. Supports both concrete types
417                  (``"department"``, ``"city"``, ``"river"``) and category hints
418                  (``"administrative"``, ``"water"``).
419            max_results: Maximum number of results.
420
421        Returns:
422            List of GeoJSON Feature dicts in WGS84. Empty list if no match.
423        """
424        self._ensure_loaded()
425
426        normalized = normalize_name(name)
427        indices = self._name_index.get(normalized, [])
428
429        if not indices:
430            indices = self._fuzzy_search(normalized)
431
432        # Filter by type if type hint provided, before building the (geometry-heavy) Feature
433        # for each row — so rows dropped by the filter skip that work entirely.
434        if type is not None:
435            matching_types = get_matching_types(type)
436            logger.debug("Filtering results by type hint %r → matching types: %s", type, matching_types)
437            if matching_types:
438                indices = [idx for idx in indices if self._row_type(idx) in matching_types]
439            else:
440                indices = [idx for idx in indices if self._row_type(idx) == type.lower()]
441
442        features = [self._row_to_feature(idx) for idx in indices]
443
444        features = merge_segments(features)
445
446        return features[:max_results]
447
448    def get_available_types(self) -> list[str]:
449        """
450        Return the union of all normalized types this source can return.
451
452        Returns:
453            Sorted list of type strings.
454        """
455        types: set[str] = set()
456        for cfg in _LAYER_CONFIGS.values():
457            if cfg.get("commune_flags"):
458                types.update({"city", "municipality"})
459            elif cfg.get("fixed_type"):
460                types.add(cfg["fixed_type"])
461            elif cfg.get("type_map"):
462                types.update(cfg["type_map"].values())
463        return sorted(types)

Geographic data source backed by IGN's BD-CARTO 5.0 dataset.

Loads French geographic data from GeoPackage files extracted to a directory. Supports administrative boundaries (communes, departments, regions, …), hydrography (rivers, lakes, …), named places (quarters, hamlets, …), orographic features (peaks, passes, valleys, …) and protected areas.

Data must first be downloaded with make download-data-ign, which places the GeoPackage files in data/bdcarto/.

All geometries are reprojected from EPSG:2154 (Lambert-93) to WGS84 (EPSG:4326) and returned as standard GeoJSON Feature dicts.

Arguments:
  • data_path: Directory containing the .gpkg files (e.g. "data/bdcarto").
Example:
>>> source = IGNBDCartoSource("data/bdcarto")
>>> results = source.search("Ardèche", type="department")
>>> results = source.search("Lyon", type="city")
>>> results = source.search("Rhône", type="river")
IGNBDCartoSource(data_path: str | pathlib._local.Path)
268    def __init__(self, data_path: str | Path) -> None:
269        _require_files_extra()
270        self._data_path = Path(data_path)
271        self._gdf: gpd.GeoDataFrame | None = None
272        self._name_index: dict[str, list[int]] = {}
273        self._token_index: dict[str, set[str]] = {}
274        self._id_col: str | None = "cleabs"
def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
401    def search(
402        self,
403        name: str,
404        type: str | None = None,
405        max_results: int = 10,
406    ) -> list[Feature]:
407        """
408        Search for geographic features by name.
409
410        Uses case-insensitive, accent-normalized exact matching with fuzzy
411        fallback when no exact match is found.
412
413        Args:
414            name: Location name to search for (e.g. ``"Ardèche"``, ``"Lyon"``,
415                  ``"Rhône"``).
416            type: Optional type hint for filtering. Supports both concrete types
417                  (``"department"``, ``"city"``, ``"river"``) and category hints
418                  (``"administrative"``, ``"water"``).
419            max_results: Maximum number of results.
420
421        Returns:
422            List of GeoJSON Feature dicts in WGS84. Empty list if no match.
423        """
424        self._ensure_loaded()
425
426        normalized = normalize_name(name)
427        indices = self._name_index.get(normalized, [])
428
429        if not indices:
430            indices = self._fuzzy_search(normalized)
431
432        # Filter by type if type hint provided, before building the (geometry-heavy) Feature
433        # for each row — so rows dropped by the filter skip that work entirely.
434        if type is not None:
435            matching_types = get_matching_types(type)
436            logger.debug("Filtering results by type hint %r → matching types: %s", type, matching_types)
437            if matching_types:
438                indices = [idx for idx in indices if self._row_type(idx) in matching_types]
439            else:
440                indices = [idx for idx in indices if self._row_type(idx) == type.lower()]
441
442        features = [self._row_to_feature(idx) for idx in indices]
443
444        features = merge_segments(features)
445
446        return features[:max_results]

Search for geographic features by name.

Uses case-insensitive, accent-normalized exact matching with fuzzy fallback when no exact match is found.

Arguments:
  • name: Location name to search for (e.g. "Ardèche", "Lyon", "Rhône").
  • type: Optional type hint for filtering. Supports both concrete types ("department", "city", "river") and category hints ("administrative", "water").
  • max_results: Maximum number of results.
Returns:

List of GeoJSON Feature dicts in WGS84. Empty list if no match.

def get_available_types(self) -> list[str]:
448    def get_available_types(self) -> list[str]:
449        """
450        Return the union of all normalized types this source can return.
451
452        Returns:
453            Sorted list of type strings.
454        """
455        types: set[str] = set()
456        for cfg in _LAYER_CONFIGS.values():
457            if cfg.get("commune_flags"):
458                types.update({"city", "municipality"})
459            elif cfg.get("fixed_type"):
460                types.add(cfg["fixed_type"])
461            elif cfg.get("type_map"):
462                types.update(cfg["type_map"].values())
463        return sorted(types)

Return the union of all normalized types this source can return.

Returns:

Sorted list of type strings.

class CompositeDataSource:
 20class CompositeDataSource:
 21    """
 22    Fan-out datasource that delegates to an ordered list of GeoDataSource instances.
 23
 24    ``search`` queries every registered source and merges results in order.
 25
 26    ``get_by_id`` tries each source in order and returns the first hit.
 27
 28    ``get_available_types`` returns the union of all sources' types.
 29
 30    Args:
 31        sources: One or more GeoDataSource instances.
 32
 33    Example:
 34        >>> swiss = SwissNames3DSource("data/")
 35        >>> ign   = IGNBDTopoSource("data/")
 36        >>> combo = CompositeDataSource(swiss, ign)
 37        >>> results = combo.search("Geneva", type="city")
 38    """
 39
 40    def __init__(self, *sources: GeoDataSource) -> None:
 41        if not sources:
 42            raise ValueError("At least one datasource is required.")
 43        self._sources: list[GeoDataSource] = list(sources)
 44
 45    def preload(self) -> None:
 46        """Eagerly load all sources that support preloading."""
 47        for source in self._sources:
 48            if isinstance(source, _Preloadable):
 49                source.preload()
 50
 51    # Public API (mirrors GeoDataSource protocol)
 52
 53    def search(
 54        self,
 55        name: str,
 56        type: str | None = None,
 57        max_results: int = 10,
 58    ) -> list[Feature]:
 59        """
 60        Search all registered sources and return merged.
 61
 62        Args:
 63            name: Location name to search for.
 64            type: Optional type hint passed through to every source.
 65            max_results: Maximum results per source.
 66
 67        Returns:
 68            List of GeoJSON Feature dicts, merged from all sources.
 69        """
 70        merged: list[Feature] = []
 71
 72        for source in self._sources:
 73            merged.extend(source.search(name, type=type, max_results=max_results))
 74
 75        return merged
 76
 77    def get_by_id(self, feature_id: str) -> Feature | None:
 78        """
 79        Get a feature by ID, trying each source in order.
 80
 81        Args:
 82            feature_id: Unique identifier to look up.
 83
 84        Returns:
 85            The first matching GeoJSON Feature dict, or None.
 86        """
 87        for source in self._sources:
 88            result = source.get_by_id(feature_id)
 89            if result is not None:
 90                return result
 91        return None
 92
 93    def get_available_types(self) -> list[str]:
 94        """
 95        Return the union of all sources' available types, sorted.
 96
 97        Returns:
 98            Sorted list of unique type strings.
 99        """
100        types: set[str] = set()
101        for source in self._sources:
102            types.update(source.get_available_types())
103        return sorted(types)

Fan-out datasource that delegates to an ordered list of GeoDataSource instances.

search queries every registered source and merges results in order.

get_by_id tries each source in order and returns the first hit.

get_available_types returns the union of all sources' types.

Arguments:
  • sources: One or more GeoDataSource instances.
Example:
>>> swiss = SwissNames3DSource("data/")
>>> ign   = IGNBDTopoSource("data/")
>>> combo = CompositeDataSource(swiss, ign)
>>> results = combo.search("Geneva", type="city")
CompositeDataSource(*sources: GeoDataSource)
40    def __init__(self, *sources: GeoDataSource) -> None:
41        if not sources:
42            raise ValueError("At least one datasource is required.")
43        self._sources: list[GeoDataSource] = list(sources)
def preload(self) -> None:
45    def preload(self) -> None:
46        """Eagerly load all sources that support preloading."""
47        for source in self._sources:
48            if isinstance(source, _Preloadable):
49                source.preload()

Eagerly load all sources that support preloading.

def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
53    def search(
54        self,
55        name: str,
56        type: str | None = None,
57        max_results: int = 10,
58    ) -> list[Feature]:
59        """
60        Search all registered sources and return merged.
61
62        Args:
63            name: Location name to search for.
64            type: Optional type hint passed through to every source.
65            max_results: Maximum results per source.
66
67        Returns:
68            List of GeoJSON Feature dicts, merged from all sources.
69        """
70        merged: list[Feature] = []
71
72        for source in self._sources:
73            merged.extend(source.search(name, type=type, max_results=max_results))
74
75        return merged

Search all registered sources and return merged.

Arguments:
  • name: Location name to search for.
  • type: Optional type hint passed through to every source.
  • max_results: Maximum results per source.
Returns:

List of GeoJSON Feature dicts, merged from all sources.

def get_by_id(self, feature_id: str) -> geojson.feature.Feature | None:
77    def get_by_id(self, feature_id: str) -> Feature | None:
78        """
79        Get a feature by ID, trying each source in order.
80
81        Args:
82            feature_id: Unique identifier to look up.
83
84        Returns:
85            The first matching GeoJSON Feature dict, or None.
86        """
87        for source in self._sources:
88            result = source.get_by_id(feature_id)
89            if result is not None:
90                return result
91        return None

Get a feature by ID, trying each source in order.

Arguments:
  • feature_id: Unique identifier to look up.
Returns:

The first matching GeoJSON Feature dict, or None.

def get_available_types(self) -> list[str]:
 93    def get_available_types(self) -> list[str]:
 94        """
 95        Return the union of all sources' available types, sorted.
 96
 97        Returns:
 98            Sorted list of unique type strings.
 99        """
100        types: set[str] = set()
101        for source in self._sources:
102            types.update(source.get_available_types())
103        return sorted(types)

Return the union of all sources' available types, sorted.

Returns:

Sorted list of unique type strings.

class PostGISDataSource:
 60class PostGISDataSource:
 61    """
 62    Geographic data source backed by a PostGIS table.
 63
 64    The table must expose at minimum a name column, a geometry column, and
 65    optionally a type column. The expected schema is:
 66
 67    .. code-block:: sql
 68
 69        CREATE TABLE <table> (
 70            id      TEXT PRIMARY KEY,
 71            name    TEXT NOT NULL,
 72            type    TEXT,
 73            geom    GEOMETRY(Geometry, 4326)
 74        );
 75
 76    The ``type`` column may store either:
 77
 78    - **Raw dataset values** (e.g. ``"See"``, ``"Berg"`` for SwissNames3D),
 79      pass ``type_map`` so the datasource can translate between raw values and
 80      the normalized etter type names.
 81    - **Already-normalized values** (e.g. ``"lake"``, ``"mountain"``),
 82      leave ``type_map=None`` (default).
 83
 84    Geometries must be in WGS84 (EPSG:4326) or supply ``crs`` for on-the-fly
 85    reprojection.
 86
 87    Args:
 88        connection: A SQLAlchemy :class:`~sqlalchemy.engine.Engine` **or** a
 89            connection URL string (e.g. ``"postgresql+psycopg2://user:pass@host/db"``).
 90            When a string is provided the engine is created internally.
 91        table: Fully-qualified table name, e.g. ``"public.swissnames3d"``.
 92        name_column: Column used for name-based search (default ``"name"``).
 93        type_column: Column used for type filtering.  Pass ``None`` to disable
 94            type filtering (default ``"type"``).
 95        geometry_column: PostGIS geometry column (default ``"geom"``).
 96        id_column: Primary-key column (default ``"id"``).
 97        crs: CRS of the stored geometries as an EPSG string.  Defaults to
 98            ``"EPSG:4326"`` (no reprojection).
 99        type_map: Optional mapping from **normalized etter type names** to
100            **lists of raw type column values** present in the database.
101            This is the same format as ``SwissNames3DSource.OBJEKTART_TYPE_MAP``
102            and ``IGNBDCartoSource.IGN_BDCARTO_TYPE_MAP``, so they can be
103            passed directly::
104
105                from etter.datasources.swissnames3d import OBJEKTART_TYPE_MAP
106                source = PostGISDataSource(
107                    engine,
108                    table="public.swissnames3d",
109                    type_map=OBJEKTART_TYPE_MAP,
110                )
111
112            When ``type_map`` is provided the datasource:
113
114            - Translates raw DB values → normalized types in returned features.
115            - Translates user type hints → raw DB values in SQL ``WHERE`` clauses.
116            - Returns normalized type names from ``get_available_types()``.
117
118            When ``None`` (default) the stored values are used as-is.
119        fuzzy_threshold: Minimum ``pg_trgm`` similarity score (0-1) used for
120            fuzzy fallback search when no exact ``ILIKE`` match is found.
121
122    .. note::
123        The fuzzy fallback scans every row (``word_similarity()`` is not
124        indexable via a plain B-tree). For large tables, add a trigram index
125        on the name column to speed it up::
126
127            CREATE INDEX ON <table> USING gist (name gist_trgm_ops);
128
129    Example: unmodified SwissNames3D table::
130
131        from sqlalchemy import create_engine
132        from etter.datasources import PostGISDataSource
133        from etter.datasources.swissnames3d import OBJEKTART_TYPE_MAP
134
135        engine = create_engine(...)
136        source = PostGISDataSource(
137            engine,
138            table="public.swissnames3d",
139            type_map=OBJEKTART_TYPE_MAP,
140        )
141        results = source.search("Lac Léman", type="lake")
142    """
143
144    def __init__(
145        self,
146        connection: str | Engine,
147        table: str,
148        name_column: str = "name",
149        type_column: str | None = "type",
150        geometry_column: str = "geom",
151        id_column: str = "id",
152        crs: str = "EPSG:4326",
153        type_map: TypeMap | None = None,
154        fuzzy_threshold: float = 0.65,
155    ) -> None:
156        sa = _require_sqlalchemy()
157
158        if isinstance(connection, str):
159            self._engine = sa.create_engine(connection)
160        else:
161            self._engine = connection
162
163        try:
164            with self._engine.connect() as conn:
165                conn.execute(sa.text(f"SELECT 1 FROM {table} LIMIT 1"))
166        except Exception as exc:
167            raise ValueError(f"Failed to connect to database or access table {table!r}") from exc
168
169        self._table = table
170        self._name_col = name_column
171        self._type_col = type_column
172        self._geom_col = geometry_column
173        self._id_col = id_column
174        self._crs = crs
175        self._fuzzy_threshold = fuzzy_threshold
176
177        # Build bidirectional lookup structures from the user-supplied map.
178        if type_map:
179            self._normalized_to_raw: dict[str, list[str]] = {k: list(v) for k, v in type_map.items()}
180            self._raw_to_normalized: dict[str, str] = {
181                raw: normalized for normalized, raws in type_map.items() for raw in raws
182            }
183        else:
184            self._normalized_to_raw = {}
185            self._raw_to_normalized = {}
186
187        self._trgm_available: bool | None = None
188        self._unaccent_available: bool | None = None
189
190    def _get_connection(self) -> Connection:
191        """Return a SQLAlchemy connection from the engine."""
192        return self._engine.connect()
193
194    def _check_trgm(self, conn: Connection) -> bool:
195        """Return True if pg_trgm extension is available in the database."""
196        if self._trgm_available is not None:
197            return self._trgm_available
198        sa = _require_sqlalchemy()
199        try:
200            result = conn.execute(sa.text("SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm'"))
201            self._trgm_available = result.fetchone() is not None
202        except Exception:
203            logger.exception("Failed to check pg_trgm availability")
204            self._trgm_available = False
205        return self._trgm_available
206
207    def _check_unaccent(self, conn: Connection) -> bool:
208        """Return True if the unaccent extension is available in the database."""
209        if self._unaccent_available is not None:
210            return self._unaccent_available
211        sa = _require_sqlalchemy()
212        try:
213            result = conn.execute(sa.text("SELECT 1 FROM pg_extension WHERE extname = 'unaccent'"))
214            self._unaccent_available = result.fetchone() is not None
215        except Exception:
216            logger.exception("Failed to check unaccent availability")
217            self._unaccent_available = False
218        return self._unaccent_available
219
220    def _normalize_type(self, raw_type: str | None) -> str | None:
221        """Translate a raw DB type value to its normalized etter name.
222
223        If no type_map was supplied the value is returned unchanged.
224        """
225        if raw_type is None:
226            return None
227        return self._raw_to_normalized.get(raw_type, raw_type)
228
229    def _row_to_feature(self, row: Row) -> Feature:
230        """Convert a SQLAlchemy Row to a GeoJSON Feature dict."""
231        feature_id = str(row.id)
232        name = str(row.name)
233        raw_type = getattr(row, "type", None)
234        normalized_type = self._normalize_type(raw_type)
235
236        geojson_str = row.geojson
237        if geojson_str:
238            geometry = json.loads(geojson_str)
239        else:
240            geometry = {"type": "Point", "coordinates": [0, 0]}
241
242        bbox = _bbox_from_geojson(geometry)
243
244        properties: dict[str, Any] = {
245            "name": name,
246            "type": normalized_type,
247            "confidence": 1.0,
248        }
249
250        return Feature(geometry=geometry, properties=properties, id=feature_id, bbox=bbox)
251
252    def _build_select_columns(self) -> str:
253        """Build the SELECT column list as a SQL fragment."""
254        type_expr = f", {self._type_col} AS type" if self._type_col else ", NULL AS type"
255        if self._crs.upper() != "EPSG:4326":
256            geom_expr = f", ST_AsGeoJSON(ST_Transform({self._geom_col}, 4326)) AS geojson"
257        else:
258            geom_expr = f", ST_AsGeoJSON({self._geom_col}) AS geojson"
259        return f"{self._id_col} AS id, {self._name_col} AS name{type_expr}{geom_expr}"
260
261    def search(
262        self,
263        name: str,
264        type: str | None = None,
265        max_results: int = 10,
266    ) -> list[Feature]:
267        """
268        Search for geographic features by name.
269
270        Uses a three-step cascade, stopping as soon as any step returns results:
271
272        1. **Normalized exact match**
273        2. **pg_trgm fuzzy with unaccent** (pg_trgm extension required and unaccent extension recommended)
274        3. **ILIKE substring**
275
276        ``merge_segments`` is applied after all rows are fetched so that
277        multi-segment linestrings (rivers, roads) are merged before the
278        ``max_results`` cap is applied.
279
280        Args:
281            name: Location name to search for.
282            type: Optional type hint for filtering results.
283            max_results: Maximum number of results to return.
284
285        Returns:
286            List of matching GeoJSON Feature dicts in WGS84.
287        """
288        sa = _require_sqlalchemy()
289        cols = self._build_select_columns()
290
291        # Resolve type filter to the raw DB values to use in the SQL WHERE clause.
292        type_filter_values: list[str] | None = None
293        if type is not None and self._type_col is not None:
294            matching_types = get_matching_types(type)
295            concrete_types = matching_types if matching_types else [type.lower()]
296            if self._normalized_to_raw:
297                raw_values: list[str] = []
298                for t in concrete_types:
299                    raw_values.extend(self._normalized_to_raw.get(t, [t]))
300                type_filter_values = raw_values if raw_values else concrete_types
301            else:
302                type_filter_values = concrete_types
303
304        # Fetch more rows than requested so that merge_segments has the full
305        # set of segments to work with.  Without this, a SQL LIMIT applied
306        # *before* merging would only return a partial set of linestring
307        # segments, producing incorrect / truncated geometries.
308        # We cap the internal limit at 2000 to avoid unbounded queries.
309        internal_limit = min(max(max_results * 20, 100), 2000)
310
311        with self._get_connection() as conn:
312            features = self._search_normalized(conn, sa, cols, name, type_filter_values, internal_limit)
313
314        if not features:
315            with self._get_connection() as conn:
316                features = self._search_fuzzy(conn, sa, cols, name, type_filter_values, internal_limit)
317
318        if not features:
319            with self._get_connection() as conn:
320                features = self._search_ilike(conn, sa, cols, name, type_filter_values, internal_limit)
321
322        features = merge_segments(features)
323        return features[:max_results]
324
325    def _type_filter_sql(self, values: list[str] | None) -> tuple[str, dict[str, Any]]:
326        """Return a WHERE clause fragment and bind params for type filtering."""
327        if not values or self._type_col is None:
328            return "", {}
329        placeholders = ", ".join(f":type_{i}" for i in range(len(values)))
330        clause = f" AND {self._type_col} IN ({placeholders})"
331        params = {f"type_{i}": v for i, v in enumerate(values)}
332        return clause, params
333
334    def _search_normalized(
335        self,
336        conn: Connection,
337        sa: types.ModuleType,
338        cols: str,
339        name: str,
340        type_filter: list[str] | None,
341        fetch_limit: int,
342    ) -> list[Feature]:
343        """
344        Exact accent- and case-insensitive search.
345
346        Accent normalization (NFD decomposition + diacritic strip) is done in
347        Python before the query is sent to the DB.
348        """
349        type_clause, type_params = self._type_filter_sql(type_filter)
350        name_expr = f"lower({self._name_col})"
351        if self._check_unaccent(conn):
352            name_expr = f"unaccent({name_expr})"
353        sql = sa.text(f"""
354            SELECT {cols} FROM {self._table}
355            WHERE {name_expr} = :query{type_clause}
356            LIMIT :limit
357        """)  # noqa: S608
358        params: dict[str, Any] = {
359            "query": normalize_name(name),
360            "limit": fetch_limit,
361            **type_params,
362        }
363        try:
364            result = conn.execute(sql, params)
365            return [self._row_to_feature(row) for row in result]
366        except Exception:
367            logger.exception("Normalized search failed for %r", name)
368            return []
369
370    def _search_ilike(
371        self,
372        conn: Connection,
373        sa: types.ModuleType,
374        cols: str,
375        name: str,
376        type_filter: list[str] | None,
377        fetch_limit: int,
378    ) -> list[Feature]:
379        """Case-insensitive substring fallback using ``ILIKE '%name%'``.
380
381        When the ``unaccent`` extension is available, both the stored name column
382        and the pattern are accent-stripped so that e.g. ``"Rhone"`` matches
383        ``"Rhône"``.  Without ``unaccent``, standard ILIKE is used (case-insensitive
384        only).
385        """
386        type_clause, type_params = self._type_filter_sql(type_filter)
387        normalized = normalize_name(name)
388        if self._check_unaccent(conn):
389            name_expr = f"unaccent(lower({self._name_col}))"
390            pattern = f"%{normalized}%"
391        else:
392            name_expr = self._name_col
393            pattern = f"%{name}%"
394        sql = sa.text(f"""
395            SELECT {cols} FROM {self._table}
396            WHERE {name_expr} ILIKE :pattern{type_clause}
397            LIMIT :limit
398        """)  # noqa: S608
399        params: dict[str, Any] = {"pattern": pattern, "limit": fetch_limit, **type_params}
400        try:
401            result = conn.execute(sql, params)
402            return [self._row_to_feature(row) for row in result]
403        except Exception:
404            logger.exception("ILIKE search failed for %r", name)
405            return []
406
407    def _search_fuzzy(
408        self,
409        conn: Connection,
410        sa: types.ModuleType,
411        cols: str,
412        name: str,
413        type_filter: list[str] | None,
414        fetch_limit: int,
415    ) -> list[Feature]:
416        """Fuzzy fallback using pg_trgm similarity (if extension is available)."""
417        if not self._check_trgm(conn):
418            logger.warning(
419                "pg_trgm extension not available. Fuzzy search disabled. Install it with: CREATE EXTENSION pg_trgm;"
420            )
421            return []
422        normalized_query = normalize_name(name)
423        if self._check_unaccent(conn):
424            name_expr = f"unaccent(lower({self._name_col}))"
425        else:
426            logger.warning(
427                "unaccent extension not available. Accent-insensitive fuzzy search degraded. "
428                "Install it with: CREATE EXTENSION unaccent;"
429            )
430            name_expr = f"lower({self._name_col})"
431        type_clause, type_params = self._type_filter_sql(type_filter)
432        # Compute word_similarity() once in the subquery and reuse it via the
433        # "sim" alias, rather than evaluating it separately for the WHERE
434        # filter and the ORDER BY sort.
435        sql = sa.text(f"""
436            SELECT id, name, type, geojson FROM (
437                SELECT {cols}, word_similarity(:query, {name_expr}) AS sim
438                FROM {self._table} WHERE TRUE{type_clause}
439            ) AS scored
440            WHERE sim > :threshold
441            ORDER BY sim DESC
442            LIMIT :limit
443        """)  # noqa: S608
444        params: dict[str, Any] = {
445            "query": normalized_query,
446            "threshold": self._fuzzy_threshold,
447            "limit": fetch_limit,
448            **type_params,
449        }
450        try:
451            result = conn.execute(sql, params)
452            return [self._row_to_feature(row) for row in result]
453        except Exception:
454            logger.exception("Fuzzy search failed for %r", name)
455            return []
456
457    def get_by_id(self, feature_id: str) -> Feature | None:
458        """
459        Get a specific feature by its unique identifier.
460
461        Args:
462            feature_id: Value of the ``id`` column.
463
464        Returns:
465            The matching GeoJSON Feature dict, or ``None`` if not found.
466        """
467        sa = _require_sqlalchemy()
468        cols = self._build_select_columns()
469        sql = sa.text(
470            f"SELECT {cols} FROM {self._table} WHERE {self._id_col} = :id LIMIT 1"  # noqa: S608
471        )
472        with self._get_connection() as conn:
473            try:
474                result = conn.execute(sql, {"id": feature_id})
475                row = result.fetchone()
476                return self._row_to_feature(row) if row else None
477            except Exception:
478                logger.exception("get_by_id failed for %r", feature_id)
479                return None
480
481    def get_available_types(self) -> list[str]:
482        """
483        Return the distinct ``type`` values present in the table.
484
485        Returns:
486            Sorted list of concrete type strings, or an empty list if the table
487            has no type column.
488        """
489        if self._type_col is None:
490            return []
491        sa = _require_sqlalchemy()
492        sql = sa.text(
493            f"SELECT DISTINCT {self._type_col} AS type FROM {self._table} "  # noqa: S608
494            f"WHERE {self._type_col} IS NOT NULL ORDER BY 1"
495        )
496        with self._get_connection() as conn:
497            try:
498                result = conn.execute(sql)
499                raw_types = [row.type for row in result]
500            except Exception:
501                logger.exception("get_available_types failed")
502                return []
503
504        normalized = {self._normalize_type(t) for t in raw_types if t}
505        return sorted(t for t in normalized if t)

Geographic data source backed by a PostGIS table.

The table must expose at minimum a name column, a geometry column, and optionally a type column. The expected schema is:

CREATE TABLE <table> (
    id      TEXT PRIMARY KEY,
    name    TEXT NOT NULL,
    type    TEXT,
    geom    GEOMETRY(Geometry, 4326)
);

The type column may store either:

  • Raw dataset values (e.g. "See", "Berg" for SwissNames3D), pass type_map so the datasource can translate between raw values and the normalized etter type names.
  • Already-normalized values (e.g. "lake", "mountain"), leave type_map=None (default).

Geometries must be in WGS84 (EPSG:4326) or supply crs for on-the-fly reprojection.

Arguments:
  • connection: A SQLAlchemy ~sqlalchemy.engine.Engine or a connection URL string (e.g. "postgresql+psycopg2://user:pass@host/db"). When a string is provided the engine is created internally.
  • table: Fully-qualified table name, e.g. "public.swissnames3d".
  • name_column: Column used for name-based search (default "name").
  • type_column: Column used for type filtering. Pass None to disable type filtering (default "type").
  • geometry_column: PostGIS geometry column (default "geom").
  • id_column: Primary-key column (default "id").
  • crs: CRS of the stored geometries as an EPSG string. Defaults to "EPSG:4326" (no reprojection).
  • type_map: Optional mapping from normalized etter type names to lists of raw type column values present in the database. This is the same format as SwissNames3DSource.OBJEKTART_TYPE_MAP and IGNBDCartoSource.IGN_BDCARTO_TYPE_MAP, so they can be passed directly::

    from etter.datasources.swissnames3d import OBJEKTART_TYPE_MAP
    source = PostGISDataSource(
        engine,
        table="public.swissnames3d",
        type_map=OBJEKTART_TYPE_MAP,
    )
    

    When type_map is provided the datasource:

    • Translates raw DB values → normalized types in returned features.
    • Translates user type hints → raw DB values in SQL WHERE clauses.
    • Returns normalized type names from get_available_types().

    When None (default) the stored values are used as-is.

  • fuzzy_threshold: Minimum pg_trgm similarity score (0-1) used for fuzzy fallback search when no exact ILIKE match is found.

The fuzzy fallback scans every row (word_similarity() is not indexable via a plain B-tree). For large tables, add a trigram index on the name column to speed it up::

CREATE INDEX ON <table> USING gist (name gist_trgm_ops);

Example: unmodified SwissNames3D table::

from sqlalchemy import create_engine
from etter.datasources import PostGISDataSource
from etter.datasources.swissnames3d import OBJEKTART_TYPE_MAP

engine = create_engine(...)
source = PostGISDataSource(
    engine,
    table="public.swissnames3d",
    type_map=OBJEKTART_TYPE_MAP,
)
results = source.search("Lac Léman", type="lake")
PostGISDataSource( connection: str | sqlalchemy.engine.base.Engine, table: str, name_column: str = 'name', type_column: str | None = 'type', geometry_column: str = 'geom', id_column: str = 'id', crs: str = 'EPSG:4326', type_map: dict[typing.Literal['alpine_pasture', 'airport', 'area', 'arrondissement', 'border_marker', 'boulder', 'bridge', 'building', 'bus_stop', 'boat_stop', 'camping', 'canton', 'cave', 'cemetery', 'city', 'correctional_facility', 'country', 'customs', 'dam', 'department', 'district', 'ditch', 'entrance_exit', 'exit', 'fairground', 'ferry', 'field_name', 'forest', 'fountain', 'glacier', 'hamlet', 'heliport', 'hill', 'historical_site', 'hospital', 'island', 'junction', 'lake', 'leisure_facility', 'landfill', 'lift', 'loading_station', 'local_name', 'massif', 'military_training_area', 'monastery', 'monument', 'mountain', 'municipality', 'nature_reserve', 'park', 'parking', 'pass', 'peak', 'peninsula', 'plain', 'pond', 'power_plant', 'private_driving_area', 'quarry', 'railway', 'railway_area', 'region', 'religious_building', 'rest_area', 'restaurant', 'ridge', 'river', 'road', 'rock_head', 'school', 'spring', 'sports_facility', 'standing_area', 'swimming_pool', 'town', 'tower', 'train_station', 'tunnel', 'unknown', 'valley', 'viewpoint', 'village', 'wastewater_treatment', 'waste_incineration', 'waterfall', 'weir', 'zoo', 'administrative', 'amenity', 'infrastructure', 'landforms', 'natural', 'other', 'settlement', 'transport', 'water'], list[str]] | None = None, fuzzy_threshold: float = 0.65)
144    def __init__(
145        self,
146        connection: str | Engine,
147        table: str,
148        name_column: str = "name",
149        type_column: str | None = "type",
150        geometry_column: str = "geom",
151        id_column: str = "id",
152        crs: str = "EPSG:4326",
153        type_map: TypeMap | None = None,
154        fuzzy_threshold: float = 0.65,
155    ) -> None:
156        sa = _require_sqlalchemy()
157
158        if isinstance(connection, str):
159            self._engine = sa.create_engine(connection)
160        else:
161            self._engine = connection
162
163        try:
164            with self._engine.connect() as conn:
165                conn.execute(sa.text(f"SELECT 1 FROM {table} LIMIT 1"))
166        except Exception as exc:
167            raise ValueError(f"Failed to connect to database or access table {table!r}") from exc
168
169        self._table = table
170        self._name_col = name_column
171        self._type_col = type_column
172        self._geom_col = geometry_column
173        self._id_col = id_column
174        self._crs = crs
175        self._fuzzy_threshold = fuzzy_threshold
176
177        # Build bidirectional lookup structures from the user-supplied map.
178        if type_map:
179            self._normalized_to_raw: dict[str, list[str]] = {k: list(v) for k, v in type_map.items()}
180            self._raw_to_normalized: dict[str, str] = {
181                raw: normalized for normalized, raws in type_map.items() for raw in raws
182            }
183        else:
184            self._normalized_to_raw = {}
185            self._raw_to_normalized = {}
186
187        self._trgm_available: bool | None = None
188        self._unaccent_available: bool | None = None
def search( self, name: str, type: str | None = None, max_results: int = 10) -> list[geojson.feature.Feature]:
261    def search(
262        self,
263        name: str,
264        type: str | None = None,
265        max_results: int = 10,
266    ) -> list[Feature]:
267        """
268        Search for geographic features by name.
269
270        Uses a three-step cascade, stopping as soon as any step returns results:
271
272        1. **Normalized exact match**
273        2. **pg_trgm fuzzy with unaccent** (pg_trgm extension required and unaccent extension recommended)
274        3. **ILIKE substring**
275
276        ``merge_segments`` is applied after all rows are fetched so that
277        multi-segment linestrings (rivers, roads) are merged before the
278        ``max_results`` cap is applied.
279
280        Args:
281            name: Location name to search for.
282            type: Optional type hint for filtering results.
283            max_results: Maximum number of results to return.
284
285        Returns:
286            List of matching GeoJSON Feature dicts in WGS84.
287        """
288        sa = _require_sqlalchemy()
289        cols = self._build_select_columns()
290
291        # Resolve type filter to the raw DB values to use in the SQL WHERE clause.
292        type_filter_values: list[str] | None = None
293        if type is not None and self._type_col is not None:
294            matching_types = get_matching_types(type)
295            concrete_types = matching_types if matching_types else [type.lower()]
296            if self._normalized_to_raw:
297                raw_values: list[str] = []
298                for t in concrete_types:
299                    raw_values.extend(self._normalized_to_raw.get(t, [t]))
300                type_filter_values = raw_values if raw_values else concrete_types
301            else:
302                type_filter_values = concrete_types
303
304        # Fetch more rows than requested so that merge_segments has the full
305        # set of segments to work with.  Without this, a SQL LIMIT applied
306        # *before* merging would only return a partial set of linestring
307        # segments, producing incorrect / truncated geometries.
308        # We cap the internal limit at 2000 to avoid unbounded queries.
309        internal_limit = min(max(max_results * 20, 100), 2000)
310
311        with self._get_connection() as conn:
312            features = self._search_normalized(conn, sa, cols, name, type_filter_values, internal_limit)
313
314        if not features:
315            with self._get_connection() as conn:
316                features = self._search_fuzzy(conn, sa, cols, name, type_filter_values, internal_limit)
317
318        if not features:
319            with self._get_connection() as conn:
320                features = self._search_ilike(conn, sa, cols, name, type_filter_values, internal_limit)
321
322        features = merge_segments(features)
323        return features[:max_results]

Search for geographic features by name.

Uses a three-step cascade, stopping as soon as any step returns results:

  1. Normalized exact match
  2. pg_trgm fuzzy with unaccent (pg_trgm extension required and unaccent extension recommended)
  3. ILIKE substring

merge_segments is applied after all rows are fetched so that multi-segment linestrings (rivers, roads) are merged before the max_results cap is applied.

Arguments:
  • name: Location name to search for.
  • type: Optional type hint for filtering results.
  • max_results: Maximum number of results to return.
Returns:

List of matching GeoJSON Feature dicts in WGS84.

def get_by_id(self, feature_id: str) -> geojson.feature.Feature | None:
457    def get_by_id(self, feature_id: str) -> Feature | None:
458        """
459        Get a specific feature by its unique identifier.
460
461        Args:
462            feature_id: Value of the ``id`` column.
463
464        Returns:
465            The matching GeoJSON Feature dict, or ``None`` if not found.
466        """
467        sa = _require_sqlalchemy()
468        cols = self._build_select_columns()
469        sql = sa.text(
470            f"SELECT {cols} FROM {self._table} WHERE {self._id_col} = :id LIMIT 1"  # noqa: S608
471        )
472        with self._get_connection() as conn:
473            try:
474                result = conn.execute(sql, {"id": feature_id})
475                row = result.fetchone()
476                return self._row_to_feature(row) if row else None
477            except Exception:
478                logger.exception("get_by_id failed for %r", feature_id)
479                return None

Get a specific feature by its unique identifier.

Arguments:
  • feature_id: Value of the id column.
Returns:

The matching GeoJSON Feature dict, or None if not found.

def get_available_types(self) -> list[str]:
481    def get_available_types(self) -> list[str]:
482        """
483        Return the distinct ``type`` values present in the table.
484
485        Returns:
486            Sorted list of concrete type strings, or an empty list if the table
487            has no type column.
488        """
489        if self._type_col is None:
490            return []
491        sa = _require_sqlalchemy()
492        sql = sa.text(
493            f"SELECT DISTINCT {self._type_col} AS type FROM {self._table} "  # noqa: S608
494            f"WHERE {self._type_col} IS NOT NULL ORDER BY 1"
495        )
496        with self._get_connection() as conn:
497            try:
498                result = conn.execute(sql)
499                raw_types = [row.type for row in result]
500            except Exception:
501                logger.exception("get_available_types failed")
502                return []
503
504        normalized = {self._normalize_type(t) for t in raw_types if t}
505        return sorted(t for t in normalized if t)

Return the distinct type values present in the table.

Returns:

Sorted list of concrete type strings, or an empty list if the table has no type column.

def apply_spatial_relation( geometry: dict[str, typing.Any] | shapely.geometry.base.BaseGeometry | str | bytes | bytearray | memoryview | list[dict[str, typing.Any] | shapely.geometry.base.BaseGeometry | str | bytes | bytearray | memoryview], relation: SpatialRelation, buffer_config: BufferConfig | None = None, spatial_config: SpatialRelationConfig | None = None, geometry_format: Literal['geojson', 'wkt', 'wkb', 'shapely'] = 'geojson') -> dict[str, typing.Any] | str | shapely.geometry.base.BaseGeometry:
172def apply_spatial_relation(
173    geometry: GeometryInput | list[GeometryInput],
174    relation: SpatialRelation,
175    buffer_config: BufferConfig | None = None,
176    spatial_config: SpatialRelationConfig | None = None,
177    geometry_format: GeometryFormat = "geojson",
178) -> GeoJsonGeometry | str | BaseGeometry:
179    """Transform one or more reference geometries according to a spatial relation.
180
181    A list of geometries is unioned into one before the transformation, so that
182    features split across multiple datasource records (e.g. a river in segments)
183    produce a single coherent search area.
184
185    When ``buffer_config.inferred`` is True (i.e. no explicit distance was
186    stated) and the relation's config sets ``scale_with_area``, the buffer
187    distance is refined from the reference polygon's area so that small
188    features receive small buffers and large regions receive large ones.
189    Other relations, and point or line references, keep the default distance.
190    The sized distance is written into ``buffer_config.distance_m`` in place, so
191    the caller can read it back: pass a copy (``buffer_config.model_copy()``)
192    when the config is shared or reused across calls.
193
194    Args:
195        geometry: Reference geometry in WGS84, or a non-empty list of them: a GeoJSON dict,
196            a WKT or hex-encoded WKB string (as ``geometry_format`` returns), WKB bytes, or
197            a shapely geometry.
198        relation: Spatial relation to apply.
199        buffer_config: Required for buffer/directional relations.
200        spatial_config: Relation registry; defaults to the module-level singleton.
201        geometry_format: "geojson" (default), "wkt", "wkb", or "shapely". Ask for "shapely" to
202            write the area in more than one format, e.g. WKB for a query and GeoJSON for a
203            response, without parsing it again.
204
205    Returns:
206        Transformed geometry in the requested format.
207    """
208    if isinstance(geometry, list):
209        if not geometry:
210            raise ValueError("geometry list must not be empty")
211        geom = unary_union([parse_geometry(g) for g in geometry])
212    else:
213        geom = parse_geometry(geometry)
214
215    cfg = spatial_config if spatial_config is not None else _DEFAULT_SPATIAL_CONFIG
216
217    # Refine inferred buffer distance from geometry area before dispatching.
218    if buffer_config is not None:
219        buffer_config = _refine_buffer_config(geom, buffer_config, relation, cfg.relations.get(relation.relation))
220
221    if relation.category == "containment":
222        if geom.geom_type in ("Point", "MultiPoint", "LineString", "MultiLineString"):
223            # A point/line reference can't meaningfully "contain" anything (a search
224            # target almost never touches an exact point or crosses a line exactly);
225            # fall back to a small fixed buffer.
226            fallback_config = BufferConfig(
227                distance_m=_POINT_LINE_CONTAINMENT_BUFFER_M, buffer_from="boundary", inferred=False
228            )
229            result = _apply_buffer(geom, fallback_config)
230        else:
231            if isinstance(geometry, dict) and geometry_format == "geojson":
232                return geometry  # Unchanged reference: no round trip through shapely.
233            result = geom
234    elif relation.category == "buffer":
235        if buffer_config is None:
236            raise ValueError(f"Buffer relation '{relation.relation}' requires buffer_config")
237        result = _apply_buffer(geom, buffer_config)
238    elif relation.category == "directional":
239        if buffer_config is None:
240            raise ValueError(f"Directional relation '{relation.relation}' requires buffer_config")
241        relation_config = cfg.get_config(relation.relation)
242        direction = relation_config.direction_angle_degrees or 0
243        sector_angle = relation_config.sector_angle_degrees or 90
244        result = _apply_directional(geom, buffer_config, direction, sector_angle)
245    elif relation.category == "clipping":
246        relation_config = cfg.get_config(relation.relation)
247        clip_direction = relation_config.clip_direction or "north"
248        result = _apply_clipping(geom, clip_direction)
249    else:
250        raise ValueError(f"Unknown relation category: '{relation.category}'")
251
252    return format_geometry(result, geometry_format)

Transform one or more reference geometries according to a spatial relation.

A list of geometries is unioned into one before the transformation, so that features split across multiple datasource records (e.g. a river in segments) produce a single coherent search area.

When buffer_config.inferred is True (i.e. no explicit distance was stated) and the relation's config sets scale_with_area, the buffer distance is refined from the reference polygon's area so that small features receive small buffers and large regions receive large ones. Other relations, and point or line references, keep the default distance. The sized distance is written into buffer_config.distance_m in place, so the caller can read it back: pass a copy (buffer_config.model_copy()) when the config is shared or reused across calls.

Arguments:
  • geometry: Reference geometry in WGS84, or a non-empty list of them: a GeoJSON dict, a WKT or hex-encoded WKB string (as geometry_format returns), WKB bytes, or a shapely geometry.
  • relation: Spatial relation to apply.
  • buffer_config: Required for buffer/directional relations.
  • spatial_config: Relation registry; defaults to the module-level singleton.
  • geometry_format: "geojson" (default), "wkt", "wkb", or "shapely". Ask for "shapely" to write the area in more than one format, e.g. WKB for a query and GeoJSON for a response, without parsing it again.
Returns:

Transformed geometry in the requested format.

def convert_geometry( geometry: dict[str, typing.Any], fmt: Literal['geojson', 'wkt', 'wkb', 'shapely']) -> dict[str, typing.Any] | str | shapely.geometry.base.BaseGeometry:
58def convert_geometry(geometry: GeoJsonGeometry, fmt: GeometryFormat) -> GeoJsonGeometry | str | BaseGeometry:
59    """
60    Convert a GeoJSON geometry dict to the requested format.
61
62    Args:
63        geometry: GeoJSON geometry dict (e.g. {"type": "Point", "coordinates": [...]})
64        fmt: Target format — "geojson" returns the dict unchanged, "wkt" returns a WKT string,
65             "wkb" returns a hex-encoded WKB string, "shapely" a shapely geometry.
66
67    Returns:
68        The geometry in the requested format.
69    """
70    if fmt == "geojson":
71        return geometry
72    return format_geometry(shape(geometry), fmt)

Convert a GeoJSON geometry dict to the requested format.

Arguments:
  • geometry: GeoJSON geometry dict (e.g. {"type": "Point", "coordinates": [...]})
  • fmt: Target format — "geojson" returns the dict unchanged, "wkt" returns a WKT string, "wkb" returns a hex-encoded WKB string, "shapely" a shapely geometry.
Returns:

The geometry in the requested format.

def convert_feature_geometry( feature: geojson.feature.Feature, fmt: Literal['geojson', 'wkt', 'wkb', 'shapely']) -> geojson.feature.Feature | dict:
75def convert_feature_geometry(feature: Feature, fmt: GeometryFormat) -> Feature | dict:
76    """
77    Return a copy of a GeoJSON Feature dict with its geometry converted to the requested format.
78
79    Args:
80        feature: GeoJSON Feature dict with a "geometry" key.
81        fmt: Target geometry format.
82
83    Returns:
84        A new dict identical to the input except the "geometry" value is converted.
85        Returns a Feature when fmt is "geojson"; a plain dict otherwise (geometry becomes a string,
86        or a shapely geometry for "shapely").
87    """
88    if fmt == "geojson":
89        return feature
90    return {**feature, "geometry": convert_geometry(feature["geometry"], fmt)}

Return a copy of a GeoJSON Feature dict with its geometry converted to the requested format.

Arguments:
  • feature: GeoJSON Feature dict with a "geometry" key.
  • fmt: Target geometry format.
Returns:

A new dict identical to the input except the "geometry" value is converted. Returns a Feature when fmt is "geojson"; a plain dict otherwise (geometry becomes a string, or a shapely geometry for "shapely").