dataeuropa 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dataeuropa/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """dataeuropa: access the data.europa.eu open data portal (Search API, Registry, SPARQL)."""
2
+ from .client import (SEARCH_URL, REPO_URL, SPARQL_URL, cache_off, cache_on, catalogues, clear_cache, count, distributions, download,
3
+ facet_values, fetch_datasets, get_dataset, get_rdf, iter_datasets, load_distribution, load_geodata, pick_lang,
4
+ search, search_datasets, sparql, summarise_dataset)
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["search", "search_datasets", "iter_datasets", "fetch_datasets", "get_dataset", "distributions",
8
+ "download", "load_distribution", "load_geodata", "facet_values", "count", "catalogues", "get_rdf", "sparql", "pick_lang",
9
+ "summarise_dataset", "cache_on", "cache_off", "clear_cache"]
dataeuropa/client.py ADDED
@@ -0,0 +1,1162 @@
1
+ """Client for the data.europa.eu Search API, Registry API and SPARQL endpoint."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from typing import Any, Iterator, Sequence
7
+
8
+ import requests
9
+ from requests.adapters import HTTPAdapter
10
+ from urllib3.util.retry import Retry
11
+
12
+ SEARCH_URL = "https://data.europa.eu/api/hub/search"
13
+ REPO_URL = "https://data.europa.eu/api/hub/repo"
14
+ SPARQL_URL = "https://data.europa.eu/sparql"
15
+
16
+ # Friendly keyword -> facet id used by the Search API.
17
+ _FACET_ALIASES = {
18
+ "country": "country",
19
+ "catalog": "catalog",
20
+ "catalogue": "catalog",
21
+ "format": "format",
22
+ "license": "license",
23
+ "licence": "license",
24
+ "category": "categories",
25
+ "categories": "categories",
26
+ "publisher": "publisher",
27
+ "keyword": "keywords",
28
+ "keywords": "keywords",
29
+ "hvd": "is_hvd",
30
+ "source_type": "source_type",
31
+ "super_catalog": "superCatalog",
32
+ }
33
+
34
+ _session: requests.Session | None = None
35
+
36
+
37
+ def _get_session() -> requests.Session:
38
+ global _session
39
+ if _session is None:
40
+ s = requests.Session()
41
+ retry = Retry(total=4, backoff_factor=0.8, status_forcelist=(429, 500, 502, 503, 504),
42
+ allowed_methods=("GET", "POST"))
43
+ s.mount("https://", HTTPAdapter(max_retries=retry))
44
+ s.headers["User-Agent"] = "dataeuropa-python/0.1 (+https://data.europa.eu)"
45
+ _session = s
46
+ return _session
47
+
48
+
49
+ def _timeout() -> float:
50
+ return float(os.environ.get("DATAEUROPA_TIMEOUT", "60"))
51
+
52
+
53
+ # ---------------------------------------------------------------- response cache
54
+
55
+ # Set by cache_on() / cache_off(); None means "use the environment variable".
56
+ _cache_settings: dict[str, Any] = {"on": None, "dir": None, "ttl": None}
57
+ _CACHE_TTL_DEFAULT = 86400 # one day, in seconds
58
+
59
+
60
+ def _default_cache_dir() -> str:
61
+ """The operating system's cache folder for dataeuropa."""
62
+ import sys
63
+
64
+ if sys.platform == "win32":
65
+ base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~/AppData/Local")
66
+ return os.path.join(base, "dataeuropa", "cache")
67
+ if sys.platform == "darwin":
68
+ return os.path.expanduser("~/Library/Caches/dataeuropa")
69
+ return os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "dataeuropa")
70
+
71
+
72
+ def _cache_enabled() -> bool:
73
+ if _cache_settings["on"] is not None:
74
+ return _cache_settings["on"]
75
+ return os.environ.get("DATAEUROPA_CACHE", "").strip().lower() in ("1", "true", "yes")
76
+
77
+
78
+ def _cache_dir() -> str:
79
+ return _cache_settings["dir"] or os.environ.get("DATAEUROPA_CACHE_DIR") or _default_cache_dir()
80
+
81
+
82
+ def _cache_ttl() -> float:
83
+ if _cache_settings["ttl"] is not None:
84
+ return float(_cache_settings["ttl"])
85
+ return float(os.environ.get("DATAEUROPA_CACHE_TTL") or _CACHE_TTL_DEFAULT)
86
+
87
+
88
+ def cache_on(dir: str | os.PathLike | None = None, ttl: float | None = None) -> str:
89
+ """Turn on the on-disk response cache for this session. Returns the cache folder.
90
+
91
+ Cached: dataset records (:func:`get_dataset`, :func:`distributions`), the catalogue list
92
+ (:func:`catalogues`), and searches with ``limit=0`` (:func:`facet_values`, :func:`count`).
93
+ Other searches, SPARQL and file downloads are never cached.
94
+
95
+ ``dir`` defaults to ``DATAEUROPA_CACHE_DIR``, else the operating system's cache folder.
96
+ ``ttl`` is how long a response stays valid, in seconds; it defaults to
97
+ ``DATAEUROPA_CACHE_TTL``, else one day. The cache is off unless this is called or
98
+ ``DATAEUROPA_CACHE=1`` is set.
99
+ """
100
+ _cache_settings.update(on=True, dir=str(dir) if dir is not None else None, ttl=ttl)
101
+ path = _cache_dir()
102
+ os.makedirs(path, exist_ok=True)
103
+ return path
104
+
105
+
106
+ def cache_off() -> None:
107
+ """Turn off the response cache for this session (cached files stay; see :func:`clear_cache`)."""
108
+ _cache_settings["on"] = False
109
+
110
+
111
+ def clear_cache() -> int:
112
+ """Delete all cached responses. Returns how many were deleted."""
113
+ import re
114
+
115
+ path = _cache_dir()
116
+ if not os.path.isdir(path):
117
+ return 0
118
+ n = 0
119
+ for name in os.listdir(path):
120
+ if re.fullmatch(r"[0-9a-f]{64}\.json", name):
121
+ os.remove(os.path.join(path, name))
122
+ n += 1
123
+ return n
124
+
125
+
126
+ def _cache_key(url: str, params: dict | None = None) -> str:
127
+ """File name of a cached response: SHA-256 of the URL and its sorted query parameters."""
128
+ import hashlib
129
+
130
+ query = "&".join(f"{k}={params[k]}" for k in sorted(params)) if params else ""
131
+ return hashlib.sha256(f"{url}?{query}".encode("utf-8")).hexdigest() + ".json"
132
+
133
+
134
+ def _get_json(url: str, params: dict | None = None, *, cacheable: bool = False) -> Any:
135
+ """GET a JSON response, from the cache when it is on, ``cacheable`` and fresh."""
136
+ import time
137
+
138
+ path = os.path.join(_cache_dir(), _cache_key(url, params)) if cacheable and _cache_enabled() else None
139
+ ttl = _cache_ttl() # ttl 0: never fresh, even when the file time is a little ahead of the clock
140
+ if path and ttl > 0 and os.path.isfile(path) and time.time() - os.path.getmtime(path) < ttl:
141
+ with open(path, "rb") as fh:
142
+ return json.loads(fh.read())
143
+ r = _get_session().get(url, params=params, timeout=_timeout())
144
+ _raise(r)
145
+ data = r.json()
146
+ if path:
147
+ os.makedirs(os.path.dirname(path), exist_ok=True)
148
+ tmp = f"{path}.{os.getpid()}.tmp" # write, then rename, so readers never see half a file
149
+ with open(tmp, "wb") as fh:
150
+ fh.write(r.content)
151
+ os.replace(tmp, path)
152
+ return data
153
+
154
+
155
+ def pick_lang(value: Any, lang: str = "en") -> str | None:
156
+ """Collapse a ``{lang: text}`` mapping to one string (lang, then en, then any)."""
157
+ if value is None:
158
+ return None
159
+ if isinstance(value, str):
160
+ return value
161
+ if isinstance(value, dict):
162
+ for k in (lang, "en"):
163
+ if value.get(k):
164
+ return value[k]
165
+ for v in value.values():
166
+ if v:
167
+ return v
168
+ return None
169
+ if isinstance(value, list):
170
+ return pick_lang(value[0], lang) if value else None
171
+ return str(value)
172
+
173
+
174
+ def _build_facets(facets: dict | None, **named: Any) -> dict | None:
175
+ out: dict[str, list[str]] = {k: list(v) for k, v in (facets or {}).items()}
176
+ for key, val in named.items():
177
+ if val is None:
178
+ continue
179
+ fid = _FACET_ALIASES[key]
180
+ if isinstance(val, bool):
181
+ vals = ["true" if val else "false"]
182
+ elif isinstance(val, str):
183
+ vals = [val.lower() if fid == "country" else val]
184
+ else:
185
+ vals = [str(v).lower() if fid == "country" else str(v) for v in val]
186
+ out.setdefault(fid, []).extend(vals)
187
+ return out or None
188
+
189
+
190
+ def _bbox_params(bbox: Sequence[float]) -> dict:
191
+ """Check ``(min_lon, min_lat, max_lon, max_lat)`` and return the Search API parameters.
192
+
193
+ The API ignores an incomplete box and rejects min > max with an unhelpful 400, so check here.
194
+ """
195
+ try:
196
+ vals = [float(v) for v in bbox]
197
+ except (TypeError, ValueError):
198
+ raise ValueError("bbox must be 4 numbers: (min_lon, min_lat, max_lon, max_lat)") from None
199
+ if len(vals) != 4:
200
+ raise ValueError("bbox must be 4 numbers: (min_lon, min_lat, max_lon, max_lat)")
201
+ min_lon, min_lat, max_lon, max_lat = vals
202
+ if not (-180 <= min_lon <= max_lon <= 180):
203
+ raise ValueError("bbox longitudes must satisfy -180 <= min_lon <= max_lon <= 180")
204
+ if not (-90 <= min_lat <= max_lat <= 90):
205
+ raise ValueError("bbox latitudes must satisfy -90 <= min_lat <= max_lat <= 90")
206
+ return dict(zip(("bboxMinLon", "bboxMinLat", "bboxMaxLon", "bboxMaxLat"), vals))
207
+
208
+
209
+ def search(q: str | None = None, *, filters: str | Sequence[str] = "dataset",
210
+ facets: dict | None = None, limit: int = 10, page: int = 0,
211
+ sort: str | Sequence[str] | None = None, country: str | Sequence[str] | None = None,
212
+ catalog: str | Sequence[str] | None = None, format: str | Sequence[str] | None = None,
213
+ license: str | Sequence[str] | None = None, category: str | Sequence[str] | None = None,
214
+ publisher: str | Sequence[str] | None = None, keywords: str | Sequence[str] | None = None,
215
+ hvd: bool | None = None, min_date: str | None = None, max_date: str | None = None,
216
+ date_type: str | None = None, bbox: Sequence[float] | None = None,
217
+ aggregation: bool = False, extra: dict | None = None) -> dict:
218
+ """Raw Search API call. Returns the ``result`` object: ``count``, ``results``, ``facets``...
219
+
220
+ ``country`` takes ISO-2 codes (``"pt"``); ``format`` takes ids such as ``"CSV"``;
221
+ ``category`` takes DCAT-AP theme codes (``"ENVI"``). Use :func:`facet_values` to discover ids.
222
+ ``sort`` is e.g. ``"modified+desc"``.
223
+
224
+ ``bbox`` is ``(min_lon, min_lat, max_lon, max_lat)`` in WGS84 degrees. A dataset matches when
225
+ its spatial extent overlaps the box, so datasets covering all of Europe or the world match any
226
+ box. Datasets without a spatial extent (about half the portal) never match.
227
+
228
+ With ``limit=0`` the result can come from the response cache (see :func:`cache_on`).
229
+ """
230
+ params: dict[str, Any] = {"limit": limit, "page": page, "aggregation": str(aggregation).lower()}
231
+ if q:
232
+ params["q"] = q
233
+ if filters:
234
+ params["filters"] = filters if isinstance(filters, str) else ",".join(filters)
235
+ fac = _build_facets(facets, country=country, catalog=catalog, format=format, license=license,
236
+ category=category, publisher=publisher, keywords=keywords, hvd=hvd)
237
+ if fac:
238
+ params["facets"] = json.dumps(fac, separators=(",", ":"))
239
+ if sort:
240
+ params["sort"] = sort if isinstance(sort, str) else ",".join(sort)
241
+ if min_date:
242
+ params["minDate"] = min_date
243
+ if max_date:
244
+ params["maxDate"] = max_date
245
+ if date_type:
246
+ params["dateType"] = date_type
247
+ if bbox is not None:
248
+ params.update(_bbox_params(bbox))
249
+ params.update(extra or {})
250
+ # limit=0 (facet counts, hit counts) carries no records, so it may come from the cache.
251
+ return _get_json(f"{SEARCH_URL}/search", params, cacheable=limit == 0)["result"]
252
+
253
+
254
+ def _raise(r: requests.Response) -> None:
255
+ if r.status_code >= 400:
256
+ try:
257
+ msg = r.json().get("message", r.text[:300])
258
+ except Exception:
259
+ msg = r.text[:300]
260
+ raise requests.HTTPError(f"{r.status_code} from {r.url}: {msg}", response=r)
261
+
262
+
263
+ def summarise_dataset(d: dict, lang: str = "en") -> dict:
264
+ """Flatten one dataset record to the fields people usually want."""
265
+ dists = d.get("distributions") or []
266
+ fmts = sorted({(x.get("format") or {}).get("id") for x in dists if (x.get("format") or {}).get("id")})
267
+ cat = d.get("catalog") or {}
268
+ lp = d.get("landing_page") or []
269
+ return {
270
+ "id": d.get("id"),
271
+ "title": pick_lang(d.get("title"), lang),
272
+ "description": pick_lang(d.get("description"), lang),
273
+ "country": (d.get("country") or {}).get("id"),
274
+ "catalog": cat.get("id"),
275
+ "publisher": (d.get("publisher") or {}).get("name"),
276
+ "issued": d.get("issued"),
277
+ "modified": d.get("modified"),
278
+ "formats": fmts,
279
+ "n_distributions": len(dists),
280
+ "is_hvd": d.get("is_hvd"),
281
+ "quality_score": (d.get("quality_meas") or {}).get("scoring"),
282
+ "landing_page": (lp[0].get("resource") if lp and isinstance(lp[0], dict) else None),
283
+ "portal_url": f"https://data.europa.eu/data/datasets/{d.get('id')}",
284
+ }
285
+
286
+
287
+ def search_datasets(q: str | None = None, *, lang: str = "en", as_dataframe: bool = True, **kw):
288
+ """Search datasets and return a table (pandas DataFrame if available, else list of dicts).
289
+
290
+ Accepts all keyword arguments of :func:`search`. ``count`` (total hits) is stored in
291
+ ``df.attrs["count"]`` for DataFrames.
292
+ """
293
+ res = search(q, **kw)
294
+ rows = [summarise_dataset(d, lang) for d in res["results"]]
295
+ return _tabulate(rows, as_dataframe, count=res["count"])
296
+
297
+
298
+ def _tabulate(rows: list[dict], as_dataframe: bool, **attrs):
299
+ if as_dataframe:
300
+ try:
301
+ import pandas as pd
302
+ except ImportError:
303
+ return rows
304
+ df = pd.DataFrame(rows)
305
+ df.attrs.update(attrs)
306
+ return df
307
+ return rows
308
+
309
+
310
+ def iter_datasets(q: str | None = None, *, max_results: int | None = None, page_size: int = 500,
311
+ **kw) -> Iterator[dict]:
312
+ """Yield *raw* dataset records for an arbitrarily large result set using scroll."""
313
+ kw.pop("limit", None)
314
+ kw.pop("page", None)
315
+ extra = dict(kw.pop("extra", None) or {})
316
+ extra["scroll"] = "true"
317
+ res = search(q, limit=min(page_size, 1000), extra=extra, **kw)
318
+ n = 0
319
+ while True:
320
+ for d in res["results"]:
321
+ yield d
322
+ n += 1
323
+ if max_results and n >= max_results:
324
+ return
325
+ sid = res.get("scrollId")
326
+ if not res["results"] or not sid:
327
+ return
328
+ r = _get_session().get(f"{SEARCH_URL}/scroll", params={"scrollId": sid}, timeout=_timeout())
329
+ _raise(r)
330
+ res = r.json()["result"]
331
+
332
+
333
+ def fetch_datasets(q: str | None = None, *, max_results: int = 1000, lang: str = "en",
334
+ as_dataframe: bool = True, **kw):
335
+ """Collect up to ``max_results`` datasets (via scroll) into a table."""
336
+ rows = [summarise_dataset(d, lang) for d in iter_datasets(q, max_results=max_results, **kw)]
337
+ return _tabulate(rows, as_dataframe)
338
+
339
+
340
+ def get_dataset(dataset_id: str, *, raw: bool = False, lang: str = "en") -> dict:
341
+ """Full metadata record for one dataset (id as shown in search results)."""
342
+ d = _get_json(f"{SEARCH_URL}/datasets/{dataset_id}", cacheable=True)["result"]
343
+ return d if raw else {**summarise_dataset(d, lang), "keywords": _keywords(d, lang), "raw": d}
344
+
345
+
346
+ def _keywords(d: dict, lang: str = "en") -> list:
347
+ """Keyword labels in ``lang``, plus those with no language tag."""
348
+ return [k.get("label") for k in d.get("keywords") or [] if k.get("language") in (lang, None)]
349
+
350
+
351
+ def distributions(dataset_id: str, *, lang: str = "en", files_only: bool = False, as_dataframe: bool = True):
352
+ """Distributions (files, services, pages) of a dataset as a table, one row each.
353
+
354
+ The ``kind`` column says what each one is: ``"file"``, ``"service"`` (WMS, WFS, APIs, feeds),
355
+ ``"page"`` (a web page), ``"none"`` (no usable URL, e.g. a localhost placeholder) or
356
+ ``"unknown"``. ``files_only=True`` keeps only files.
357
+ """
358
+ rows = _distribution_rows(get_dataset(dataset_id, raw=True), lang)
359
+ if files_only:
360
+ rows = [r for r in rows if r["kind"] == "file"]
361
+ return _tabulate(rows, as_dataframe)
362
+
363
+
364
+ def _distribution_rows(d: dict, lang: str = "en") -> list[dict]:
365
+ """One row per distribution of a raw dataset record; ``url`` is the download URL, else the access URL."""
366
+ rows = []
367
+ for x in d.get("distributions") or []:
368
+ acc = x.get("access_url") or []
369
+ dl = x.get("download_url") or []
370
+ cs_algo, cs_value = _checksum(x.get("checksum"))
371
+ rows.append({
372
+ "id": x.get("id"),
373
+ "title": pick_lang(x.get("title"), lang),
374
+ "format": (x.get("format") or {}).get("id"),
375
+ "media_type": x.get("media_type"),
376
+ "byte_size": x.get("byte_size"),
377
+ "checksum": cs_value,
378
+ "checksum_algorithm": cs_algo,
379
+ "license": (x.get("license") or {}).get("id"),
380
+ "modified": x.get("modified"),
381
+ "download_url": dl[0] if dl else None,
382
+ "access_url": acc[0] if acc else None,
383
+ "url": (dl[0] if dl else (acc[0] if acc else None)),
384
+ "kind": _distribution_kind((x.get("format") or {}).get("id"), x.get("media_type"),
385
+ dl[0] if dl else (acc[0] if acc else None), dl[0] if dl else None),
386
+ })
387
+ return rows
388
+
389
+
390
+ # Hash algorithms that downloads can be checked with. The portal also has a few others (e.g. CRC).
391
+ _HASHES = ("md5", "sha1", "sha256")
392
+ # Hash lengths in hex digits, for checksums that do not name their algorithm.
393
+ _HASH_BY_LENGTH = {32: "md5", 40: "sha1", 64: "sha256"}
394
+
395
+
396
+ def _checksum(cs: Any) -> tuple[str | None, str | None]:
397
+ """``(algorithm, value)`` of a distribution's ``checksum`` field, both lowercase, or ``(None, None)``.
398
+
399
+ The algorithm is normalised (``"SHA-256"`` and SPDX's ``"...checksumAlgorithm_sha256"`` become
400
+ ``"sha256"``). When it is not given, a hex value of 32, 40 or 64 digits counts as MD5, SHA-1 or
401
+ SHA-256; otherwise the algorithm is None.
402
+ """
403
+ if not isinstance(cs, dict) or not isinstance(cs.get("checksum_value"), str) or not cs["checksum_value"].strip():
404
+ return None, None
405
+ value = cs["checksum_value"].strip().lower()
406
+ algo = cs.get("algorithm")
407
+ if isinstance(algo, str) and algo.strip():
408
+ algo = algo.strip().lower().rsplit("checksumalgorithm_", 1)[-1].replace("-", "").replace("_", "")
409
+ elif all(c in "0123456789abcdef" for c in value):
410
+ algo = _HASH_BY_LENGTH.get(len(value))
411
+ else:
412
+ algo = None
413
+ return algo, value
414
+
415
+
416
+ def _file_hash(path: str | os.PathLike, algorithm: str) -> str:
417
+ """Lowercase hex digest of a file with ``algorithm`` (``"md5"``, ``"sha1"`` or ``"sha256"``)."""
418
+ import hashlib
419
+
420
+ h = hashlib.new(algorithm)
421
+ with open(path, "rb") as fh:
422
+ for part in iter(lambda: fh.read(1 << 20), b""):
423
+ h.update(part)
424
+ return h.hexdigest()
425
+
426
+
427
+ def _verify_checksum(path: str | os.PathLike, algorithm: str | None, value: str | None) -> bool:
428
+ """Check a downloaded file against its checksum. Returns True if checked, False if there was
429
+ nothing to check with (no checksum, or an algorithm other than MD5, SHA-1, SHA-256). On a
430
+ mismatch, deletes the file and raises ``ValueError``."""
431
+ if not isinstance(algorithm, str) or algorithm not in _HASHES or not isinstance(value, str) or not value:
432
+ return False
433
+ got = _file_hash(path, algorithm)
434
+ if got != value.lower():
435
+ os.remove(path)
436
+ raise ValueError(f"checksum mismatch: expected {algorithm} {value.lower()}, got {got}; "
437
+ f"the file was deleted (pass verify=False to keep it)")
438
+ return True
439
+
440
+
441
+ def _range_validator(etag: str | None, last_modified: str | None) -> str | None:
442
+ """The value to send as ``If-Range`` when resuming: a strong ETag, else Last-Modified, else None.
443
+ Weak ETags (``W/"..."``) are not allowed in ``If-Range``."""
444
+ if isinstance(etag, str) and etag.strip() and not etag.strip().startswith("W/"):
445
+ return etag.strip()
446
+ if isinstance(last_modified, str) and last_modified.strip():
447
+ return last_modified.strip()
448
+ return None
449
+
450
+
451
+ def _resume_action(status: int, content_range: str | None, offset: int) -> str:
452
+ """What to do with the reply to a request for bytes ``offset``- of a partial download:
453
+ ``"append"`` (206 from ``offset``), ``"replace"`` (200: the whole file, because the server
454
+ ignores ranges or the file changed), ``"restart"`` (416, or a 206 for other bytes: start again
455
+ without a range) or ``"error"``."""
456
+ import re
457
+
458
+ if status == 206:
459
+ m = re.match(r"\s*bytes\s+(\d+)-", content_range or "", re.IGNORECASE)
460
+ return "append" if m and int(m.group(1)) == offset else "restart"
461
+ if status == 200:
462
+ return "replace"
463
+ if status == 416:
464
+ return "restart"
465
+ return "error"
466
+
467
+
468
+ class _TooLarge(ValueError):
469
+ """A download went over its size limit; the partial file was deleted."""
470
+
471
+
472
+ def _fetch(url: str, part: str, *, resume: bool, chunk: int, max_bytes: int | None = None) -> requests.Response:
473
+ """Stream ``url`` into the partial file ``part``, continuing an earlier partial download when
474
+ possible. Returns the (closed) response, for its headers and final URL. Over ``max_bytes``
475
+ (announced or received), deletes the partial file and raises ``_TooLarge``."""
476
+ meta = part + ".json"
477
+ offset = 0
478
+ headers = {"Accept-Encoding": "identity"} # byte offsets must refer to the file itself
479
+ if resume and os.path.isfile(part) and os.path.isfile(meta):
480
+ try:
481
+ with open(meta, encoding="utf-8") as fh:
482
+ m = json.load(fh)
483
+ except (OSError, ValueError):
484
+ m = {}
485
+ if m.get("url") == url and m.get("validator") and os.path.getsize(part) > 0:
486
+ offset = os.path.getsize(part)
487
+ headers.update({"Range": f"bytes={offset}-", "If-Range": m["validator"]})
488
+ if offset == 0:
489
+ for f in (part, meta):
490
+ if os.path.exists(f):
491
+ os.remove(f)
492
+ r = _get_session().get(url, stream=True, timeout=_timeout(), allow_redirects=True, headers=headers)
493
+ action = _resume_action(r.status_code, r.headers.get("content-range"), offset) if offset else "replace"
494
+ if action == "restart":
495
+ r.close()
496
+ for f in (part, meta):
497
+ if os.path.exists(f):
498
+ os.remove(f)
499
+ return _fetch(url, part, resume=False, chunk=chunk, max_bytes=max_bytes)
500
+ _raise(r)
501
+ start = offset if action == "append" else 0
502
+
503
+ def too_large():
504
+ r.close()
505
+ for f in (part, meta):
506
+ if os.path.exists(f):
507
+ os.remove(f)
508
+ return _TooLarge(f"{url} is larger than the limit of {max_bytes:,} bytes; the download was stopped")
509
+
510
+ announced = r.headers.get("content-length", "")
511
+ if max_bytes is not None and announced.isdigit() and start + int(announced) > max_bytes:
512
+ raise too_large()
513
+ if action == "replace":
514
+ validator = _range_validator(r.headers.get("etag"), r.headers.get("last-modified"))
515
+ if validator:
516
+ with open(meta, "w", encoding="utf-8") as fh:
517
+ json.dump({"url": url, "validator": validator}, fh)
518
+ elif os.path.exists(meta):
519
+ os.remove(meta)
520
+ size = start
521
+ with open(part, "ab" if action == "append" else "wb") as fh:
522
+ for piece in r.iter_content(chunk):
523
+ size += len(piece)
524
+ if max_bytes is not None and size > max_bytes:
525
+ fh.close()
526
+ raise too_large()
527
+ fh.write(piece)
528
+ r.close()
529
+ if os.path.exists(meta):
530
+ os.remove(meta)
531
+ return r
532
+
533
+
534
+ def download(url_or_row: str | dict, dest: str | os.PathLike | None = None, *, chunk: int = 1 << 20,
535
+ verify: bool = True, resume: bool = True, max_bytes: int | None = None) -> str:
536
+ """Download a distribution to ``dest`` (file or directory). Returns the local path.
537
+
538
+ Accepts a URL, or a row/dict from :func:`distributions` (uses its ``url``). Streams to disk.
539
+
540
+ If the row has a checksum (``checksum`` and ``checksum_algorithm``; MD5, SHA-1 or SHA-256), the
541
+ file is checked against it. On a mismatch the file is deleted and ``ValueError`` is raised;
542
+ ``verify=False`` skips the check. ``byte_size`` is not checked: on the portal it is often a
543
+ placeholder (0, 1, 1024).
544
+
545
+ The file is written as ``<file>.part`` and renamed when complete. If a download is interrupted,
546
+ calling ``download`` again for the same URL and destination continues where it stopped, when
547
+ the server supports ranges and identifies the file (ETag or Last-Modified); a file that changed
548
+ meanwhile is downloaded again from the start. ``resume=False`` always starts from the start.
549
+
550
+ ``max_bytes`` stops a download that is (or is announced as) larger, deletes the partial file
551
+ and raises ``ValueError``. Default: no limit.
552
+ """
553
+ from urllib.parse import urlparse, unquote
554
+
555
+ url = url_or_row if isinstance(url_or_row, str) else url_or_row.get("url")
556
+ if not url:
557
+ raise ValueError("no URL available for this distribution")
558
+ folder = None if dest is not None and not os.path.isdir(dest) else (str(dest) if dest is not None else "")
559
+ guess = unquote(os.path.basename(urlparse(url).path)) or "download"
560
+ part = (os.path.join(folder, guess) if folder is not None else str(dest)) + ".part"
561
+ r = _fetch(url, part, resume=resume, chunk=chunk, max_bytes=max_bytes)
562
+ if folder is None:
563
+ path = str(dest)
564
+ else:
565
+ name = None
566
+ cd = r.headers.get("content-disposition", "")
567
+ if "filename=" in cd:
568
+ name = cd.split("filename=")[-1].strip("\"' ;")
569
+ name = name or unquote(os.path.basename(urlparse(r.url).path)) or "download"
570
+ path = os.path.join(folder, name)
571
+ os.replace(part, path)
572
+ if verify and not isinstance(url_or_row, str):
573
+ _verify_checksum(path, url_or_row.get("checksum_algorithm"), url_or_row.get("checksum"))
574
+ return path
575
+
576
+
577
+ # ---------------------------------------------------------------- load into a table
578
+
579
+ # Format ids, media types and file extensions that map to a readable file format. Keys are
580
+ # matched after _format_key(): lowercase, look-alike letters folded, leading dot removed.
581
+ _FILE_FORMATS = {
582
+ "csv": "csv", "text/csv": "csv", "csv/utf8": "csv", "comma separated value (csv)": "csv",
583
+ "tsv": "csv", "text/tab-separated-values": "csv", # the CSV reader detects the tab delimiter
584
+ "json": "json", "application/json": "json",
585
+ "xlsx": "xlsx", "xlsm": "xlsx", "excel (.xlsx)": "xlsx",
586
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
587
+ "vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
588
+ "parquet": "parquet", "application/vnd.apache.parquet": "parquet", "application/x-parquet": "parquet",
589
+ }
590
+ # Media types and extensions of compressed archives, which must be unpacked before reading.
591
+ _ARCHIVES = {"application/zip", "application/x-zip-compressed", "application/gzip", "application/x-gzip",
592
+ "application/x-tar", "zip", "gz", "tgz", "tar"}
593
+ # Format ids of services (map servers, APIs) rather than files. Ids ending in "_srvc" count too.
594
+ # Atom and RSS feeds count as services: in INSPIRE they list files rather than being one.
595
+ _SERVICE_FORMATS = {
596
+ "wms", "wfs", "wcs", "wmts", "ogc:wms", "ogc:wfs", "ogc:wcs", "ogc:wmts", "ogc:ows-c", "api", "open-api",
597
+ "ogc api features", "ogcapi-features", "ogcfeat", "arcgis geoservices rest api", "rest", "esri rest",
598
+ "application/vnd.ogc.wms_xml", "sparql", "sparqlq", "inspire download service", "atom", "rss",
599
+ "application/atom+xml", "application/rss+xml",
600
+ }
601
+ # Format ids and media types of web pages (landing pages, links, viewers) rather than files.
602
+ _PAGE_FORMATS = {
603
+ "html", "text/html", "application/xhtml+xml", "web page", "html_simpl", "www:link",
604
+ "www:link-1.0-http--link", "www:link-1.0-http--metadata-url", "url", "view", "doi", "map_prvw",
605
+ }
606
+ # Look-alike letters some publishers type in format ids (Cyrillic а е о р с х, both cases).
607
+ _LOOKALIKES = str.maketrans("\u0430\u0435\u043e\u0440\u0441\u0445\u0410\u0415\u041e\u0420\u0421\u0425",
608
+ "aeopcxAEOPCX")
609
+
610
+
611
+ def _format_key(value: str) -> str:
612
+ """A format id, media type or extension as matched against the tables above."""
613
+ key = value.strip().translate(_LOOKALIKES).lower()
614
+ if key.startswith("file:///"):
615
+ key = key.rsplit("/", 1)[-1]
616
+ return key.lstrip(".")
617
+
618
+
619
+ def _url_extension(url: str | None) -> str | None:
620
+ """The file extension of a URL's last path part, without query or fragment; None if none."""
621
+ if not isinstance(url, str) or not url:
622
+ return None
623
+ path = url.split("?", 1)[0].split("#", 1)[0].rstrip("/")
624
+ last = path.rsplit("/", 1)[-1]
625
+ return last.rsplit(".", 1)[-1] if "." in last else None
626
+
627
+
628
+ def _file_format(fmt: str | None = None, media_type: str | None = None, url: str | None = None) -> str | None:
629
+ """``"csv"``, ``"json"``, ``"xlsx"``, ``"parquet"``, ``"service"``, ``"archive"``, ``"page"`` or
630
+ None (unknown).
631
+
632
+ A compressed media type or file extension (ZIP, gzip, tar) means ``"archive"``, whatever the
633
+ format id says. Otherwise looks at the format id, then the media type, then the file
634
+ extension, and uses the first one it recognises as a service or a readable file. ``"page"``
635
+ (a web page) only when one of them says so and none names a service or a file.
636
+ """
637
+ ext = _url_extension(url)
638
+ for cand in (media_type, ext):
639
+ if isinstance(cand, str) and _format_key(cand) in _ARCHIVES:
640
+ return "archive"
641
+ keys = [_format_key(c) for c in (fmt, media_type, ext) if isinstance(c, str) and c.strip()]
642
+ for key in keys:
643
+ if key in _SERVICE_FORMATS or key.endswith("_srvc"):
644
+ return "service"
645
+ if key in _FILE_FORMATS:
646
+ return _FILE_FORMATS[key]
647
+ return "page" if any(k in _PAGE_FORMATS for k in keys) else None
648
+
649
+
650
+ # Format ids that say nothing about the content ("onLine" is ISO 19115 for "a link").
651
+ _NO_FORMAT = {"online", "other", "inconnu", "unknown", "n/a"}
652
+ # Hosts that only appear in placeholder URLs.
653
+ _PLACEHOLDER_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "::1", ""}
654
+
655
+
656
+ def _distribution_kind(fmt: str | None = None, media_type: str | None = None, url: str | None = None,
657
+ download_url: str | None = None) -> str:
658
+ """What a distribution is: ``"file"``, ``"service"``, ``"page"``, ``"none"`` (no usable URL) or
659
+ ``"unknown"``.
660
+
661
+ ``"none"``: no URL, a scheme other than http(s) or ftp, or a placeholder host (localhost).
662
+ ``"service"``: an OGC query in the URL (``service=WMS``, ``request=GetCapabilities``), or a
663
+ service format. ``"page"``: a web-page format, or no format and an ``.html`` URL. ``"file"``:
664
+ any other format or media type, or a download URL. Otherwise ``"unknown"``. Format ids that
665
+ say nothing (``onLine``, ``OTHER``) count as no format.
666
+ """
667
+ import re
668
+ from urllib.parse import urlparse
669
+
670
+ if not isinstance(url, str) or not url.strip():
671
+ return "none"
672
+ parts = urlparse(url.strip())
673
+ if parts.scheme.lower() not in ("http", "https", "ftp") or (parts.hostname or "").lower() in _PLACEHOLDER_HOSTS:
674
+ return "none"
675
+ if re.search(r"(^|&)(service=(wms|wfs|wcs|wmts|csw|wps|sos)|request=getcapabilities)(&|$)",
676
+ parts.query, re.IGNORECASE):
677
+ return "service"
678
+ f = _file_format(fmt, media_type, url)
679
+ if f in ("service", "page"):
680
+ return f
681
+ if f is not None or any(isinstance(v, str) and v.strip() and _format_key(v) not in _NO_FORMAT
682
+ for v in (fmt, media_type)):
683
+ return "file"
684
+ if (_url_extension(url) or "").lower() in ("html", "htm"):
685
+ return "page"
686
+ return "file" if isinstance(download_url, str) and download_url.strip() else "unknown"
687
+
688
+
689
+ def _check_payload(path: str | os.PathLike) -> None:
690
+ """Refuse a downloaded file that is an archive or an HTML page rather than data."""
691
+ with open(path, "rb") as fh:
692
+ head = fh.read(512)
693
+ if head.startswith(b"PK\x03\x04") or head.startswith(b"\x1f\x8b"):
694
+ raise ValueError("the download is a compressed archive (ZIP or gzip); use download() and unpack it")
695
+ start = head.lstrip(b"\xef\xbb\xbf \t\r\n").lower()
696
+ if start.startswith(b"<!doctype html") or start.startswith(b"<html"):
697
+ raise ValueError("the download is an HTML page, not a data file (often a landing page)")
698
+
699
+
700
+ def _decode(raw: bytes) -> str:
701
+ """UTF-8 (with or without a byte-order mark), falling back to Latin-1."""
702
+ if raw.startswith(b"\xef\xbb\xbf"):
703
+ raw = raw[3:]
704
+ try:
705
+ return raw.decode("utf-8")
706
+ except UnicodeDecodeError:
707
+ return raw.decode("latin-1")
708
+
709
+
710
+ def _sniff_delimiter(text: str) -> str:
711
+ """The most frequent of , ; tab | in the header line (comma on a tie or if none occurs)."""
712
+ header = text.split("\n", 1)[0]
713
+ counts = {d: header.count(d) for d in (",", ";", "\t", "|")}
714
+ best = max(counts.values())
715
+ if best == 0 or counts[","] == best:
716
+ return ","
717
+ return next(d for d in (";", "\t", "|") if counts[d] == best)
718
+
719
+
720
+ def _json_records(data: Any) -> list[dict]:
721
+ """An array of objects, or an object holding exactly one array of objects."""
722
+ if isinstance(data, list) and all(isinstance(r, dict) for r in data):
723
+ return data
724
+ if isinstance(data, dict):
725
+ lists = [v for v in data.values() if isinstance(v, list) and v and all(isinstance(r, dict) for r in v)]
726
+ if len(lists) == 1:
727
+ return lists[0]
728
+ raise ValueError("JSON is not a table: expected an array of objects, or an object holding one")
729
+
730
+
731
+ def _read_table(path: str | os.PathLike, fmt: str, sheet: str | int | None = None):
732
+ """Read a local file of format ``fmt`` into a pandas DataFrame."""
733
+ try:
734
+ import pandas as pd
735
+ except ImportError:
736
+ raise ImportError("load_distribution needs pandas: pip install 'dataeuropa[pandas]'") from None
737
+ if fmt == "csv":
738
+ import io
739
+ with open(path, "rb") as fh:
740
+ text = _decode(fh.read())
741
+ return pd.read_csv(io.StringIO(text), sep=_sniff_delimiter(text), keep_default_na=False, na_values=[""])
742
+ if fmt == "json":
743
+ with open(path, "rb") as fh:
744
+ records = _json_records(json.loads(_decode(fh.read())))
745
+ cols: list[str] = []
746
+ for r in records:
747
+ cols.extend(k for k in r if k not in cols)
748
+ return pd.DataFrame([[r.get(c) for c in cols] for r in records], columns=cols)
749
+ if fmt == "xlsx":
750
+ try:
751
+ import openpyxl # noqa: F401
752
+ except ImportError:
753
+ raise ImportError("reading XLSX needs openpyxl: pip install 'dataeuropa[xlsx]'") from None
754
+ return pd.read_excel(path, sheet_name=0 if sheet is None else sheet, engine="openpyxl")
755
+ if fmt == "parquet":
756
+ try:
757
+ import pyarrow # noqa: F401
758
+ except ImportError:
759
+ raise ImportError("reading Parquet needs pyarrow: pip install 'dataeuropa[parquet]'") from None
760
+ return pd.read_parquet(path, engine="pyarrow")
761
+ raise ValueError(f"unsupported format {fmt!r}")
762
+
763
+
764
+ def load_distribution(url_or_row: str | dict, *, format: str | None = None, sheet: str | int | None = None):
765
+ """Download a distribution and read it into a pandas DataFrame.
766
+
767
+ Accepts a URL, or a row/dict from :func:`distributions`. Reads CSV and JSON (needs pandas),
768
+ XLSX (needs openpyxl) and Parquet (needs pyarrow). The format comes from ``format`` if given
769
+ (``"csv"``, ``"json"``, ``"xlsx"``, ``"parquet"``), else from the row's format id, its media
770
+ type, then the URL's file extension. ``sheet`` picks an XLSX sheet by name or 0-based index
771
+ (default: the first).
772
+
773
+ CSV: the delimiter (``,`` ``;`` tab ``|``) is taken from the header line, text is read as
774
+ UTF-8 with a Latin-1 fallback, and only empty cells count as missing. JSON: an array of
775
+ objects, or an object holding exactly one such array; keys become columns.
776
+
777
+ Raises ``ValueError`` for services (WMS, WFS, APIs), compressed archives, HTML pages served
778
+ instead of data, formats it cannot tell or read, and files that fail their checksum (see
779
+ :func:`download`).
780
+ """
781
+ import tempfile
782
+
783
+ row = {"url": url_or_row} if isinstance(url_or_row, str) else url_or_row
784
+ url = row.get("url")
785
+ if not url:
786
+ raise ValueError("no URL available for this distribution")
787
+ if format is not None:
788
+ fmt = _file_format(format)
789
+ if fmt in (None, "service", "archive", "page"):
790
+ raise ValueError(f"format must be one of csv, json, xlsx, parquet (got {format!r})")
791
+ else:
792
+ fmt = _file_format(row.get("format"), row.get("media_type"), url)
793
+ if fmt == "service":
794
+ raise ValueError(f"{url} is a service ({row.get('format')}), not a file; open it with a client for that service")
795
+ if fmt == "archive":
796
+ raise ValueError(f"{url} is a compressed archive; use download() and unpack it")
797
+ if fmt == "page":
798
+ raise ValueError(f"{url} is a web page, not a file")
799
+ if fmt is None:
800
+ raise ValueError(f"cannot tell the file format of {url}; pass format='csv', 'json', 'xlsx' or 'parquet'")
801
+ with tempfile.TemporaryDirectory() as tmp:
802
+ path = download(url_or_row, os.path.join(tmp, f"distribution.{fmt}"))
803
+ if fmt in ("csv", "json"): # XLSX and Parquet are binary; their readers report bad files themselves
804
+ _check_payload(path)
805
+ return _read_table(path, fmt, sheet)
806
+
807
+
808
+ # ---------------------------------------------------------------- geodata
809
+
810
+ # Format ids, media types and extensions of vector geodata files, after _format_key(). Values are
811
+ # the file extension the download is saved under (GDAL needs it for some formats); "zip" for
812
+ # formats published as ZIP archives (shapefiles, MapInfo, file geodatabases).
813
+ _GEO_FORMATS = {
814
+ "geojson": "geojson", "application/geo+json": "geojson", "geo+json": "geojson",
815
+ "application/vnd.geo+json": "geojson",
816
+ "kml": "kml", "application/vnd.google-earth.kml+xml": "kml", "vnd.google-earth.kml+xml": "kml",
817
+ "kmz": "kmz", "application/vnd.google-earth.kmz": "kmz", "vnd.google-earth.kmz": "kmz",
818
+ "gml": "gml", "application/gml+xml": "gml", "gml+xml": "gml", "geographic markup language (gml)": "gml",
819
+ "xplangml": "gml", "kuntagml": "gml",
820
+ "gpkg": "gpkg", "geopackage": "gpkg", "geopackage - gpkg": "gpkg", "application/geopackage+sqlite3": "gpkg",
821
+ "geopackage+sqlite3": "gpkg",
822
+ "gpx": "gpx", "application/gpx+xml": "gpx", "gpx+xml": "gpx",
823
+ "fgb": "fgb", "flatgeobuf": "fgb",
824
+ "shp": "zip", "shape": "zip", "shapefile": "zip", "shapefiles": "zip", "shapefile (zip)": "zip",
825
+ "shapefile zip": "zip", "shp / zip": "zip", "esri shape": "zip", "esri shapefile": "zip",
826
+ "esri shapefile (shp)": "zip", "www:download:esri shapefile": "zip",
827
+ "tab": "zip", "mapinfo tab": "zip", "gdb": "zip", "esri file geodatabase": "zip", "file geodatabase": "zip",
828
+ }
829
+ # Extensions of the files GDAL is asked to open inside an archive; a ".gdb" folder counts too.
830
+ _GEO_MEMBER_EXTS = ("shp", "gpkg", "geojson", "kml", "gml", "gpx", "tab", "fgb")
831
+ _NESTED_ARCHIVE_EXTS = ("zip", "kmz", "gz", "tgz", "tar", "7z", "rar")
832
+
833
+
834
+ def _geo_format(fmt: str | None = None, media_type: str | None = None, url: str | None = None) -> str | None:
835
+ """The extension to save a geodata download under (``"geojson"``, ``"kml"``, ``"kmz"``,
836
+ ``"gml"``, ``"gpkg"``, ``"gpx"``, ``"fgb"``, or ``"zip"`` for shapefiles, MapInfo and file
837
+ geodatabases), from the format id, then the media type, then the URL's extension. None if
838
+ none of them names a geodata format."""
839
+ for cand in (fmt, media_type, _url_extension(url)):
840
+ if isinstance(cand, str) and cand.strip():
841
+ key = _format_key(cand)
842
+ if key in _GEO_FORMATS:
843
+ return _GEO_FORMATS[key]
844
+ return None
845
+
846
+
847
+ def _geo_member(names: list[str], layer: str | int | None = None) -> tuple[str, str | int | None]:
848
+ """Choose the file to read inside an archive, from its member ``names``.
849
+
850
+ Candidates: files ending in .shp, .gpkg, .geojson, .kml, .gml, .gpx, .tab or .fgb, and .gdb
851
+ folders; macOS metadata (``__MACOSX/``, ``._*``) is ignored. One candidate: that one. Several:
852
+ the one whose name (without extension) or path equals ``layer``, ignoring case; ``layer`` is
853
+ then used up and the second value is None. Otherwise raises ``ValueError`` listing them.
854
+ Returns ``(member, layer left for reading inside it)``.
855
+ """
856
+ files = [n.replace("\\", "/") for n in names if not n.endswith("/") and not n.endswith("\\")]
857
+ files = [n for n in files if not n.startswith("__MACOSX/") and not n.rsplit("/", 1)[-1].startswith("._")]
858
+ cands: list[str] = []
859
+ for n in files:
860
+ low = n.lower()
861
+ if ".gdb/" in low:
862
+ folder = n[:low.index(".gdb/") + 4]
863
+ if folder not in cands:
864
+ cands.append(folder)
865
+ elif "." in low.rsplit("/", 1)[-1] and low.rsplit(".", 1)[-1] in _GEO_MEMBER_EXTS:
866
+ cands.append(n)
867
+ cands.sort()
868
+ if not cands:
869
+ nested = sorted(n for n in files if "." in n.rsplit("/", 1)[-1] and n.rsplit(".", 1)[-1].lower() in _NESTED_ARCHIVE_EXTS)
870
+ if nested:
871
+ raise ValueError(f"the archive holds other archives ({', '.join(nested)}); download() it and unpack them")
872
+ raise ValueError("the archive holds no geodata file (looked for .shp, .gpkg, .geojson, .kml, .gml, .gpx, "
873
+ ".tab, .fgb files and .gdb folders)")
874
+ if len(cands) == 1:
875
+ return cands[0], layer
876
+ if isinstance(layer, str):
877
+ want = layer.lower()
878
+ hits = [c for c in cands if c.lower() == want or c.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower() == want]
879
+ if len(hits) == 1:
880
+ return hits[0], None
881
+ raise ValueError(f"the archive holds {len(cands)} geodata files ({', '.join(cands)}); pick one with layer=")
882
+
883
+
884
+ # Format ids of the feature services load_geodata reads, after _format_key().
885
+ _WFS_FORMATS = {"wfs", "ogc:wfs", "wfs_srvc"}
886
+ _OAPIF_FORMATS = {"ogcfeat", "ogc api features", "ogcapi-features"}
887
+
888
+
889
+ def _service_source(fmt: str | None = None, url: str | None = None) -> str | None:
890
+ """The GDAL data source for a feature service: ``"WFS:<url>"`` or ``"OAPIF:<url>"``, or None
891
+ when the distribution is not one (or is another service, such as WMS).
892
+
893
+ A ``service=`` parameter in the URL decides (``service=WFS``: WFS, anything else: None),
894
+ because format ids are often wrong. Otherwise an OGC API Features format id, or a URL ending
895
+ in ``/collections/{id}`` or ``/collections/{id}/items``, means OGC API Features (the URL is
896
+ cut to the collection, without query); a WFS format id means WFS. Only http(s) URLs.
897
+ """
898
+ import re
899
+ from urllib.parse import urlparse
900
+
901
+ if not isinstance(url, str) or not url.strip():
902
+ return None
903
+ u = url.strip()
904
+ parts = urlparse(u)
905
+ if parts.scheme.lower() not in ("http", "https") or not parts.netloc:
906
+ return None
907
+ m = re.search(r"(?:^|&)service=([^&]*)", parts.query, re.IGNORECASE)
908
+ if m:
909
+ return f"WFS:{u}" if m.group(1).lower() == "wfs" else None
910
+ key = _format_key(fmt) if isinstance(fmt, str) and fmt.strip() else ""
911
+ path = parts.path.rstrip("/")
912
+ collection = re.search(r"/collections/[^/]+(/items)?$", path)
913
+ if key in _OAPIF_FORMATS or collection:
914
+ if collection and collection.group(1):
915
+ path = path[: -len("/items")]
916
+ return f"OAPIF:{parts.scheme}://{parts.netloc}{path}"
917
+ return f"WFS:{u}" if key in _WFS_FORMATS else None
918
+
919
+
920
+ def _pick_layer(layers: list[str], layer: str | int | None = None, what: str = "the file") -> str:
921
+ """The layer to read: ``layer`` by name or 0-based position; by default the first, with a
922
+ warning if there are more. A name matches exactly, else ignoring case, else (once) the part
923
+ after a namespace prefix, as in WFS layer names (``"roads"`` for ``"ns:roads"``)."""
924
+ import warnings
925
+
926
+ if not layers:
927
+ raise ValueError(f"{what} holds no layers")
928
+ if layer is None:
929
+ if len(layers) > 1:
930
+ warnings.warn(f"{what} has {len(layers)} layers ({', '.join(layers)}); reading {layers[0]!r}, "
931
+ f"pick another with layer=", stacklevel=3)
932
+ return layers[0]
933
+ if isinstance(layer, int) and not isinstance(layer, bool):
934
+ if 0 <= layer < len(layers):
935
+ return layers[layer]
936
+ raise ValueError(f"layer {layer} is out of range: {what} has {len(layers)} layers ({', '.join(layers)})")
937
+ if layer in layers:
938
+ return layer
939
+ want = str(layer).lower()
940
+ for hits in ([n for n in layers if n.lower() == want],
941
+ [n for n in layers if n.lower().rpartition(":")[2] == want]):
942
+ if len(hits) == 1:
943
+ return hits[0]
944
+ raise ValueError(f"no layer {layer!r}; {what} has {', '.join(layers)}")
945
+
946
+
947
+ def _read_geodata(path: str | os.PathLike, layer: str | int | None = None, crs: Any = None):
948
+ """Read a local geodata file (or a ZIP holding one) into a GeoDataFrame."""
949
+ import warnings
950
+ import zipfile
951
+
952
+ try:
953
+ import geopandas
954
+ import pyogrio
955
+ except ImportError:
956
+ raise ImportError("load_geodata needs geopandas and pyogrio: pip install 'dataeuropa[geo]'") from None
957
+ with open(path, "rb") as fh:
958
+ head = fh.read(512)
959
+ start = head.lstrip(b"\xef\xbb\xbf \t\r\n").lower()
960
+ if start.startswith(b"<!doctype html") or start.startswith(b"<html"):
961
+ raise ValueError("the download is an HTML page, not a data file (often a landing page)")
962
+ src = os.path.abspath(path).replace("\\", "/")
963
+ if head.startswith(b"PK\x03\x04"):
964
+ with zipfile.ZipFile(path) as z:
965
+ member, layer = _geo_member(z.namelist(), layer)
966
+ src = f"/vsizip/{src}/{member}"
967
+ elif head.startswith(b"\x1f\x8b"):
968
+ src = f"/vsigzip/{src}"
969
+ return _read_source(src, layer, crs)
970
+
971
+
972
+ def _read_source(src: str, layer: str | int | None = None, crs: Any = None, max_features: int | None = None,
973
+ what: str = "the file"):
974
+ """Read a GDAL data source (a local path, /vsizip/ path, or WFS:/OAPIF: service) into a
975
+ GeoDataFrame. ``max_features``: read at most that many, with a warning if there are more."""
976
+ import warnings
977
+
978
+ import geopandas
979
+ import pyogrio
980
+
981
+ try:
982
+ layers = [str(entry[0]) for entry in pyogrio.list_layers(src)]
983
+ except Exception as e: # pyogrio raises its own DataSourceError
984
+ raise ValueError(f"cannot read {what} as geodata: {e}") from None
985
+ name = _pick_layer(layers, layer, what)
986
+ extra = {} if max_features is None else {"max_features": max_features + 1}
987
+ try:
988
+ with warnings.catch_warnings():
989
+ warnings.filterwarnings("ignore", message=".*has GPKG application_id.*")
990
+ gdf = geopandas.read_file(src, layer=name, engine="pyogrio", **extra)
991
+ except Exception as e:
992
+ if what == "the file":
993
+ raise
994
+ raise ValueError(f"cannot read {what}: {e}") from None
995
+ if max_features is not None and len(gdf) > max_features:
996
+ warnings.warn(f"{what} has more than {max_features:,} features; read the first {max_features:,} "
997
+ f"(pass max_features=None for all)", stacklevel=3)
998
+ gdf = gdf.iloc[:max_features]
999
+ if not isinstance(gdf, geopandas.GeoDataFrame) or getattr(gdf, "_geometry_column_name", None) not in gdf.columns:
1000
+ raise ValueError(f"{what} has no geometries (a plain table?); use load_distribution()")
1001
+ if gdf.crs is None:
1002
+ if crs is not None:
1003
+ raise ValueError("the data has no coordinate reference system (no .prj file?), so it cannot be "
1004
+ "reprojected; read it without crs= and set one with set_crs()")
1005
+ warnings.warn("the data has no coordinate reference system (no .prj file?); coordinates are as stored",
1006
+ stacklevel=2)
1007
+ elif crs is not None:
1008
+ gdf = gdf.to_crs(crs)
1009
+ return gdf
1010
+
1011
+
1012
+ # 2D geometry type names, as reported by GEOS, sf (upper case) and GDAL.
1013
+ _GEOMETRY_TYPES = {t.upper(): t for t in ("Point", "LineString", "Polygon", "MultiPoint", "MultiLineString",
1014
+ "MultiPolygon", "GeometryCollection")}
1015
+
1016
+
1017
+ def _geo_summary(gdf, columns: list[str] | None = None) -> dict:
1018
+ """What the conformance cases compare of a GeoDataFrame: attribute columns (or the values of
1019
+ ``columns`` only), row count (``nrow``), 2D geometry types, EPSG code and bounds."""
1020
+ import pandas as pd
1021
+
1022
+ def plain(v):
1023
+ if v is None or (not isinstance(v, (list, dict)) and pd.isna(v)):
1024
+ return None
1025
+ return v.item() if hasattr(v, "item") else v
1026
+
1027
+ attrs = [str(c) for c in gdf.columns if c != gdf.geometry.name]
1028
+ out: dict = {"columns": attrs} if columns is None else {}
1029
+ out["values"] = {c: [plain(v) for v in gdf[c]] for c in (attrs if columns is None else columns)}
1030
+ out["nrow"] = len(gdf)
1031
+ out["geometry_types"] = sorted({_GEOMETRY_TYPES.get(t.upper().replace(" Z", ""), t) for t in gdf.geom_type})
1032
+ out["crs"] = gdf.crs.to_epsg() if gdf.crs is not None else None
1033
+ out["bounds"] = [round(float(b), 6) for b in gdf.total_bounds]
1034
+ return out
1035
+
1036
+
1037
+ def load_geodata(url_or_row: str | dict, *, layer: str | int | None = None, crs: Any = None,
1038
+ max_mb: float | None = 200, max_features: int | None = 10_000):
1039
+ """Download a geodata distribution, or read a feature service, into a geopandas GeoDataFrame.
1040
+
1041
+ Accepts a URL, or a row/dict from :func:`distributions`. Needs geopandas and pyogrio
1042
+ (``pip install 'dataeuropa[geo]'``); GDAL does the reading, so any vector format it knows
1043
+ works: GeoJSON, Shapefile, GeoPackage, KML/KMZ, GML, GPX, MapInfo TAB, FlatGeobuf, file
1044
+ geodatabase.
1045
+
1046
+ ZIP archives (how shapefiles are published) are opened in place. Inside, the one geodata file
1047
+ is read (a .shp with its .dbf/.shx/.prj, .gpkg, .geojson, .kml, .gml, .gpx, .tab, .fgb, or a
1048
+ .gdb folder); if there are several, ``layer`` picks one by file name (without extension),
1049
+ otherwise ``ValueError`` lists them. Archives inside archives are not opened.
1050
+
1051
+ ``layer`` picks a layer by name or 0-based position in files with several (GeoPackage, file
1052
+ geodatabase); by default the first is read, with a warning if there are more.
1053
+
1054
+ The source coordinate reference system is kept. ``crs`` (e.g. ``"EPSG:4326"``) reprojects; a
1055
+ file without one (a shapefile without .prj) is read as stored, with a warning.
1056
+
1057
+ Files over ``max_mb`` megabytes (default 200) are not downloaded; ``max_mb=None`` lifts the
1058
+ limit.
1059
+
1060
+ Feature services are read too: WFS (``service=WFS`` URLs, WFS format ids) and OGC API
1061
+ Features (collection or landing-page URLs, OGCFEAT format ids). GDAL pages through the
1062
+ results. Each collection or feature type is a layer. At most ``max_features`` features
1063
+ (default 10,000) are read, with a warning when there are more; ``max_features=None`` reads all.
1064
+
1065
+ Raises ``ValueError`` for other services (WMS, ...), web pages, HTML served instead of data,
1066
+ files or services GDAL cannot read, and checksum mismatches.
1067
+ """
1068
+ import re
1069
+ import tempfile
1070
+
1071
+ row = {"url": url_or_row} if isinstance(url_or_row, str) else url_or_row
1072
+ url = row.get("url")
1073
+ if not url:
1074
+ raise ValueError("no URL available for this distribution")
1075
+ try:
1076
+ import geopandas # noqa: F401
1077
+ import pyogrio # noqa: F401
1078
+ except ImportError:
1079
+ raise ImportError("load_geodata needs geopandas and pyogrio: pip install 'dataeuropa[geo]'") from None
1080
+ source = _service_source(row.get("format"), url)
1081
+ if source is not None:
1082
+ return _read_source(source, layer, crs, max_features=max_features, what="the service")
1083
+ kind = _distribution_kind(row.get("format"), row.get("media_type"), url, row.get("download_url"))
1084
+ if kind == "service":
1085
+ raise ValueError(f"{url} is a service ({row.get('format')}) that load_geodata cannot read; "
1086
+ f"it reads files, WFS and OGC API Features")
1087
+ if kind == "page":
1088
+ raise ValueError(f"{url} is a web page, not a file")
1089
+ ext = _geo_format(row.get("format"), row.get("media_type"), url) or _url_extension(url) or ""
1090
+ if not re.fullmatch(r"[A-Za-z0-9]{1,8}", ext):
1091
+ ext = "dat"
1092
+ limit = None if max_mb is None else int(max_mb * 1_000_000)
1093
+ with tempfile.TemporaryDirectory() as tmp:
1094
+ try:
1095
+ path = download(url_or_row, os.path.join(tmp, f"distribution.{ext.lower()}"), max_bytes=limit)
1096
+ except _TooLarge:
1097
+ raise ValueError(f"{url} is larger than {max_mb:g} MB; pass max_mb=None to load it anyway") from None
1098
+ return _read_geodata(path, layer, crs)
1099
+
1100
+
1101
+ def facet_values(facet: str, q: str | None = None, *, top: int | None = 50, filters: str = "dataset",
1102
+ **kw) -> Any:
1103
+ """List the values (and counts) of a facet, e.g. ``"country"``, ``"format"``, ``"categories"``."""
1104
+ fid = _FACET_ALIASES.get(facet, facet)
1105
+ res = search(q, filters=filters, limit=0, aggregation=True,
1106
+ extra={"aggregationAllFields": "false", "aggregationFields": fid}, **kw)
1107
+ rows = _facet_rows(res, fid, top)
1108
+ if rows is None:
1109
+ raise KeyError(f"unknown facet {facet!r}")
1110
+ return _tabulate(rows, True)
1111
+
1112
+
1113
+ def _facet_rows(res: dict, fid: str, top: int | None = None) -> list[dict] | None:
1114
+ """Rows (id, label, count) of facet ``fid`` in a search result, most frequent first; None if absent.
1115
+
1116
+ ``label`` is the item's title, else its label, else its id; a missing ``count`` is 0.
1117
+ Ties keep the API's order.
1118
+ """
1119
+ for f in res.get("facets") or []:
1120
+ if f.get("id") == fid:
1121
+ rows = [{"id": i.get("id"),
1122
+ "label": pick_lang(i.get("title")) or i.get("label") or i.get("id"),
1123
+ "count": int(i.get("count") or 0)} for i in f.get("items") or []]
1124
+ rows.sort(key=lambda x: -x["count"])
1125
+ return rows[:top] if top else rows
1126
+ return None
1127
+
1128
+
1129
+ def count(q: str | None = None, **kw) -> int:
1130
+ """Number of hits for a query (no records transferred)."""
1131
+ return int(search(q, limit=0, **kw)["count"])
1132
+
1133
+
1134
+ def catalogues() -> list[str]:
1135
+ """Ids of all harvested catalogues."""
1136
+ return _get_json(f"{SEARCH_URL}/catalogues", cacheable=True)
1137
+
1138
+
1139
+ def get_rdf(dataset_id: str, fmt: str = "ttl") -> str:
1140
+ """Dataset metadata as RDF text. ``fmt``: ``ttl`` (Turtle) or ``jsonld``."""
1141
+ if fmt not in ("ttl", "jsonld"):
1142
+ raise ValueError("fmt must be 'ttl' or 'jsonld'")
1143
+ r = _get_session().get(f"{REPO_URL}/datasets/{dataset_id}.{fmt}", timeout=_timeout())
1144
+ _raise(r)
1145
+ return r.text
1146
+
1147
+
1148
+ def sparql(query: str, *, as_dataframe: bool = True):
1149
+ """Run a SPARQL SELECT/ASK query against data.europa.eu. Returns a table of plain values."""
1150
+ r = _get_session().post(SPARQL_URL, data={"query": query},
1151
+ headers={"Accept": "application/sparql-results+json"}, timeout=_timeout())
1152
+ _raise(r)
1153
+ res = _sparql_rows(r.json())
1154
+ return res if isinstance(res, bool) else _tabulate(res, as_dataframe)
1155
+
1156
+
1157
+ def _sparql_rows(j: dict) -> bool | list[dict]:
1158
+ """ASK result as a bool, or SELECT bindings as rows of plain string values (None when unbound)."""
1159
+ if "boolean" in j:
1160
+ return bool(j["boolean"])
1161
+ cols = j["head"]["vars"]
1162
+ return [{c: (b[c]["value"] if c in b else None) for c in cols} for b in j["results"]["bindings"]]
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: dataeuropa
3
+ Version: 0.1.0
4
+ Summary: Python client for the data.europa.eu open data portal (Search API, Registry, SPARQL)
5
+ Author-email: Nigel Randsley <nigel.randsley@protonmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/randsley/dataeuropa
8
+ Project-URL: Documentation, https://randsley.github.io/dataeuropa/python/
9
+ Project-URL: Issues, https://github.com/randsley/dataeuropa/issues
10
+ Project-URL: Changelog, https://github.com/randsley/dataeuropa/blob/main/CHANGELOG.md
11
+ Keywords: open data,data.europa.eu,European data portal,DCAT-AP,SPARQL,geodata
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests>=2.28
21
+ Provides-Extra: pandas
22
+ Requires-Dist: pandas>=1.5; extra == "pandas"
23
+ Provides-Extra: xlsx
24
+ Requires-Dist: pandas>=1.5; extra == "xlsx"
25
+ Requires-Dist: openpyxl>=3.1; extra == "xlsx"
26
+ Provides-Extra: parquet
27
+ Requires-Dist: pandas>=1.5; extra == "parquet"
28
+ Requires-Dist: pyarrow>=14; extra == "parquet"
29
+ Provides-Extra: geo
30
+ Requires-Dist: pandas>=1.5; extra == "geo"
31
+ Requires-Dist: geopandas>=0.14; extra == "geo"
32
+ Requires-Dist: pyogrio>=0.7; extra == "geo"
33
+ Provides-Extra: test
34
+ Requires-Dist: pytest; extra == "test"
35
+ Requires-Dist: pandas; extra == "test"
36
+ Requires-Dist: openpyxl; extra == "test"
37
+ Requires-Dist: pyarrow; extra == "test"
38
+ Requires-Dist: geopandas; extra == "test"
39
+ Requires-Dist: pyogrio; extra == "test"
40
+ Provides-Extra: docs
41
+ Requires-Dist: mkdocs-material<10,>=9.5; extra == "docs"
42
+ Requires-Dist: mkdocstrings[python]>=0.26; extra == "docs"
43
+ Dynamic: license-file
44
+
45
+ # dataeuropa (Python)
46
+ Client for data.europa.eu. See the top-level README for the cross-language overview.
47
+ `pip install ".[pandas]"` · tests: `pytest` (live tests are marked `live`; skip with `-m "not live"`).
@@ -0,0 +1,7 @@
1
+ dataeuropa/__init__.py,sha256=yciNeax-O8hSjG2lCjw7N375xL7K6qFj-WacavxJbME,766
2
+ dataeuropa/client.py,sha256=lq_fh7Gs01ZA3UnL_zXjbBs1mJ6Oa0tseStPXUK0NFo,54234
3
+ dataeuropa-0.1.0.dist-info/licenses/LICENSE,sha256=ZJ0FsB5QBLe8EJ3N2wVMxH3muhiY-hCedGQWYiJcXqY,1071
4
+ dataeuropa-0.1.0.dist-info/METADATA,sha256=nWby4Jm89ukv4LvJC5JMhVZTjC-rbw0aoby1xfuEc2E,2058
5
+ dataeuropa-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ dataeuropa-0.1.0.dist-info/top_level.txt,sha256=zVChnutXKSTnMppbVKNxI6BKLjaZ_3bJ3EQj_kaJGis,11
7
+ dataeuropa-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nigel Randsley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ dataeuropa