Metadata-Version: 2.4
Name: geofinder-icgc
Version: 3.0.0
Summary: Geocodificador asíncrono para Cataluña usando el servicio ICGC
Author-email: ICGC <qgis.openicgc@icgc.cat>, Goalnefesh <goalnefesh@protonmail.com>
Maintainer-email: Goalnefesh <goalnefesh@protonmail.com>
License: GPL-2.0-or-later
Project-URL: Homepage, https://github.com/jccamel/geofinder-icgc
Project-URL: Documentation, https://www.icgc.cat/es/Herramientas-y-visores/Herramientas/Geocodificador-ICGC
Project-URL: Repository, https://github.com/jccamel/geofinder-icgc
Project-URL: Original Project, https://github.com/OpenICGC/QgisPlugin
Project-URL: Issues, https://github.com/jccamel/geofinder-icgc/issues
Keywords: geocoding,catalonia,icgc,gis,coordinates,pelias,reverse-geocoding,async
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: AsyncIO
Classifier: Topic :: Scientific/Engineering :: GIS
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0
Requires-Dist: httpx>=0.27.0
Provides-Extra: gdal
Requires-Dist: GDAL>=3.0; extra == "gdal"
Provides-Extra: pyproj
Requires-Dist: pyproj>=3.0; extra == "pyproj"
Provides-Extra: all
Requires-Dist: pyproj>=3.0; extra == "all"
Dynamic: license-file

# <img src="assets/pics/geofinder-logo 192x192.jpg" alt="GeoFinder Logo" width="50" height="50"> GeoFinder-ICGC

> **Geocoder for Catalonia** using the ICGC service (Institut Cartogràfic i Geològic de Catalunya).
> Dual API: Native async + sync wrappers for simple scripts.

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: GPL-2.0](https://img.shields.io/badge/License-GPL--2.0-yellow.svg)](LICENSE)

---

**GeoFinder-ICGC** is an advanced geocoder for Catalonia designed to be robust, fast, and easy to use.

## Installation


```bash
# Basic installation
pip install geofinder-icgc

# With coordinate transformation support (recommended)
pip install geofinder-icgc[pyproj]
```

Since 3.0.0 this package is the library only. The MCP server for AI assistants lives in a
separate repository built on `mcp-secure-core` and uses this library as a dependency; until it is
released, pin `geofinder-icgc<3` if you need the server that was bundled up to 2.4.2.

## Quick Start

### Synchronous Usage (Simple scripts)
```python
from geofinder import GeoFinder

gf = GeoFinder()
results = gf.find_sync("Barcelona")

for r in results:
    print(f"{r.nom} ({r.nomTipus}) - {r.x}, {r.y}")
```

### Asynchronous Usage (High performance)
```python
import asyncio
from geofinder import GeoFinder

async def main():
    async with GeoFinder() as gf:
        results = await gf.find("Diagonal 100, Barcelona")
        print(f"Found: {len(results)}")

asyncio.run(main())
```

## Features Guide

### 1. General Search (`find` / `find_sync`)
Automatically detects the search type based on input:
- **Toponyms:** `"Montserrat"`, `"Girona"`
- **Addresses:** `"Carrer Aragó 50, Barcelona"`, `"Gran Via 123"`
- **Coordinates:** `"430000 4580000 EPSG:25831"`, `"2.17 41.38 EPSG:4326"`
- **Roads:** `"C-32 km 10"`
- **Rectangles:** `"X1 Y1 X2 Y2"`

Toponym results come municipality first, then other `topo1` places, `topo2` places and any other
layer, so `find("Barcelona")[0]` is the city. `size` is a maximum (`None` or `<= 0` means
`default_size`); coordinate and rectangle searches add their own `Coordenada`/`Rectangle` entry on
top of the `size` results from the ICGC. With space-separated numbers a comma is a decimal
separator (`"430000,5 4580000,5"` is a point), unless the text already uses `.` for decimals or a
comma has more digits after it than before; in those cases, and without spaces, it separates
numbers (`"430000,4580000"`, `"1,2,3,4"`, `"430000,4580000 431000,4581000"`,
`"2.1,41.3 2.2,41.4"`). An empty or blank text returns `[]` without calling the service.

### 2. Reverse Geocoding (`find_reverse` / `find_reverse_sync`)
Find places or addresses from coordinates.
```python
# Supports EPSG:25831 (default) and EPSG:4326 (GPS)
results = await gf.find_reverse(430000, 4580000)
```

### 3. Autocomplete (`autocomplete` / `autocomplete_sync`)
Ideal for implementing real-time search suggestions.
```python
suggestions = await gf.autocomplete("Barcel")
```

### 4. Proximity Search (`search_nearby`)
Find places within a given radius around a reference point.
```python
# Search everything within 2km of Sagrada Família
nearby = await gf.search_nearby("Sagrada Família, Barcelona", radius_km=2.0)
```

### 5. Batch Processing (`find_batch` / `find_reverse_batch`)
Execute multiple queries in parallel with optimized concurrency.
```python
queries = ["Barcelona", "Girona", "Lleida", "Tarragona"]
batch_results = await gf.find_batch(queries, max_concurrency=10)
```

### 6. Response with Metadata (`find_response`)
Returns a `GeoResponse` object that includes results and performance metadata such as execution time.

### 7. Query Classification (`parse_query`)
Find out how a text will be searched before running the search. `find()` uses this same parser,
so the answer always matches what `find()` does.
```python
from geofinder import parse_query

q = parse_query("C-32 km 10")
q.kind, q.road, q.km                     # ('road', 'C-32', '10')
parse_query("430000 4580000").epsg       # 25831 (default_epsg), epsg_explicit=False
parse_query("Barcelona, Diagonal 100")   # AddressQuery(municipality='Barcelona', ...)
```
`kind` is one of `rectangle`, `coordinate`, `road`, `address` or `placename`; each kind is its own
frozen model (`RectangleQuery`, `CoordinateQuery`, `RoadQuery`, `AddressQuery`, `PlacenameQuery`).

## Configuration

The `GeoFinder` constructor allows customizing the library behavior:

| Parameter | Type | Description |
| --------- | ---- | ----------- |
| `timeout` | `int` | Maximum wait time (default: 5s). |
| `cache_size` | `int` | LRU cache capacity (default: 128). |
| `cache_ttl` | `int` | Cache time-to-live in seconds (default: 3600). |
| `max_retries` | `int` | Number of retries on failure (default: 3). |
| `verify_ssl` | `bool` | Verify SSL certificates (default: True). |
| `http_client` | `httpx.AsyncClient` | Share your own httpx client (not closed by GeoFinder). |
| `transport` | `HTTPTransport` | Send every request through your own transport (see below). Not combinable with `http_client`. |
| `total_timeout` | `float` | Time budget in seconds for each public call, all requests and retries included (default: none). |

### Custom HTTP transport

GeoFinder never needs to talk to `httpx` directly: every request is a GET to a full URL sent
through an `HTTPTransport`. The default is `HttpxTransport`. To use your own network client
(for example one with an egress allow-list), write a small adapter and inject it:

```python
from geofinder import (
    GeoFinder, ServiceConnectionError, ServiceHTTPError, ServiceTimeoutError, TransportResponse,
)

class MyTransport:
    def __init__(self, http):
        self._http = http

    async def get(self, url: str, *, timeout: float) -> TransportResponse:
        try:
            body = await self._http.fetch_text(url, timeout=timeout)
        except MyTimeout as e:
            raise ServiceTimeoutError(str(e), url=url) from e       # retried
        except MyNetworkError as e:
            raise ServiceConnectionError(str(e), url=url) from e    # retried
        except MyStatusError as e:
            raise ServiceHTTPError(str(e), url=url, status_code=e.status) from e  # 5xx retried
        return TransportResponse(200, body, url)

gf = GeoFinder(transport=MyTransport(client), total_timeout=8, max_retries=1)
```

The library still builds the URL, checks the status code, parses the JSON, validates the
response and retries. Any other exception raised by the transport is not retried and reaches
you as a `ServiceError`. GeoFinder never closes an injected transport.

> **Note:** most async HTTP clients (httpx included) are bound to the event loop they first ran
> in. Each `*_sync` call runs its own loop, so a client you inject through `http_client=` or a
> transport should be used from async code (`await gf.find(...)`), not shared across several
> `*_sync` calls.

`total_timeout` covers the whole public call: `search_nearby`, which chains several requests,
or a coordinate search, which runs two in parallel, share a single budget. In batches, queries
that do not finish in time fail like any other query error and the rest keep their results.


---

## Documentation

- [COOKBOOK.md](COOKBOOK.md) - Tutorials and practical examples
- [README-DEV.md](README-DEV.md) - Development guide
- [README-ARQ.md](README-ARQ.md) - Technical architecture

---

## Resources

- [ICGC Documentation](https://www.icgc.cat/es/Herramientas-y-visores/Herramientas/Geocodificador-ICGC)
- [GitHub Repository](https://github.com/jccamel/geofinder-icgc)
- [Issues](https://github.com/jccamel/geofinder-icgc/issues)

---


## License

Distributed under the **GPL-2.0-or-later** license. Based on the original ICGC work adapted for standalone use.

---
© 2025 ICGC / Adapted by Goalnefesh

Small changes are powerful
