overture-osm 1.0.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.
- overture_osm-1.0.0/.java-version +1 -0
- overture_osm-1.0.0/.python-version +1 -0
- overture_osm-1.0.0/LICENSE +21 -0
- overture_osm-1.0.0/PKG-INFO +55 -0
- overture_osm-1.0.0/README.md +30 -0
- overture_osm-1.0.0/overture_osm/__init__.py +0 -0
- overture_osm-1.0.0/overture_osm/name_vandalism.py +146 -0
- overture_osm-1.0.0/overture_osm/osm_common.py +385 -0
- overture_osm-1.0.0/overture_osm.egg-info/PKG-INFO +55 -0
- overture_osm-1.0.0/overture_osm.egg-info/SOURCES.txt +23 -0
- overture_osm-1.0.0/overture_osm.egg-info/dependency_links.txt +1 -0
- overture_osm-1.0.0/overture_osm.egg-info/requires.txt +6 -0
- overture_osm-1.0.0/overture_osm.egg-info/scm_file_list.json +20 -0
- overture_osm-1.0.0/overture_osm.egg-info/scm_version.json +8 -0
- overture_osm-1.0.0/overture_osm.egg-info/top_level.txt +1 -0
- overture_osm-1.0.0/pyproject.toml +81 -0
- overture_osm-1.0.0/setup.cfg +4 -0
- overture_osm-1.0.0/tests/__init__.py +0 -0
- overture_osm-1.0.0/tests/conftest.py +25 -0
- overture_osm-1.0.0/tests/test_name_vandalism.py +91 -0
- overture_osm-1.0.0/tests/test_osm_common.py +78 -0
- overture_osm-1.0.0/tests/test_osm_common_sql.py +45 -0
- overture_osm-1.0.0/tests/test_osm_elevation.py +71 -0
- overture_osm-1.0.0/tests/test_osm_names.py +136 -0
- overture_osm-1.0.0/uv.lock +1113 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
17
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.11
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Overture Maps
|
|
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,55 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: overture-osm
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Common OSM-to-Overture SQL helpers shared across theme packages
|
|
5
|
+
Author: Overture Maps Foundation
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/OvertureMaps/overture-osm
|
|
8
|
+
Project-URL: Source, https://github.com/OvertureMaps/overture-osm/tree/main/packages/overture_osm
|
|
9
|
+
Project-URL: Issues, https://github.com/OvertureMaps/overture-osm/issues
|
|
10
|
+
Keywords: overture,overturemaps,openstreetmap,osm,spark
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: overture-core<3.0.0,>=1.4.0
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pyspark>=3.5.0; extra == "dev"
|
|
22
|
+
Requires-Dist: pytest>=9.1.1; extra == "dev"
|
|
23
|
+
Requires-Dist: pytest-cov>=7.0.0; extra == "dev"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# overture-osm
|
|
27
|
+
|
|
28
|
+
[](https://pypi.org/project/overture-osm/)
|
|
29
|
+
[](https://pypi.org/project/overture-osm/)
|
|
30
|
+
|
|
31
|
+
Common SparkSQL helper functions for converting OSM data to Overture format, plus the prompts and SQL builders for the OSM name vandalism check.
|
|
32
|
+
|
|
33
|
+
Shared by `overture_base`, `overture_buildings`, and other theme packages that process [OpenStreetMap](https://www.openstreetmap.org) data. Moved from `tf-data-platform`'s `overture_osm` module; the import path `overture_osm.osm_common` is unchanged.
|
|
34
|
+
|
|
35
|
+
## Modules
|
|
36
|
+
|
|
37
|
+
- `overture_osm.osm_common`: functions that return SparkSQL strings for OSM-to-Overture conversion (names, heights, surfaces, elevation, sources, bbox, lifecycle-prefix deletion checks) and `OvertureNameSpace`, the UUID v3 namespaces per theme. It uses `overture-core`'s `strings_sql` and `uuids_sql`.
|
|
38
|
+
- `overture_osm.name_vandalism`: the Bedrock prompts (`SYSTEM_PROMPT`, `LANGUAGE_DETECTION_PROMPT`) and the Athena/Trino SQL builders (`get_raw_inference_cte`, `get_json_parse_expression`, `get_language_detection_ctes`) the name vandalism check DAG runs. The strings are pinned byte for byte by tests, so any edit is a deliberate change. Table names, S3 paths, thresholds and task functions stay in the DAG.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pip install overture-osm
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Consumers should pin a compatible range, for example `overture-osm>=1.0.0,<2.0.0`.
|
|
47
|
+
|
|
48
|
+
## Development
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
uv sync --extra dev
|
|
52
|
+
uv run pytest -v --cov
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The `osm_names` and `osm_elevation` tests evaluate the generated SQL in a local Spark session, so they need JDK 17 on the machine, the version CI installs.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# overture-osm
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/overture-osm/)
|
|
4
|
+
[](https://pypi.org/project/overture-osm/)
|
|
5
|
+
|
|
6
|
+
Common SparkSQL helper functions for converting OSM data to Overture format, plus the prompts and SQL builders for the OSM name vandalism check.
|
|
7
|
+
|
|
8
|
+
Shared by `overture_base`, `overture_buildings`, and other theme packages that process [OpenStreetMap](https://www.openstreetmap.org) data. Moved from `tf-data-platform`'s `overture_osm` module; the import path `overture_osm.osm_common` is unchanged.
|
|
9
|
+
|
|
10
|
+
## Modules
|
|
11
|
+
|
|
12
|
+
- `overture_osm.osm_common`: functions that return SparkSQL strings for OSM-to-Overture conversion (names, heights, surfaces, elevation, sources, bbox, lifecycle-prefix deletion checks) and `OvertureNameSpace`, the UUID v3 namespaces per theme. It uses `overture-core`'s `strings_sql` and `uuids_sql`.
|
|
13
|
+
- `overture_osm.name_vandalism`: the Bedrock prompts (`SYSTEM_PROMPT`, `LANGUAGE_DETECTION_PROMPT`) and the Athena/Trino SQL builders (`get_raw_inference_cte`, `get_json_parse_expression`, `get_language_detection_ctes`) the name vandalism check DAG runs. The strings are pinned byte for byte by tests, so any edit is a deliberate change. Table names, S3 paths, thresholds and task functions stay in the DAG.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install overture-osm
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Consumers should pin a compatible range, for example `overture-osm>=1.0.0,<2.0.0`.
|
|
22
|
+
|
|
23
|
+
## Development
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
uv sync --extra dev
|
|
27
|
+
uv run pytest -v --cov
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The `osm_names` and `osm_elevation` tests evaluate the generated SQL in a local Spark session, so they need JDK 17 on the machine, the version CI installs.
|
|
File without changes
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Prompts and SQL builders for the OSM name vandalism check.
|
|
2
|
+
|
|
3
|
+
Moved verbatim from the Airflow DAG module so the strings the Athena/Trino
|
|
4
|
+
queries run on live in one tested place.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
SYSTEM_PROMPT = """
|
|
8
|
+
You are a senior map QA analyst, tasked with reviewing name changes to prevent offensive content from being shown to end users.
|
|
9
|
+
These name changes are crowd-sourced from OpenStreetMap and could contain:
|
|
10
|
+
- Profanity (e.g., expletives, cursing, or offensive language)
|
|
11
|
+
- Vulgarity (e.g., sexual, offensive, or inappropriate language)
|
|
12
|
+
- Vandalism (e.g., modifying well-known names or adding fictional references)
|
|
13
|
+
- Private data (e.g., personally identifiable information like "Brad's House", phone numbers, emails)
|
|
14
|
+
- Advertising (e.g., "Call Joe's Bakery at 555 for all your pastries!" but not business names like "Joe's Bakery")
|
|
15
|
+
- Suspicious changes (e.g., significant changes to meaning, typos, misspellings, grammar issues)
|
|
16
|
+
- Meaningless changes (e.g., numbers, random words, symbols, or redundant descriptors)
|
|
17
|
+
|
|
18
|
+
Note that these names can be in any language, not just English. During assessment, please consider diverse political, lingual, socioeconomic and geographic viewpoints in the evaluation.
|
|
19
|
+
|
|
20
|
+
Your task is to provide a response strictly in the form of a valid JSON object with the following structure:
|
|
21
|
+
{"risk_score": 0.0, "label": ""}
|
|
22
|
+
|
|
23
|
+
Response requirements:
|
|
24
|
+
- Output only a valid JSON object with no formatting errors.
|
|
25
|
+
- label must be one of: "profanity", "vulgarity", "vandalism", "suspicious", "private", "advertising", "meaningless", "no_issue"
|
|
26
|
+
- risk_score must be a float between 0.0 (low) and 1.0 (definitely problematic) indicating confidence/severity
|
|
27
|
+
- You SHOULD NOT include any other text in the response.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
LANGUAGE_DETECTION_PROMPT = """
|
|
31
|
+
You are a localization expert. Your task is to determine the language of a map feature name and whether it's appropriate for English speakers.
|
|
32
|
+
|
|
33
|
+
## Detection Rules:
|
|
34
|
+
|
|
35
|
+
### Script Analysis (Check First):
|
|
36
|
+
NON-LATIN SCRIPTS - identify the language:
|
|
37
|
+
- Cyrillic (А-Я, а-я) → "ru", "uk", "bg", "sr", etc. (NOT english_compatible)
|
|
38
|
+
- Greek (Α-Ω, α-ω) → "el" (NOT english_compatible)
|
|
39
|
+
- Arabic script → "ar", "fa", "ur" (NOT english_compatible)
|
|
40
|
+
- Hebrew (א-ת) → "he" (NOT english_compatible)
|
|
41
|
+
- CJK characters → "zh", "ja", "ko" (NOT english_compatible)
|
|
42
|
+
- Hiragana/Katakana → "ja" (NOT english_compatible)
|
|
43
|
+
- Hangul → "ko" (NOT english_compatible)
|
|
44
|
+
- Devanagari → "hi", "sa" (NOT english_compatible)
|
|
45
|
+
- Thai → "th" (NOT english_compatible)
|
|
46
|
+
|
|
47
|
+
### Latin Script Analysis:
|
|
48
|
+
Names in Latin/Roman script ARE english_compatible if:
|
|
49
|
+
- They contain ANY English words mixed with other content
|
|
50
|
+
- They are transliterations readable by English speakers
|
|
51
|
+
- They use standard Latin alphabet (even with light diacritics)
|
|
52
|
+
|
|
53
|
+
### Language Marker Characters (for language identification):
|
|
54
|
+
- "ß" → "de" (German)
|
|
55
|
+
- "ø", "å" → "da" or "no" (Danish/Norwegian)
|
|
56
|
+
- "ł", "ź", "ż" → "pl" (Polish)
|
|
57
|
+
- "ș", "ț" → "ro" (Romanian)
|
|
58
|
+
- "ő", "ű" → "hu" (Hungarian)
|
|
59
|
+
- "ñ" → likely "es" (Spanish)
|
|
60
|
+
- "ç" → "pt", "fr", or "ca"
|
|
61
|
+
|
|
62
|
+
### Word Pattern Analysis:
|
|
63
|
+
- German: "-ung", "-keit", "-heit", "-straße", articles "der/die/das"
|
|
64
|
+
- Portuguese: "-ção", "-ões"
|
|
65
|
+
- Spanish: "-ción", "-mente", articles "el/la/los/las"
|
|
66
|
+
- French: articles "le/la/les/du/des"
|
|
67
|
+
- English indicators: "the", "a", "an", "road", "street", "station", "park", "-tion", "-ness", "-ing"
|
|
68
|
+
|
|
69
|
+
### English Compatibility Rules:
|
|
70
|
+
- Latin script with English words = english_compatible: true
|
|
71
|
+
- Pure transliterations (e.g., "Tokyo Station") = english_compatible: true
|
|
72
|
+
- Latin script foreign names without English = english_compatible: true (readable)
|
|
73
|
+
- Non-Latin scripts = english_compatible: false
|
|
74
|
+
|
|
75
|
+
## Examples:
|
|
76
|
+
- "Shimogamo Shizuhara Ohara Line" → language: "ja", english_compatible: true (transliterated)
|
|
77
|
+
- "Tokyo Station" → language: "en", english_compatible: true
|
|
78
|
+
- "Boulevard Saint-Michel" → language: "fr", english_compatible: true (Latin script)
|
|
79
|
+
- "Rue de la Paix" → language: "fr", english_compatible: true (Latin script, readable)
|
|
80
|
+
- "Hauptstraße" → language: "de", english_compatible: true (Latin script)
|
|
81
|
+
- "Москва" → language: "ru", english_compatible: false (Cyrillic)
|
|
82
|
+
- "東京" → language: "ja", english_compatible: false (CJK)
|
|
83
|
+
|
|
84
|
+
Output as JSON:
|
|
85
|
+
{"language": "<ISO 639-1 code>", "confidence": <0.0-1.0>, "english_compatible": <true/false>}
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ---------------------------------------------------------------------------
|
|
90
|
+
# SQL helper functions
|
|
91
|
+
# ---------------------------------------------------------------------------
|
|
92
|
+
def get_raw_inference_cte(table_name: str, ds: str | None = None) -> str:
|
|
93
|
+
"""Generate SQL CTE to extract prompt and generation from Bedrock inference output."""
|
|
94
|
+
ds_filter = f"\n WHERE ds = '{ds}'" if ds else ""
|
|
95
|
+
return f"""
|
|
96
|
+
raw as (
|
|
97
|
+
SELECT
|
|
98
|
+
COALESCE(
|
|
99
|
+
modelinput.prompt,
|
|
100
|
+
CASE
|
|
101
|
+
WHEN modelinput.messages IS NOT NULL
|
|
102
|
+
THEN ARRAY_JOIN(TRANSFORM(modelinput.messages, x -> x.content), ' ')
|
|
103
|
+
ELSE NULL
|
|
104
|
+
END
|
|
105
|
+
) AS prompt,
|
|
106
|
+
COALESCE(modeloutput.generation, modeloutput.choices[1].message.content) AS generation
|
|
107
|
+
FROM {table_name}{ds_filter}
|
|
108
|
+
)
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def get_json_parse_expression() -> str:
|
|
113
|
+
"""Generate SQL expression to parse JSON from LLM generation output."""
|
|
114
|
+
return """
|
|
115
|
+
try(json_parse(replace(generation, '\\n', '')))
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_language_detection_ctes() -> str:
|
|
120
|
+
"""Generate parsed and extracted CTEs for language detection inference results."""
|
|
121
|
+
return f"""
|
|
122
|
+
parsed as (
|
|
123
|
+
SELECT
|
|
124
|
+
{get_json_parse_expression()} as json_output,
|
|
125
|
+
regexp_extract(prompt, '[nwr]\\d+') as id,
|
|
126
|
+
regexp_extract(generation, '"language":\\s*"([a-z]{{2}})"', 1) as fallback_language,
|
|
127
|
+
regexp_extract(generation, '"english_compatible":\\s*(true|false)', 1) as fallback_english_compatible,
|
|
128
|
+
regexp_extract(generation, '\\d\\.\\d') as fallback_confidence,
|
|
129
|
+
prompt,
|
|
130
|
+
generation as raw_generation
|
|
131
|
+
FROM raw
|
|
132
|
+
),
|
|
133
|
+
extracted as (
|
|
134
|
+
SELECT
|
|
135
|
+
COALESCE(json_extract_scalar(json_output, '$.language'), fallback_language) as language,
|
|
136
|
+
try(cast(COALESCE(json_extract_scalar(json_output, '$.confidence'), fallback_confidence, '0.0') as double)) as confidence,
|
|
137
|
+
COALESCE(
|
|
138
|
+
try(cast(json_extract_scalar(json_output, '$.english_compatible') as boolean)),
|
|
139
|
+
fallback_english_compatible = 'true'
|
|
140
|
+
) as english_compatible,
|
|
141
|
+
id,
|
|
142
|
+
prompt,
|
|
143
|
+
raw_generation
|
|
144
|
+
FROM parsed
|
|
145
|
+
)
|
|
146
|
+
"""
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
"""Common SparkSQL helper functions for OSM-to-Overture conversion."""
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from overture_core.strings_sql import stripped_string_sql
|
|
7
|
+
from overture_core.uuids_sql import generate_uuid3_sql
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class OvertureNameSpace(Enum):
|
|
11
|
+
INFRASTRUCTURE = UUID("a3fbee78-be68-4a26-a099-d5722fbba3cf")
|
|
12
|
+
LAND = UUID("bcd48754-c8c7-4f07-8746-f6c3e0af0945")
|
|
13
|
+
LAND_USE = UUID("e043daee-53fa-4e87-96c5-1b58a74e804e")
|
|
14
|
+
WATER = UUID("3d6a33ba-1abe-4aaa-abcd-5aa7ccb6ca42")
|
|
15
|
+
BATHYMETRY = UUID("aedbcb94-2ca3-4f55-b665-410856b63a66")
|
|
16
|
+
LAND_COVER = UUID("ea180a5d-c662-4b72-8f32-4fc88460d6fd")
|
|
17
|
+
BUILDING_PART = UUID("3482fc70-1cfe-47e7-a341-4971e4fc2037")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
LANGUAGE_REGEXP = r"(?:(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}?)|(?:[A-Za-z]{4,8}))(?:-[A-Za-z]{4})?(?:-[A-Za-z]{2}|[0-9]{3})?(?:-(?:[A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*(?:-[A-WY-Za-wy-z0-9](?:-[A-Za-z0-9]{2,8})+)*$"
|
|
21
|
+
LANG_PSEUDO_NUMBER_REGEXP = r"[a-z]{2}[0-9]+$"
|
|
22
|
+
|
|
23
|
+
OSM_NAME_KEYS_MAPPING = {
|
|
24
|
+
"int_name": "alternate",
|
|
25
|
+
"loc_name": "alternate",
|
|
26
|
+
"nat_name": "alternate",
|
|
27
|
+
"official_name": "official",
|
|
28
|
+
"old_name": "alternate",
|
|
29
|
+
"ref_name": "alternate",
|
|
30
|
+
"reg_name": "alternate",
|
|
31
|
+
"short_name": "short",
|
|
32
|
+
"alt_name": "alternate",
|
|
33
|
+
"nickname": "alternate",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# OSM lifecycle prefixes that indicate a feature no longer exists on the
|
|
37
|
+
# ground (https://wiki.openstreetmap.org/wiki/Lifecycle_prefix). Applied to a
|
|
38
|
+
# tag key, e.g. "building" -> demolished:building=yes.
|
|
39
|
+
OSM_LIFECYCLE_DELETION_PREFIXES = (
|
|
40
|
+
"demolished",
|
|
41
|
+
"razed",
|
|
42
|
+
"destroyed",
|
|
43
|
+
"was",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def osm_lifecycle_deleted_sql(
|
|
48
|
+
key: str = "building",
|
|
49
|
+
tags: str = "tags",
|
|
50
|
+
prefixes: tuple[str, ...] = OSM_LIFECYCLE_DELETION_PREFIXES,
|
|
51
|
+
) -> str:
|
|
52
|
+
"""SparkSQL predicate: tags mark `key` as removed via a lifecycle prefix.
|
|
53
|
+
|
|
54
|
+
True when any `<prefix>:<key>` tag is present with a value other than
|
|
55
|
+
'no' (the value usually carries the old primary value, e.g.
|
|
56
|
+
razed:building=house). NULL (falsy) when no prefixed tag is present, so
|
|
57
|
+
wrap in COALESCE(..., FALSE) before negating.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
key: Tag key the lifecycle prefixes apply to (e.g. "building").
|
|
61
|
+
tags: SQL expression for the tags map column.
|
|
62
|
+
prefixes: Lifecycle prefixes to test; extend for other prefix:key
|
|
63
|
+
combinations as needed.
|
|
64
|
+
"""
|
|
65
|
+
checks = "\n OR ".join(
|
|
66
|
+
f"element_at({tags}, '{prefix}:{key}') <> 'no'" for prefix in prefixes
|
|
67
|
+
)
|
|
68
|
+
return f"({checks})"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def uuid_v3_sql(namespace: str, value_expr: str) -> str:
|
|
72
|
+
"""Generate SparkSQL expression to create a UUID v3.
|
|
73
|
+
|
|
74
|
+
Uses overture-core's RFC 4122 implementation so OSM-derived base features
|
|
75
|
+
retain the UUIDs produced before the Spark ingest migration.
|
|
76
|
+
"""
|
|
77
|
+
ns_uuid = OvertureNameSpace[namespace].value
|
|
78
|
+
return generate_uuid3_sql(ns_uuid, value_expr)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _sql_string_literal(value: str) -> str:
|
|
82
|
+
return "'" + str(value).replace("'", "''") + "'"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def osm_to_overture_sources_sql(
|
|
86
|
+
osm_id="id",
|
|
87
|
+
osm_type="type",
|
|
88
|
+
osm_version="version",
|
|
89
|
+
updated_at="updated_at",
|
|
90
|
+
*,
|
|
91
|
+
pull_date: str,
|
|
92
|
+
provider: str,
|
|
93
|
+
resource: str,
|
|
94
|
+
license_type: str,
|
|
95
|
+
) -> str:
|
|
96
|
+
"""SparkSQL expression to create the Overture sources array from OSM fields.
|
|
97
|
+
|
|
98
|
+
update_time is the OSM feature's last-edited timestamp. version is the
|
|
99
|
+
date the snapshot was pulled from OSM (pull_date, formatted as
|
|
100
|
+
YYYY-MM-DDT00:00:00.000Z). If the feature's update_time is later
|
|
101
|
+
than pull_date (e.g. clock skew or a mid-import edit) version falls
|
|
102
|
+
back to update_time so version >= update_time is always true.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
pull_date: Date string in YYYY-MM-DD format for when the OSM snapshot was pulled.
|
|
106
|
+
provider: OSM source provider label from the caller DAG.
|
|
107
|
+
resource: OSM source resource label from the caller DAG.
|
|
108
|
+
license_type: OSM source license type from the Dataset catalogue.
|
|
109
|
+
"""
|
|
110
|
+
update_time = f"date_format({updated_at}, \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\")"
|
|
111
|
+
pull_ts = f"concat('{pull_date}', 'T00:00:00.000Z')"
|
|
112
|
+
version_expr = f"greatest({pull_ts}, {update_time})"
|
|
113
|
+
provider_literal = _sql_string_literal(provider)
|
|
114
|
+
resource_literal = _sql_string_literal(resource)
|
|
115
|
+
license_literal = _sql_string_literal(license_type)
|
|
116
|
+
|
|
117
|
+
return f"""
|
|
118
|
+
array(
|
|
119
|
+
named_struct(
|
|
120
|
+
'property', '',
|
|
121
|
+
'dataset', 'OpenStreetMap',
|
|
122
|
+
'license', {license_literal},
|
|
123
|
+
'record_id', concat(
|
|
124
|
+
substring({osm_type}, 1, 1),
|
|
125
|
+
cast({osm_id} as string),
|
|
126
|
+
'@',
|
|
127
|
+
cast({osm_version} as string)
|
|
128
|
+
),
|
|
129
|
+
'update_time', {update_time},
|
|
130
|
+
'confidence', cast(null as double),
|
|
131
|
+
'between', cast(null as array<double>),
|
|
132
|
+
'provider', {provider_literal},
|
|
133
|
+
'resource', {resource_literal},
|
|
134
|
+
'version', {version_expr}
|
|
135
|
+
)
|
|
136
|
+
)"""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def clean_name_value_sql(value: str) -> str:
|
|
140
|
+
"""SparkSQL expression to clean a name value.
|
|
141
|
+
|
|
142
|
+
Normalizes every Unicode whitespace character (and U+200B zero-width
|
|
143
|
+
space, which Unicode does not class as White_Space) to a plain space,
|
|
144
|
+
collapses runs of spaces, then strips leading/trailing whitespace and
|
|
145
|
+
control characters and turns an empty result into NULL. The strip is
|
|
146
|
+
`overture_core.strings_sql.stripped_string_sql`, which owns the schema's
|
|
147
|
+
StrippedString boundary rule. The result satisfies that constraint on
|
|
148
|
+
names.primary, names.common values and names.rules[].value.
|
|
149
|
+
"""
|
|
150
|
+
collapsed = rf"""regexp_replace(
|
|
151
|
+
{value},
|
|
152
|
+
'(?U)(\\s|\u200b)+',
|
|
153
|
+
' '
|
|
154
|
+
)"""
|
|
155
|
+
return stripped_string_sql(collapsed)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _generate_rules_when_statements() -> str:
|
|
159
|
+
statements = ""
|
|
160
|
+
for key, variant in OSM_NAME_KEYS_MAPPING.items():
|
|
161
|
+
statements += f"""
|
|
162
|
+
WHEN kv.key = '{key}' OR kv.key rlike '^{key}:{LANGUAGE_REGEXP}' THEN named_struct(
|
|
163
|
+
'variant', '{variant}',
|
|
164
|
+
'language', IF(
|
|
165
|
+
kv.key = '{key}',
|
|
166
|
+
cast(null as string),
|
|
167
|
+
substring(kv.key, length('{key}:') + 1)
|
|
168
|
+
),
|
|
169
|
+
'perspectives', cast(null as struct<mode: string, countries: array<string>>),
|
|
170
|
+
'value', {clean_name_value_sql("kv.value")},
|
|
171
|
+
'between', cast(null as array<double>),
|
|
172
|
+
'side', cast(null as string)
|
|
173
|
+
)"""
|
|
174
|
+
return statements
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _nullif_empty_sql(expr: str) -> str:
|
|
178
|
+
"""SparkSQL equivalent of nullif(collection, empty) since Spark doesn't support = on MAP/ARRAY of structs."""
|
|
179
|
+
return f"if(size({expr}) = 0, null, {expr})"
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def osm_tags_to_names_sql() -> str:
|
|
183
|
+
"""SparkSQL expression to convert OSM tags map to Overture names struct."""
|
|
184
|
+
common_expr = f"""map_filter(
|
|
185
|
+
transform_values(
|
|
186
|
+
transform_keys(
|
|
187
|
+
map_filter(
|
|
188
|
+
tags, (k, v) -> CASE
|
|
189
|
+
WHEN k IN (
|
|
190
|
+
'name:botanical',
|
|
191
|
+
'name:cadastre',
|
|
192
|
+
'name:etymology',
|
|
193
|
+
'name:etymology:wikidata',
|
|
194
|
+
'name:etymology:wikipedia',
|
|
195
|
+
'name:ga:genitive',
|
|
196
|
+
'name:historic',
|
|
197
|
+
'name:int_name',
|
|
198
|
+
'name:language',
|
|
199
|
+
'name:prefix',
|
|
200
|
+
'name:pronunciation',
|
|
201
|
+
'name:signed',
|
|
202
|
+
'name:source',
|
|
203
|
+
'name:start_date',
|
|
204
|
+
'name:statcan_rbuid'
|
|
205
|
+
) THEN FALSE
|
|
206
|
+
WHEN k rlike '^name:{LANG_PSEUDO_NUMBER_REGEXP}' THEN FALSE
|
|
207
|
+
WHEN lower(k) = 'name:ja_kana' AND array_contains(map_keys(tags), 'name:ja-kana') THEN FALSE
|
|
208
|
+
WHEN lower(k) = 'name:ja_hira' AND array_contains(map_keys(tags), 'name:ja-hira') THEN FALSE
|
|
209
|
+
WHEN lower(k) = 'name:zh_pinyin' AND array_contains(map_keys(tags), 'name:zh-pinyin') THEN FALSE
|
|
210
|
+
WHEN lower(k) = 'name:zh_zhuyin' AND array_contains(map_keys(tags), 'name:zh-zhuyin') THEN FALSE
|
|
211
|
+
WHEN lower(k) IN ('name:zh_pinyin', 'name:zh-pinyin') AND array_contains(map_keys(tags), 'name:zh-Latn-pinyin') THEN FALSE
|
|
212
|
+
WHEN lower(k) IN ('name:zh_zhuyin', 'name:zh-zhuyin') AND array_contains(map_keys(tags), 'name:zh-Bopo') THEN FALSE
|
|
213
|
+
WHEN lower(k) = 'name:be-tarask' AND array_contains(map_keys(tags), 'name:be-Latn-tarask') THEN FALSE
|
|
214
|
+
WHEN lower(k) = 'name:nan-poj' AND array_contains(map_keys(tags), 'name:nan-Latn') THEN FALSE
|
|
215
|
+
WHEN k rlike '^name:' THEN TRUE
|
|
216
|
+
ELSE FALSE
|
|
217
|
+
END
|
|
218
|
+
),
|
|
219
|
+
(k, v) -> CASE
|
|
220
|
+
WHEN lower(k) IN ('name:ja_kana', 'name:ja-kana') THEN 'ja-Kana'
|
|
221
|
+
WHEN lower(k) IN ('name:ja_hira', 'name:ja-hira') THEN 'ja-Hira'
|
|
222
|
+
WHEN lower(k) IN ('name:zh_pinyin', 'name:zh-pinyin') THEN 'zh-Latn-pinyin'
|
|
223
|
+
WHEN lower(k) IN ('name:zh_zhuyin', 'name:zh-zhuyin') THEN 'zh-Bopo'
|
|
224
|
+
WHEN lower(k) = 'name:be-tarask' THEN 'be-Latn-tarask'
|
|
225
|
+
WHEN lower(k) = 'name:nan-poj' THEN 'nan-Latn'
|
|
226
|
+
ELSE substring(k, 6)
|
|
227
|
+
END
|
|
228
|
+
),
|
|
229
|
+
(k, v) -> {clean_name_value_sql("v")}
|
|
230
|
+
),
|
|
231
|
+
(k, v) -> CASE
|
|
232
|
+
WHEN v = '' THEN FALSE
|
|
233
|
+
WHEN v IS NULL THEN FALSE
|
|
234
|
+
WHEN k rlike '^{LANGUAGE_REGEXP}' THEN TRUE
|
|
235
|
+
ELSE FALSE
|
|
236
|
+
END
|
|
237
|
+
)"""
|
|
238
|
+
|
|
239
|
+
rules_expr = f"""filter(
|
|
240
|
+
transform(
|
|
241
|
+
map_entries(tags),
|
|
242
|
+
kv -> CASE
|
|
243
|
+
{_generate_rules_when_statements()}
|
|
244
|
+
END
|
|
245
|
+
),
|
|
246
|
+
x -> x IS NOT NULL AND x.value IS NOT NULL
|
|
247
|
+
)"""
|
|
248
|
+
|
|
249
|
+
return f"""
|
|
250
|
+
named_struct(
|
|
251
|
+
'primary', {clean_name_value_sql("element_at(tags, 'name')")},
|
|
252
|
+
'common', {_nullif_empty_sql(common_expr)},
|
|
253
|
+
'rules', {_nullif_empty_sql(rules_expr)}
|
|
254
|
+
)"""
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def source_tags_filter_sql() -> str:
|
|
258
|
+
"""SparkSQL expression to filter source tags."""
|
|
259
|
+
return """
|
|
260
|
+
map_filter(tags, (k, v) -> k NOT IN ('wikidata', 'layer') AND k NOT LIKE 'name%')"""
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def wikidata_tag_sql() -> str:
|
|
264
|
+
# Use [0-9] instead of \d: Spark SQL consumes backslash escapes in string
|
|
265
|
+
# literals, so '\\d' would reach the regex engine as literal 'd'.
|
|
266
|
+
return (
|
|
267
|
+
"""nullif(regexp_extract(element_at(tags, 'wikidata'), '^(Q[0-9]+)', 1), '')"""
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def osm_layer_to_level_sql() -> str:
|
|
272
|
+
return """try_cast(element_at(tags, 'layer') AS int)"""
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def height_case_sql(value: str) -> str:
|
|
276
|
+
return f"""
|
|
277
|
+
(CASE
|
|
278
|
+
WHEN {value} rlike '^\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*$'
|
|
279
|
+
THEN try_cast({value} AS DOUBLE)
|
|
280
|
+
WHEN {value} rlike '^\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*(m|meter|metre)s?\\\\s*$' THEN
|
|
281
|
+
try_cast(regexp_extract({value}, '\\\\d+(\\\\.\\\\d+)?', 0) AS DOUBLE)
|
|
282
|
+
WHEN {value} rlike '^\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*(''|ft|feet)\\\\s*$' THEN
|
|
283
|
+
round(try_cast(regexp_extract({value}, '\\\\d+(\\\\.\\\\d+)?', 0) AS DOUBLE) * 0.3048, 2)
|
|
284
|
+
WHEN {value} rlike '^\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*''\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*"\\\\s*$' THEN (
|
|
285
|
+
round(
|
|
286
|
+
(
|
|
287
|
+
try_cast(regexp_extract({value}, '\\\\s*\\\\d*(\\\\.\\\\d+)?', 0) AS DOUBLE) * 12 +
|
|
288
|
+
try_cast(regexp_extract(regexp_extract({value}, '\\\\d*(\\\\.\\\\d*)?\\\\s*"', 0), '\\\\d*(\\\\.\\\\d+)?', 0) AS DOUBLE)
|
|
289
|
+
) * 0.0254, 2
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
WHEN {value} rlike '^\\\\s*\\\\d+(\\\\.\\\\d*)?\\\\s*"\\\\s*$' THEN
|
|
293
|
+
round(try_cast(regexp_extract({value}, '\\\\d+(\\\\.\\\\d+)?', 0) AS DOUBLE) * 0.0254, 2)
|
|
294
|
+
ELSE NULL
|
|
295
|
+
END)"""
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def height_transform_sql(value: str) -> str:
|
|
299
|
+
return f"""
|
|
300
|
+
(CASE
|
|
301
|
+
WHEN {height_case_sql(value)} > 0 THEN {height_case_sql(value)} ELSE NULL
|
|
302
|
+
END)"""
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def osm_surface_tag_transform_sql() -> str:
|
|
306
|
+
return """
|
|
307
|
+
CASE
|
|
308
|
+
WHEN element_at(tags,'leisure') IN ('pitch', 'playground', 'track', 'stadium') OR element_at(tags,'sport') IS NOT NULL THEN CASE
|
|
309
|
+
WHEN element_at(tags,'natural') = 'sand' OR element_at(tags,'surface') IN (
|
|
310
|
+
'dirt', 'earth', 'fine_gravel', 'gravel', 'ground', 'unpaved', 'sand'
|
|
311
|
+
) OR element_at(tags,'golf') IN ('bunker') THEN 'recreation_sand'
|
|
312
|
+
WHEN element_at(tags,'surface') IN ('artificial_turf', 'grass', 'grass_paver')
|
|
313
|
+
THEN 'recreation_grass'
|
|
314
|
+
WHEN element_at(tags,'surface') IN (
|
|
315
|
+
'acrylic', 'asphalt', 'clay', 'compacted', 'concrete', 'hard', 'paved'
|
|
316
|
+
) THEN 'recreation_paved'
|
|
317
|
+
WHEN element_at(tags,'surface') IS NULL AND element_at(tags,'sport') IN ('basketball')
|
|
318
|
+
THEN 'recreation_paved'
|
|
319
|
+
WHEN element_at(tags,'surface') IS NULL AND element_at(tags,'sport') IN ('soccer', 'football')
|
|
320
|
+
THEN 'recreation_grass'
|
|
321
|
+
END
|
|
322
|
+
WHEN element_at(tags,'golf') = 'bunker' THEN 'recreation_sand'
|
|
323
|
+
WHEN element_at(tags,'surface') IN (
|
|
324
|
+
'asphalt', 'cobblestone', 'compacted', 'concrete', 'dirt', 'earth',
|
|
325
|
+
'fine_gravel', 'grass', 'gravel', 'ground', 'paved', 'paving_stones',
|
|
326
|
+
'pebblestone', 'recreation_grass', 'recreation_paved', 'recreation_sand',
|
|
327
|
+
'rubber', 'sand', 'sett', 'tartan', 'unpaved', 'wood', 'woodchips'
|
|
328
|
+
) THEN element_at(tags,'surface')
|
|
329
|
+
WHEN element_at(tags,'surface') = 'concrete:plates' THEN 'concrete_plates'
|
|
330
|
+
ELSE NULL
|
|
331
|
+
END"""
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def osm_elevation_tag_transform_sql() -> str:
|
|
335
|
+
return f"""
|
|
336
|
+
CASE
|
|
337
|
+
WHEN element_at(tags,'ele') rlike '^\\\\s*\\\\d*(\\\\.\\\\d*)?\\\\s*(m|meter|metre)?s?\\\\s*$' THEN
|
|
338
|
+
IF(
|
|
339
|
+
try_cast(regexp_extract(element_at(tags,'ele'), '\\\\d+(\\\\.\\\\d+)?', 0) AS DOUBLE) < 8850,
|
|
340
|
+
cast(round(try_cast(regexp_extract(element_at(tags,'ele'), '\\\\d+(\\\\.\\\\d+)?', 0) AS DOUBLE)) AS INTEGER),
|
|
341
|
+
NULL
|
|
342
|
+
)
|
|
343
|
+
ELSE NULL
|
|
344
|
+
END"""
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# Float32 bbox rounding factors. Casting a double bound to float32 may land on
|
|
348
|
+
# the wrong side of the original value; nudge by one float32 mantissa ULP
|
|
349
|
+
# toward the correct side.
|
|
350
|
+
_RND_TOWARDS_ZERO = "0.9999998807907104" # 1 - 2**-23
|
|
351
|
+
_RND_AWAY_FROM_ZERO = "1.0000001192092896" # 1 + 2**-23
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _next_float_below_sql(value: str) -> str:
|
|
355
|
+
return f"""(CASE
|
|
356
|
+
WHEN CAST({value} AS FLOAT) > {value} AND {value} < 0
|
|
357
|
+
THEN CAST({value} * {_RND_AWAY_FROM_ZERO} AS FLOAT)
|
|
358
|
+
WHEN CAST({value} AS FLOAT) > {value}
|
|
359
|
+
THEN CAST({value} * {_RND_TOWARDS_ZERO} AS FLOAT)
|
|
360
|
+
ELSE CAST({value} AS FLOAT)
|
|
361
|
+
END)"""
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _next_float_above_sql(value: str) -> str:
|
|
365
|
+
return f"""(CASE
|
|
366
|
+
WHEN CAST({value} AS FLOAT) < {value} AND {value} < 0
|
|
367
|
+
THEN CAST({value} * {_RND_TOWARDS_ZERO} AS FLOAT)
|
|
368
|
+
WHEN CAST({value} AS FLOAT) < {value}
|
|
369
|
+
THEN CAST({value} * {_RND_AWAY_FROM_ZERO} AS FLOAT)
|
|
370
|
+
ELSE CAST({value} AS FLOAT)
|
|
371
|
+
END)"""
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def bbox_from_geometry_sql(geometry: str = "ST_GeomFromWKB(geometry)") -> str:
|
|
375
|
+
"""SparkSQL expression: Overture bbox struct from a Sedona geometry.
|
|
376
|
+
|
|
377
|
+
Bounds are float32, rounded outward so the float bbox always contains
|
|
378
|
+
the double-precision geometry.
|
|
379
|
+
"""
|
|
380
|
+
return f"""named_struct(
|
|
381
|
+
'xmin', {_next_float_below_sql(f"ST_XMin({geometry})")},
|
|
382
|
+
'xmax', {_next_float_above_sql(f"ST_XMax({geometry})")},
|
|
383
|
+
'ymin', {_next_float_below_sql(f"ST_YMin({geometry})")},
|
|
384
|
+
'ymax', {_next_float_above_sql(f"ST_YMax({geometry})")}
|
|
385
|
+
)"""
|