cmem-plugin-gps 0.5.0__tar.gz

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.
@@ -0,0 +1,176 @@
1
+ # NOTE: this file is shipped inside the source distribution. Hatchling
2
+ # force-includes the VCS ignore file in every sdist and no setting can turn
3
+ # that off, so anything written here is published together with the package -
4
+ # on PyPI too, if the project publishes there. Keep it free of internal host
5
+ # names, customer names and similar.
6
+
7
+ # https://raw.githubusercontent.com/github/gitignore/master/Python.gitignore
8
+ # Byte-compiled / optimized / DLL files
9
+ __pycache__/
10
+ *.py[cod]
11
+ *$py.class
12
+
13
+ # C extensions
14
+ *.so
15
+
16
+ # Distribution / packaging
17
+ .Python
18
+ build/
19
+ develop-eggs/
20
+ dist/
21
+ downloads/
22
+ eggs/
23
+ .eggs/
24
+ lib/
25
+ lib64/
26
+ parts/
27
+ sdist/
28
+ var/
29
+ wheels/
30
+ share/python-wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ *.py,cover
57
+ .hypothesis/
58
+ .pytest_cache/
59
+ cover/
60
+
61
+ # Translations
62
+ *.mo
63
+ *.pot
64
+
65
+ # Django stuff:
66
+ *.log
67
+ local_settings.py
68
+ db.sqlite3
69
+ db.sqlite3-journal
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+
81
+ # PyBuilder
82
+ .pybuilder/
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # IPython
89
+ profile_default/
90
+ ipython_config.py
91
+
92
+ # pyenv
93
+ # For a library or package, you might want to ignore these files since the code is
94
+ # intended to run in multiple environments; otherwise, check them in:
95
+ # .python-version
96
+
97
+ # pipenv
98
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
99
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
100
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
101
+ # install all needed dependencies.
102
+ #Pipfile.lock
103
+
104
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
105
+ __pypackages__/
106
+
107
+ # Celery stuff
108
+ celerybeat-schedule
109
+ celerybeat.pid
110
+
111
+ # SageMath parsed files
112
+ *.sage.py
113
+
114
+ # Environments
115
+ .env
116
+ .venv
117
+ env/
118
+ venv/
119
+ ENV/
120
+ env.bak/
121
+ venv.bak/
122
+
123
+ # Spyder project settings
124
+ .spyderproject
125
+ .spyproject
126
+
127
+ # Rope project settings
128
+ .ropeproject
129
+
130
+ # mkdocs documentation
131
+ /site
132
+
133
+ # mypy
134
+ .mypy_cache/
135
+ .dmypy.json
136
+ dmypy.json
137
+
138
+ # Pyre type checker
139
+ .pyre/
140
+
141
+ # pytype static type analyzer
142
+ .pytype/
143
+
144
+ # Cython debug symbols
145
+ cython_debug/
146
+
147
+ # Claude code specifics
148
+ .claude/settings.local.json
149
+
150
+ # JetBrains IDEs - most of .idea/ is shared, which is what PyCharm's own
151
+ # generated .idea/.gitignore already assumes: vcs.xml, modules.xml, the project
152
+ # .iml, inspectionProfiles/ and runConfigurations/ describe the project, not the
153
+ # machine. These entries follow github/gitignore's Global/JetBrains.gitignore,
154
+ # plus misc.xml, which names the local Python interpreter, and sonarlint/, whose
155
+ # binary index files neither list covers.
156
+ .idea/**/workspace.xml
157
+ .idea/**/tasks.xml
158
+ .idea/**/usage.statistics.xml
159
+ .idea/**/dictionaries
160
+ .idea/**/shelf
161
+ .idea/**/dataSources/
162
+ .idea/**/dataSources.local.xml
163
+ .idea/**/sqlDataSources.xml
164
+ .idea/misc.xml
165
+ .idea/sonarlint/
166
+
167
+ # project build plan specific ignores
168
+ # 'co' is CMEM orchestration output, which is sometimes part of a build plan.
169
+ co
170
+ *.bak
171
+ artifacts
172
+ .DS_Store
173
+ .task
174
+ # uv's package cache, which the gitlab pipeline keeps inside the project so it
175
+ # can be cached between jobs.
176
+ .uv-cache
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright eccenca GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: cmem-plugin-gps
3
+ Version: 0.5.0
4
+ Summary: Import GPS data into eccenca Corporate Memory
5
+ Author-email: eccenca GmbH <cmempy-developer@eccenca.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: eccenca Corporate Memory,plugin
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Plugins
11
+ Requires-Python: <4,>=3.13
12
+ Requires-Dist: cmem-plugin-base<5,>=4.20.0
13
+ Requires-Dist: defusedxml<0.8,>=0.7.1
14
+ Description-Content-Type: text/markdown
15
+
16
+ # cmem-plugin-gps
17
+
18
+ Import GPS and geo data into eccenca Corporate Memory
19
+
20
+ The task **Import GPS and geo data** reads GPX, KML, KMZ, GeoJSON and GML files, for example
21
+ from the **Get project files** task, and turns them into GeoSPARQL RDF. Tracks, routes, waypoints
22
+ and other features become resources with WKT geometries, ready to be written to a knowledge graph.
23
+ Long tracks get a simplified line, so that they can be shown with the map service.
24
+
25
+ [![eccenca Corporate Memory][cmem-shield]][cmem-link]
26
+
27
+ This is a plugin for [eccenca Corporate Memory](https://documentation.eccenca.com). You can install it with the [cmemc](https://eccenca.com/go/cmemc) command line client like this:
28
+
29
+ ```
30
+ cmemc admin workspace python install cmem-plugin-gps
31
+ ```
32
+ [![pypi version](https://img.shields.io/pypi/v/cmem-plugin-gps)](https://pypi.org/project/cmem-plugin-gps) [![license](https://img.shields.io/pypi/l/cmem-plugin-gps)](https://pypi.org/project/cmem-plugin-gps)
33
+ [![uv][uv-shield]][uv-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
34
+
35
+ [cmem-link]: https://documentation.eccenca.com
36
+ [cmem-shield]: https://img.shields.io/endpoint?url=https://documentation.eccenca.com/latest/badge.json
37
+ [uv-link]: https://docs.astral.sh/uv/
38
+ [uv-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json
39
+ [ruff-link]: https://docs.astral.sh/ruff/
40
+ [ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
41
+ [mypy-link]: https://mypy-lang.org/
42
+ [mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
43
+ [copier]: https://copier.readthedocs.io/
44
+ [copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
45
+
@@ -0,0 +1,30 @@
1
+ # cmem-plugin-gps
2
+
3
+ Import GPS and geo data into eccenca Corporate Memory
4
+
5
+ The task **Import GPS and geo data** reads GPX, KML, KMZ, GeoJSON and GML files, for example
6
+ from the **Get project files** task, and turns them into GeoSPARQL RDF. Tracks, routes, waypoints
7
+ and other features become resources with WKT geometries, ready to be written to a knowledge graph.
8
+ Long tracks get a simplified line, so that they can be shown with the map service.
9
+
10
+ [![eccenca Corporate Memory][cmem-shield]][cmem-link]
11
+
12
+ This is a plugin for [eccenca Corporate Memory](https://documentation.eccenca.com). You can install it with the [cmemc](https://eccenca.com/go/cmemc) command line client like this:
13
+
14
+ ```
15
+ cmemc admin workspace python install cmem-plugin-gps
16
+ ```
17
+ [![pypi version](https://img.shields.io/pypi/v/cmem-plugin-gps)](https://pypi.org/project/cmem-plugin-gps) [![license](https://img.shields.io/pypi/l/cmem-plugin-gps)](https://pypi.org/project/cmem-plugin-gps)
18
+ [![uv][uv-shield]][uv-link] [![ruff][ruff-shield]][ruff-link] [![mypy][mypy-shield]][mypy-link] [![copier][copier-shield]][copier]
19
+
20
+ [cmem-link]: https://documentation.eccenca.com
21
+ [cmem-shield]: https://img.shields.io/endpoint?url=https://documentation.eccenca.com/latest/badge.json
22
+ [uv-link]: https://docs.astral.sh/uv/
23
+ [uv-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json
24
+ [ruff-link]: https://docs.astral.sh/ruff/
25
+ [ruff-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&label=Code%20Style
26
+ [mypy-link]: https://mypy-lang.org/
27
+ [mypy-shield]: https://www.mypy-lang.org/static/mypy_badge.svg
28
+ [copier]: https://copier.readthedocs.io/
29
+ [copier-shield]: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/copier-org/copier/master/img/badge/badge-grayscale-inverted-border-purple.json
30
+
@@ -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)
@@ -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)