cmem-plugin-gps 0.5.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.
- cmem_plugin_gps/__init__.py +1 -0
- cmem_plugin_gps/convert.py +79 -0
- cmem_plugin_gps/crs.py +100 -0
- cmem_plugin_gps/detect.py +69 -0
- cmem_plugin_gps/epsg_axes.py +65 -0
- cmem_plugin_gps/formats/__init__.py +1 -0
- cmem_plugin_gps/formats/geojson.py +229 -0
- cmem_plugin_gps/formats/gml.py +512 -0
- cmem_plugin_gps/formats/gpx.py +270 -0
- cmem_plugin_gps/formats/kml.py +391 -0
- cmem_plugin_gps/geometry.py +190 -0
- cmem_plugin_gps/gps.svg +3 -0
- cmem_plugin_gps/model.py +79 -0
- cmem_plugin_gps/rdf.py +430 -0
- cmem_plugin_gps/task.py +304 -0
- cmem_plugin_gps/times.py +45 -0
- cmem_plugin_gps-0.5.0.dist-info/METADATA +45 -0
- cmem_plugin_gps-0.5.0.dist-info/RECORD +20 -0
- cmem_plugin_gps-0.5.0.dist-info/WHEEL +4 -0
- cmem_plugin_gps-0.5.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""cmem-plugin-gps"""
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Convert one input file to quads."""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
from collections.abc import Callable, Iterator
|
|
5
|
+
from typing import IO, NamedTuple
|
|
6
|
+
|
|
7
|
+
from cmem_plugin_base.dataintegration.typed_entities.quads import Quad
|
|
8
|
+
from defusedxml.ElementTree import ParseError
|
|
9
|
+
|
|
10
|
+
from cmem_plugin_gps.detect import FileFormat, InputFileError, detect_format
|
|
11
|
+
from cmem_plugin_gps.formats import geojson, gml, gpx, kml
|
|
12
|
+
from cmem_plugin_gps.model import ParseEvent, Skipped
|
|
13
|
+
from cmem_plugin_gps.rdf import MappingOptions, to_quads
|
|
14
|
+
|
|
15
|
+
Parser = Callable[[IO[bytes], Skipped], Iterator[ParseEvent]]
|
|
16
|
+
|
|
17
|
+
PARSERS: dict[FileFormat, Parser] = {
|
|
18
|
+
"gpx": gpx.parse,
|
|
19
|
+
"geojson": geojson.parse,
|
|
20
|
+
"kml": kml.parse,
|
|
21
|
+
"kmz": kml.parse_kmz,
|
|
22
|
+
"gml": gml.parse,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
HEAD_SIZE = 4096
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Source(NamedTuple):
|
|
29
|
+
"""Where a file comes from and how its resources are named."""
|
|
30
|
+
|
|
31
|
+
path: str # shown in messages and written as gps:sourceFile, `archive!entry` for an entry
|
|
32
|
+
iri: str # the IRI of the collection that stands for the file
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _format_of(stream: IO[bytes], path: str, file_format: str) -> str:
|
|
36
|
+
if file_format != "auto":
|
|
37
|
+
return file_format
|
|
38
|
+
head = stream.read(HEAD_SIZE)
|
|
39
|
+
stream.seek(0)
|
|
40
|
+
return detect_format(path, head)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _parser_for(file_format: str, path: str) -> Parser:
|
|
44
|
+
for known, parser in PARSERS.items():
|
|
45
|
+
if known == file_format:
|
|
46
|
+
return parser
|
|
47
|
+
raise InputFileError(f"Could not read '{path}': unsupported format '{file_format}'")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _events(
|
|
51
|
+
stream: IO[bytes], source: Source, file_format: str, skipped: Skipped
|
|
52
|
+
) -> Iterator[ParseEvent]:
|
|
53
|
+
"""Read the events of a file, turning what is wrong with the input into `InputFileError`."""
|
|
54
|
+
try:
|
|
55
|
+
if file_format == "auto" and not stream.seekable():
|
|
56
|
+
stream = io.BytesIO(stream.read())
|
|
57
|
+
parser = _parser_for(_format_of(stream, source.path, file_format), source.path)
|
|
58
|
+
yield from parser(stream, skipped)
|
|
59
|
+
except (InputFileError, KeyError, IndexError):
|
|
60
|
+
raise # the last two are programming errors, which a file cannot be blamed for
|
|
61
|
+
except (ParseError, ValueError, OSError, LookupError) as err: # LookupError: unknown encoding
|
|
62
|
+
raise InputFileError(f"Could not read '{source.path}': {err}") from err
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def convert_file(
|
|
66
|
+
stream: IO[bytes],
|
|
67
|
+
source: Source,
|
|
68
|
+
file_format: str,
|
|
69
|
+
options: MappingOptions,
|
|
70
|
+
skipped: Skipped,
|
|
71
|
+
) -> Iterator[Quad]:
|
|
72
|
+
"""Read a file in the given format, or detect it with "auto", and map it to quads.
|
|
73
|
+
|
|
74
|
+
The quads are produced while the file is read, so what came before an error stays
|
|
75
|
+
available. An unreadable file raises an `InputFileError` naming it. Errors of the mapping
|
|
76
|
+
itself are not input errors and propagate unchanged.
|
|
77
|
+
"""
|
|
78
|
+
events = _events(stream, source, file_format, skipped)
|
|
79
|
+
yield from to_quads(events, source.iri, source.path, options, skipped)
|
cmem_plugin_gps/crs.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Resolve coordinate reference system names to what the RDF mapper needs."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import NamedTuple
|
|
6
|
+
|
|
7
|
+
from cmem_plugin_gps.epsg_axes import NORTH_FIRST
|
|
8
|
+
|
|
9
|
+
EPSG_IRI = "http://www.opengis.net/def/crs/EPSG/0/{code}"
|
|
10
|
+
WGS84_CODES = frozenset({"4326", "4979"}) # 4979 is WGS84 with height
|
|
11
|
+
CRS84 = "CRS84"
|
|
12
|
+
|
|
13
|
+
# Forms that declare the axis order of the EPSG definition
|
|
14
|
+
_AXIS_ORDERED = (
|
|
15
|
+
re.compile(r"^urn:(?:x-)?ogc:def:crs:EPSG:(?:[^:]*:)?(\d+)$", re.IGNORECASE),
|
|
16
|
+
re.compile(r"^https?://www\.opengis\.net/def/crs/EPSG/[^/]+/(\d+)$", re.IGNORECASE),
|
|
17
|
+
)
|
|
18
|
+
# Legacy forms that mean x,y, which is longitude/latitude
|
|
19
|
+
_LEGACY = (
|
|
20
|
+
re.compile(r"^EPSG:(\d+)$", re.IGNORECASE),
|
|
21
|
+
re.compile(r"^https?://www\.opengis\.net/gml/srs/epsg\.xml#(\d+)$", re.IGNORECASE),
|
|
22
|
+
)
|
|
23
|
+
_CRS84 = (
|
|
24
|
+
re.compile(r"^urn:(?:x-)?ogc:def:crs:OGC:[^:]*:CRS84$", re.IGNORECASE),
|
|
25
|
+
re.compile(r"^https?://www\.opengis\.net/def/crs/OGC/[^/]+/CRS84$", re.IGNORECASE),
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class ResolvedCrs:
|
|
31
|
+
"""A resolved coordinate reference system."""
|
|
32
|
+
|
|
33
|
+
iri: str | None # None means WGS84
|
|
34
|
+
# True: the first two values of the source are turned around. The result is longitude/latitude
|
|
35
|
+
# for WGS84 and the order its IRI declares for any other system.
|
|
36
|
+
swap_axes: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Name(NamedTuple):
|
|
40
|
+
"""What the name of a reference system says."""
|
|
41
|
+
|
|
42
|
+
code: str # the EPSG code, or `CRS84`
|
|
43
|
+
written_east_first: bool
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _parse(srs_name: str) -> _Name | None:
|
|
47
|
+
name = srs_name.strip()
|
|
48
|
+
if any(pattern.match(name) for pattern in _CRS84):
|
|
49
|
+
return _Name(CRS84, written_east_first=True)
|
|
50
|
+
for pattern in _AXIS_ORDERED:
|
|
51
|
+
if match := pattern.match(name):
|
|
52
|
+
return _Name(match.group(1), written_east_first=False)
|
|
53
|
+
for pattern in _LEGACY:
|
|
54
|
+
if match := pattern.match(name):
|
|
55
|
+
return _Name(match.group(1), written_east_first=True)
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _from_code(code: str, *, written_east_first: bool) -> ResolvedCrs:
|
|
60
|
+
if code in WGS84_CODES:
|
|
61
|
+
return ResolvedCrs(None, swap_axes=not written_east_first)
|
|
62
|
+
return ResolvedCrs(EPSG_IRI.format(code=code), written_east_first and code in NORTH_FIRST)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def same_crs(first: str, second: str) -> bool:
|
|
66
|
+
"""Tell whether two names stand for the same reference system.
|
|
67
|
+
|
|
68
|
+
The order the names imply does not matter, and names that cannot be interpreted are compared
|
|
69
|
+
as they are written.
|
|
70
|
+
"""
|
|
71
|
+
parsed_first, parsed_second = _parse(first), _parse(second)
|
|
72
|
+
if parsed_first is None or parsed_second is None:
|
|
73
|
+
return first.strip() == second.strip()
|
|
74
|
+
return parsed_first.code == parsed_second.code
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def resolve_gml_crs(srs_name: str | None) -> ResolvedCrs | None:
|
|
78
|
+
"""Resolve a GML srsName, or return None if it cannot be interpreted."""
|
|
79
|
+
parsed = _parse(srs_name) if srs_name else None
|
|
80
|
+
if parsed is None:
|
|
81
|
+
return None
|
|
82
|
+
if parsed.code == CRS84:
|
|
83
|
+
return ResolvedCrs(None, swap_axes=False)
|
|
84
|
+
return _from_code(parsed.code, written_east_first=parsed.written_east_first)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def resolve_geojson_crs(name: str | None) -> ResolvedCrs | None:
|
|
88
|
+
"""Resolve a GeoJSON crs name.
|
|
89
|
+
|
|
90
|
+
GeoJSON positions are always x,y whatever form the name has. WGS84 therefore stays as it is,
|
|
91
|
+
and a north first system is turned around into the order of its IRI.
|
|
92
|
+
"""
|
|
93
|
+
if name is None:
|
|
94
|
+
return ResolvedCrs(None, swap_axes=False)
|
|
95
|
+
resolved = resolve_gml_crs(name)
|
|
96
|
+
if resolved is None:
|
|
97
|
+
return None
|
|
98
|
+
if resolved.iri is None:
|
|
99
|
+
return ResolvedCrs(None, swap_axes=False)
|
|
100
|
+
return ResolvedCrs(resolved.iri, resolved.iri.rpartition("/")[2] in NORTH_FIRST)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Detect the format of an input file."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Literal, get_args
|
|
5
|
+
|
|
6
|
+
FileFormat = Literal["gpx", "kml", "kmz", "geojson", "gml"]
|
|
7
|
+
|
|
8
|
+
_BY_EXTENSION: dict[str, FileFormat] = {name: name for name in get_args(FileFormat)}
|
|
9
|
+
_GEOJSON_TYPES = frozenset(
|
|
10
|
+
{
|
|
11
|
+
"Feature",
|
|
12
|
+
"FeatureCollection",
|
|
13
|
+
"Point",
|
|
14
|
+
"MultiPoint",
|
|
15
|
+
"LineString",
|
|
16
|
+
"MultiLineString",
|
|
17
|
+
"Polygon",
|
|
18
|
+
"MultiPolygon",
|
|
19
|
+
"GeometryCollection",
|
|
20
|
+
}
|
|
21
|
+
)
|
|
22
|
+
_ZIP_MAGIC = b"PK\x03\x04"
|
|
23
|
+
_BOM = b"\xef\xbb\xbf"
|
|
24
|
+
_ROOT_TAG = re.compile(r"<([A-Za-z_][^\s/>]*)([^>]*)")
|
|
25
|
+
_JSON_TYPE = re.compile(r'"type"\s*:\s*"([^"]*)"')
|
|
26
|
+
_GML_NAMESPACE = "opengis.net/gml"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class InputFileError(ValueError):
|
|
30
|
+
"""An input file cannot be read. The message names the file."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _extension(path: str) -> str:
|
|
34
|
+
# The entry of an archive is written as `archive!entry` and only the entry counts
|
|
35
|
+
name = path.replace("\\", "/").rsplit("!", 1)[-1].rsplit("/", 1)[-1]
|
|
36
|
+
return name.rpartition(".")[2].lower() if "." in name else ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _from_content(head: bytes) -> FileFormat | None:
|
|
40
|
+
if head.startswith(_ZIP_MAGIC):
|
|
41
|
+
return "kmz"
|
|
42
|
+
text = head.removeprefix(_BOM).decode("utf-8", errors="replace").lstrip()
|
|
43
|
+
if text.startswith("{"):
|
|
44
|
+
types = set(_JSON_TYPE.findall(text))
|
|
45
|
+
return "geojson" if types & _GEOJSON_TYPES else None
|
|
46
|
+
if (root := _ROOT_TAG.search(text)) is None:
|
|
47
|
+
return None
|
|
48
|
+
local = root.group(1).rpartition(":")[2]
|
|
49
|
+
if local == "gpx":
|
|
50
|
+
return "gpx"
|
|
51
|
+
if local == "kml":
|
|
52
|
+
return "kml"
|
|
53
|
+
return "gml" if _GML_NAMESPACE in root.group(0) else None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def detect_format(path: str, head: bytes) -> FileFormat:
|
|
57
|
+
"""Return the format of a file from its name and its first bytes.
|
|
58
|
+
|
|
59
|
+
The extension decides. Only `.json`, `.xml` and a missing extension are decided by the
|
|
60
|
+
content. An unclear format raises an `InputFileError` naming the file.
|
|
61
|
+
"""
|
|
62
|
+
extension = _extension(path)
|
|
63
|
+
if extension in _BY_EXTENSION:
|
|
64
|
+
return _BY_EXTENSION[extension]
|
|
65
|
+
if extension in ("json", "xml", "") and (detected := _from_content(head)) is not None:
|
|
66
|
+
return detected
|
|
67
|
+
raise InputFileError(
|
|
68
|
+
f"Could not detect the format of '{path}'. Choose the file format in the task settings."
|
|
69
|
+
)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""The EPSG systems whose definition has the north or south axis first.
|
|
2
|
+
|
|
3
|
+
Generated by `tests/generate_epsg_axes.py` from EPSG v12.029 of 2025-10-02, do not edit.
|
|
4
|
+
Deprecated systems are included, as old data keeps using them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
_RANGES = (
|
|
8
|
+
"2036 2044-2045 2065 2081-2083 2085-2086 2091-2093 2096-2098 2105-2132 2166-2180 2193 "
|
|
9
|
+
"2199-2200 2206-2212 2218 2221 2296-2307 2319-2549 2551-2735 2738-2758 2935-2941 2953 2963 "
|
|
10
|
+
"3006-3030 3034-3035 3038-3051 3058-3059 3068 3114-3118 3120 3126-3140 3144-3147 3150-3152 "
|
|
11
|
+
"3173 3300-3301 3328-3335 3346 3350-3352 3366 3386-3390 3396-3399 3407 3414 3416 3764 "
|
|
12
|
+
"3788-3791 3793 3795-3796 3819 3821 3823-3824 3833-3852 3854 3873-3885 3888-3889 3901-3903 "
|
|
13
|
+
"3906-3911 4001-4038 4040-4047 4052-4055 4074-4075 4080-4081 4120-4176 4178-4185 4188-4216 "
|
|
14
|
+
"4218-4289 4291-4304 4306-4319 4322 4324 4326-4327 4329 4339 4341 4343 4345 4347 4349 4351 "
|
|
15
|
+
"4353 4355 4357 4359 4361 4363 4365 4367 4369 4371 4373 4375 4377 4379 4381 4383 4386 4388 "
|
|
16
|
+
"4417 4434 4463 4466 4469-4470 4472 4475 4480 4482-4483 4490-4555 4557-4558 4568-4589 "
|
|
17
|
+
"4600-4646 4652-4824 4839 4855-4880 4883 4885 4887 4889 4891 4893 4895 4898 4900-4904 4907 "
|
|
18
|
+
"4909 4921 4923 4925 4927 4929 4931 4933 4935 4937 4939 4941 4943 4945 4947 4949 4951 4953 "
|
|
19
|
+
"4955 4957 4959 4961 4963 4965 4967 4969 4971 4973 4975 4977 4979 4981 4983 4985 4987 4989 "
|
|
20
|
+
"4991 4993 4995 4997 4999 5012-5013 5017 5048 5105-5130 5132 5167-5188 5224 5228-5229 5233 "
|
|
21
|
+
"5245-5246 5251-5259 5263-5264 5269-5275 5323-5324 5340 5342-5349 5353-5354 5359-5360 "
|
|
22
|
+
"5364-5365 5367 5370-5373 5380-5381 5392-5393 5451 5464 5467 5479-5482 5488-5489 5498-5500 "
|
|
23
|
+
"5513 5515 5518-5520 5524 5527 5545-5546 5560-5583 5588 5592-5593 5628 5632-5639 5651-5653 "
|
|
24
|
+
"5681 5830 5845-5857 5885-5886 5942 5945-5970 6134-6135 6144-6170 6207 6244-6275 6310-6311 "
|
|
25
|
+
"6318-6319 6321-6322 6324-6325 6349 6362 6364-6365 6372 6381-6387 6649 6667-6687 6696-6697 "
|
|
26
|
+
"6700 6705-6709 6782-6783 6870 6875-6876 6881-6883 6892 6894 6917 6927 6962 6979-6980 "
|
|
27
|
+
"6982-6983 6986-6987 6989-6990 7072-7073 7135-7136 7138-7139 7372-7373 7400 7404 7406 "
|
|
28
|
+
"7408-7410 7414 7423 7657 7659 7661 7663 7665 7678 7680 7682-7683 7685-7686 7797-7801 7816 "
|
|
29
|
+
"7825-7831 7843-7844 7880-7881 7885-7886 7900-7912 7915 7917 7919 7921 7923 7925 7927 7929 "
|
|
30
|
+
"7931 8042-8045 8085-8086 8231-8232 8235 8237 8239-8240 8244 8246 8248-8249 8251-8252 "
|
|
31
|
+
"8254-8255 8349-8352 8360 8399 8403 8426-8428 8430-8431 8433 8441 8449 8542 8544-8545 "
|
|
32
|
+
"8684-8685 8694 8698-8699 8817-8818 8860 8888 8899-8900 8906-8907 8916 8918 8920 8922 8924 "
|
|
33
|
+
"8926 8928 8930 8932 8934 8936 8938 8940 8942 8944 8946 8948-8949 8972-9000 9002-9003 "
|
|
34
|
+
"9005-9006 9008-9009 9011-9014 9016-9019 9039-9040 9053-9057 9059-9069 9071-9072 9074-9075 "
|
|
35
|
+
"9139-9140 9147-9148 9152-9153 9183-9184 9221-9222 9248-9254 9267 9271-9273 9284-9286 "
|
|
36
|
+
"9289-9290 9293-9294 9299 9308-9309 9332-9333 9364 9372 9377 9379-9380 9384 9403 9422-9430 "
|
|
37
|
+
"9449-9450 9452-9453 9462-9464 9469-9470 9474-9475 9498 9500-9544 9546-9547 9656-9657 "
|
|
38
|
+
"9695-9696 9701-9702 9705 9707 9723-9725 9739 9754-9755 9758 9763 9776-9777 9781-9782 9785 "
|
|
39
|
+
"9821 9831-9841 9851-9866 9871 9883 9893 9895 9897 9907 9924 9939 9948-9950 9964 9969 9974 "
|
|
40
|
+
"9989-9990 10156-10158 10162-10175 10177-10178 10185 10191 10196 10204 10209 10214 10219 "
|
|
41
|
+
"10224 10229 10237 10245 10249 10252 10256 10260 10265 10268 10272 10277 10283-10284 10286 "
|
|
42
|
+
"10288 10290 10293 10298-10299 10304-10306 10309-10310 10327-10329 10345-10346 10355-10357 "
|
|
43
|
+
"10365 10413-10414 10468 10474-10475 10486-10488 10507 10545 10553-10556 10570-10571 "
|
|
44
|
+
"10605-10606 10623 10628 10635-10636 10638-10639 10643-10644 10651-10652 10659 10670-10671 "
|
|
45
|
+
"10679 10686 10689-10692 10724-10725 10735-10736 10738-10739 10741-10742 10758 10761-10762 "
|
|
46
|
+
"10765 10780-10781 10784-10785 10790-10791 10799-10800 10806-10807 10826 10830-10831 10833 "
|
|
47
|
+
"10836-10837 10839 10849 10860 10865 10874-10875 10891-10892 10898 10904 10909-10910 10920 "
|
|
48
|
+
"10940-10941 10951-10952 10955-10956 10958-10959 10967-10968 10979-10980 11000 11012-11019 "
|
|
49
|
+
"11042-11043 11114-11118 11158 20001 20004-20033 20037-20038 20040-20041 20043 20045-20046 "
|
|
50
|
+
"20064-20092 20904-20932 21004-21032 21207-21264 21307-21364 21413-21423 21453-21463 "
|
|
51
|
+
"21473-21483 21896-21899 22171-22177 22181-22187 22191-22197 22240 23301-23333 25884 "
|
|
52
|
+
"27205-27232 27391-27398 27492 28402-28432 28462-28492 29701-29702 30161-30179 30800 "
|
|
53
|
+
"31251-31259 31275-31279 31281-31290 31466-31469 31700 32661 32761 "
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _codes() -> frozenset[str]:
|
|
58
|
+
codes: set[str] = set()
|
|
59
|
+
for part in _RANGES.split():
|
|
60
|
+
first, _, last = part.partition("-")
|
|
61
|
+
codes.update(map(str, range(int(first), int(last or first) + 1)))
|
|
62
|
+
return frozenset(codes)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
NORTH_FIRST = _codes()
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Parsers of the supported file formats."""
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Parser for GeoJSON.
|
|
2
|
+
|
|
3
|
+
The document is loaded as a whole. Decimals are kept as `Decimal`, so the digits of a coordinate
|
|
4
|
+
reach the RDF as they were written.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Iterator
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import IO, Any
|
|
11
|
+
|
|
12
|
+
from cmem_plugin_gps.crs import ResolvedCrs, resolve_geojson_crs
|
|
13
|
+
from cmem_plugin_gps.geometry import is_well_formed, valid_position
|
|
14
|
+
from cmem_plugin_gps.model import (
|
|
15
|
+
Attribute,
|
|
16
|
+
Collection,
|
|
17
|
+
Feature,
|
|
18
|
+
Geometry,
|
|
19
|
+
ParseEvent,
|
|
20
|
+
Position,
|
|
21
|
+
Skipped,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_MIN_COORDINATES = 2
|
|
25
|
+
_MAX_COORDINATES = 3
|
|
26
|
+
_GEOMETRIES = frozenset(
|
|
27
|
+
{
|
|
28
|
+
"Point",
|
|
29
|
+
"MultiPoint",
|
|
30
|
+
"LineString",
|
|
31
|
+
"MultiLineString",
|
|
32
|
+
"Polygon",
|
|
33
|
+
"MultiPolygon",
|
|
34
|
+
"GeometryCollection",
|
|
35
|
+
}
|
|
36
|
+
)
|
|
37
|
+
_TYPES = _GEOMETRIES | {"Feature", "FeatureCollection"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _InvalidPositionError(ValueError):
|
|
41
|
+
"""A position or the structure holding it cannot be used."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _number(value: object) -> str:
|
|
45
|
+
# bool is an int in Python, but not a coordinate
|
|
46
|
+
if isinstance(value, bool) or not isinstance(value, int | Decimal):
|
|
47
|
+
raise _InvalidPositionError
|
|
48
|
+
return str(value)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _position(coordinates: object, crs: ResolvedCrs, skipped: Skipped) -> Position:
|
|
52
|
+
"""Return the position, cutting what lies beyond the third element.
|
|
53
|
+
|
|
54
|
+
A north first system is turned around here, so the position has the order of its IRI.
|
|
55
|
+
"""
|
|
56
|
+
if not isinstance(coordinates, list) or len(coordinates) < _MIN_COORDINATES:
|
|
57
|
+
raise _InvalidPositionError
|
|
58
|
+
first, second, *rest = (_number(value) for value in coordinates[:_MAX_COORDINATES])
|
|
59
|
+
x, y = (second, first) if crs.swap_axes else (first, second)
|
|
60
|
+
height = rest[0] if rest else None
|
|
61
|
+
position = valid_position(x, y, height, wgs84=crs.iri is None, skipped=skipped)
|
|
62
|
+
if position is None:
|
|
63
|
+
raise _InvalidPositionError
|
|
64
|
+
return position
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _positions(coordinates: object, crs: ResolvedCrs, skipped: Skipped) -> tuple[Position, ...]:
|
|
68
|
+
if not isinstance(coordinates, list):
|
|
69
|
+
raise _InvalidPositionError
|
|
70
|
+
return tuple(_position(item, crs, skipped) for item in coordinates)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _members(coordinates: object) -> list[Any]:
|
|
74
|
+
if not isinstance(coordinates, list):
|
|
75
|
+
raise _InvalidPositionError
|
|
76
|
+
return coordinates
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _simple(
|
|
80
|
+
kind: str, coordinates: object, crs: ResolvedCrs, skipped: Skipped
|
|
81
|
+
) -> Iterator[Geometry]:
|
|
82
|
+
"""Build the geometries of a non collection geometry, which are several for Multi types."""
|
|
83
|
+
iri = crs.iri
|
|
84
|
+
|
|
85
|
+
def rings(value: object) -> tuple[tuple[Position, ...], ...]:
|
|
86
|
+
return tuple(_positions(ring, crs, skipped) for ring in _members(value))
|
|
87
|
+
|
|
88
|
+
match kind:
|
|
89
|
+
case "Point":
|
|
90
|
+
yield Geometry("Point", ((_position(coordinates, crs, skipped),),), iri)
|
|
91
|
+
case "MultiPoint":
|
|
92
|
+
for item in _members(coordinates):
|
|
93
|
+
yield Geometry("Point", ((_position(item, crs, skipped),),), iri)
|
|
94
|
+
case "LineString":
|
|
95
|
+
yield Geometry("LineString", (_positions(coordinates, crs, skipped),), iri)
|
|
96
|
+
case "MultiLineString":
|
|
97
|
+
for item in _members(coordinates):
|
|
98
|
+
yield Geometry("LineString", (_positions(item, crs, skipped),), iri)
|
|
99
|
+
case "Polygon":
|
|
100
|
+
yield Geometry("Polygon", rings(coordinates), iri)
|
|
101
|
+
case _: # MultiPolygon
|
|
102
|
+
for item in _members(coordinates):
|
|
103
|
+
yield Geometry("Polygon", rings(item), iri)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _geometries(geometry: object, crs: ResolvedCrs | None, skipped: Skipped) -> Iterator[Geometry]:
|
|
107
|
+
"""Flatten a geometry into the geometries it consists of, counting what is left out.
|
|
108
|
+
|
|
109
|
+
A geometry with an invalid position is left out as a whole, since dropping a position
|
|
110
|
+
would change its shape.
|
|
111
|
+
"""
|
|
112
|
+
if geometry is None:
|
|
113
|
+
return
|
|
114
|
+
kind = geometry.get("type") if isinstance(geometry, dict) else None
|
|
115
|
+
if not isinstance(geometry, dict) or not isinstance(kind, str) or kind not in _GEOMETRIES:
|
|
116
|
+
skipped["unsupported geometry"] += 1
|
|
117
|
+
return
|
|
118
|
+
if kind == "GeometryCollection":
|
|
119
|
+
members = geometry.get("geometries")
|
|
120
|
+
for member in members if isinstance(members, list) else []:
|
|
121
|
+
yield from _geometries(member, crs, skipped)
|
|
122
|
+
return
|
|
123
|
+
if crs is None:
|
|
124
|
+
skipped["unsupported crs"] += 1
|
|
125
|
+
return
|
|
126
|
+
try:
|
|
127
|
+
# Built completely first, so an invalid position leaves out every part
|
|
128
|
+
built = list(_simple(kind, geometry.get("coordinates"), crs, skipped))
|
|
129
|
+
except _InvalidPositionError:
|
|
130
|
+
skipped["invalid position"] += 1
|
|
131
|
+
return
|
|
132
|
+
if all(is_well_formed(part) for part in built):
|
|
133
|
+
yield from built
|
|
134
|
+
else:
|
|
135
|
+
skipped["invalid geometry"] += 1
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _json(value: object) -> str:
|
|
139
|
+
"""Serialize a nested value as JSON with its decimals as written."""
|
|
140
|
+
if isinstance(value, Decimal):
|
|
141
|
+
return str(value)
|
|
142
|
+
if isinstance(value, dict):
|
|
143
|
+
return "{" + ", ".join(f"{json.dumps(k)}: {_json(v)}" for k, v in value.items()) + "}"
|
|
144
|
+
if isinstance(value, list):
|
|
145
|
+
return "[" + ", ".join(_json(v) for v in value) + "]"
|
|
146
|
+
return json.dumps(value)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _attributes(properties: object) -> list[Attribute]:
|
|
150
|
+
if not isinstance(properties, dict):
|
|
151
|
+
return []
|
|
152
|
+
return [
|
|
153
|
+
Attribute(
|
|
154
|
+
name,
|
|
155
|
+
_json(value) if isinstance(value, dict | list) else value,
|
|
156
|
+
)
|
|
157
|
+
for name, value in properties.items()
|
|
158
|
+
if value is not None
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _label(properties: object) -> str | None:
|
|
163
|
+
"""Return the conventional property `name`, which stays an attribute as well."""
|
|
164
|
+
name = properties.get("name") if isinstance(properties, dict) else None
|
|
165
|
+
return name if isinstance(name, str) and name else None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _identifier(value: object) -> str | None:
|
|
169
|
+
if isinstance(value, str) or (isinstance(value, int | Decimal) and not isinstance(value, bool)):
|
|
170
|
+
return str(value)
|
|
171
|
+
return None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _feature(item: dict[str, Any], crs: ResolvedCrs | None, skipped: Skipped) -> Feature:
|
|
175
|
+
return Feature(
|
|
176
|
+
label=_label(item.get("properties")),
|
|
177
|
+
identifier=_identifier(item.get("id")),
|
|
178
|
+
attributes=_attributes(item.get("properties")),
|
|
179
|
+
geometries=list(_geometries(item.get("geometry"), crs, skipped)),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _resolve_crs(document: dict[str, Any]) -> ResolvedCrs | None:
|
|
184
|
+
"""Resolve the legacy crs member, None if it cannot be interpreted."""
|
|
185
|
+
crs = document.get("crs")
|
|
186
|
+
if crs is None:
|
|
187
|
+
return resolve_geojson_crs(None)
|
|
188
|
+
properties = crs.get("properties") if isinstance(crs, dict) else None
|
|
189
|
+
name = properties.get("name") if isinstance(properties, dict) else None
|
|
190
|
+
return resolve_geojson_crs(name) if isinstance(name, str) else None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _items(document: dict[str, Any], skipped: Skipped) -> Iterator[dict[str, Any]]:
|
|
194
|
+
"""Return the Feature objects of the document, a bare geometry being wrapped in one."""
|
|
195
|
+
match document["type"]:
|
|
196
|
+
case "FeatureCollection":
|
|
197
|
+
members = document.get("features")
|
|
198
|
+
for member in members if isinstance(members, list) else []:
|
|
199
|
+
if isinstance(member, dict) and member.get("type") == "Feature":
|
|
200
|
+
yield member
|
|
201
|
+
else:
|
|
202
|
+
skipped["unsupported element"] += 1
|
|
203
|
+
case "Feature":
|
|
204
|
+
yield document
|
|
205
|
+
case _:
|
|
206
|
+
yield {"geometry": document}
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def parse(stream: IO[bytes], skipped: Skipped) -> Iterator[ParseEvent]:
|
|
210
|
+
"""Read a GeoJSON document as a collection followed by its features.
|
|
211
|
+
|
|
212
|
+
Geometries with an invalid position or point count, of an unsupported type or in an unresolvable
|
|
213
|
+
coordinate reference system are counted in `skipped` and left out of their feature.
|
|
214
|
+
"""
|
|
215
|
+
try:
|
|
216
|
+
yield from _events(stream, skipped)
|
|
217
|
+
except RecursionError as err:
|
|
218
|
+
raise ValueError("the document is nested too deeply") from err
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _events(stream: IO[bytes], skipped: Skipped) -> Iterator[ParseEvent]:
|
|
222
|
+
document = json.loads(stream.read().decode("utf-8-sig"), parse_float=Decimal)
|
|
223
|
+
kind = document.get("type") if isinstance(document, dict) else None
|
|
224
|
+
if not isinstance(kind, str) or kind not in _TYPES:
|
|
225
|
+
raise ValueError(f"expected a GeoJSON object, found type '{kind}'")
|
|
226
|
+
crs = _resolve_crs(document)
|
|
227
|
+
yield Collection(path=())
|
|
228
|
+
for item in _items(document, skipped):
|
|
229
|
+
yield _feature(item, crs, skipped)
|