Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ Easiest way to learn about it, is starting with an existing transformation using

E.g. you could start with the following to example transformations (which might not exactly reflect the latest code version of this project):

* https://try.jsonata.org/Gk5r-kLek: Mapping DATEX3.7LiteJSON to DATEX2MostlyFlatGeoJSON (Current JSONata expression is in datex2_xml2json/transform/jsonata_transformer.py)
* https://try.jsonata.org/QEnqmItyF: Mapping DATEX2MostlyFlatGeoJSON to (mostly) WAZE CIFS (Current JSONata expression is in datex2_xml2json/transform/cifs_transformer.py)
* https://try.jsonata.org/Gk5r-kLek: Mapping DATEX3.7LiteJSON to DATEX2MostlyFlatGeoJSON (Current JSONata expression is in `src/datex2_xml2json/transform/jsonata_transformer.py`)
* https://try.jsonata.org/QEnqmItyF: Mapping DATEX2MostlyFlatGeoJSON to (mostly) WAZE CIFS (Current JSONata expression is in `src/datex2_xml2json/transform/cifs_transformer.py`)

### Running tests

Expand Down
26 changes: 14 additions & 12 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
[build-system]
requires = ["uv_build >= 0.12.19"]
requires = ["uv_build >= 0.12.19, <1"]
build-backend = "uv_build"

[tool.uv.build-backend]
source-exclude = [".DS_Store"]

[project]
name = "datex2-xml2json"
# The version is bumped from the git tag in CI via `uv version` on release; see .github/workflows/test_build_and_publish.yml
Expand All @@ -24,23 +27,21 @@ license = "EUPL-1.2"
license-files = ["LICENSE.md"]

dependencies = [
"jsonschema>=4.26.0",
"check-jsonschema>=0.38.2",
"jsonata-python>=0.7.0",
"geoparquet-io>=1.6.0",
"pyarrow>=26.0.0",
"rs-xml2json>=0.2.0"
"jsonschema>=4.26,<5",
"check-jsonschema>=0.38,<1",
"jsonata-python>=0.7.0,<1",
"geoparquet-io>=1.7,<2",
"pyarrow>=26,<27",
"rs-xml2json~=0.2.0"
]

# Development and test dependencies (PEP 735 dependency group, installed by `uv sync`).
[dependency-groups]
dev = [
"pytest~=9.1.1",
"pytest>=9.1.1,<10",
"ruff~=0.17.2",
"mypy~=2.3.1",
"pre-commit>=4.3.0",
"types-shapely~=2.1.0.20260728",
"pyarrow-stubs~=20.0.0.20260819",
"pre-commit>=4.3.0,<5"
]

[project.urls]
Expand Down Expand Up @@ -130,6 +131,7 @@ testpaths = ["tests"]

[tool.mypy]
python_version = "3.12"
strict = true

[[tool.mypy.overrides]]
module = [
Expand All @@ -144,6 +146,6 @@ module = [
"geoparquet_io",
"rs_xml2json",
"pyarrow",
"shapely.geometry",
"pyarrow.parquet",
]
ignore_missing_imports = true
9 changes: 6 additions & 3 deletions src/datex2_xml2json/json_validator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

from check_jsonschema.checker import SchemaChecker
from check_jsonschema.file_wrapper import BinaryFileInput
from check_jsonschema.formats import FormatOptions
Expand All @@ -8,7 +10,7 @@


class JsonValidator:
def __init__(self, schema_path):
def __init__(self, schema_path: str) -> None:
self.schema_loader = SchemaLoader(
schema_path,
disable_cache=False,
Expand All @@ -20,7 +22,7 @@ def build_reporter(self, output_format: str, verbosity: int) -> Reporter:
cls = REPORTER_BY_NAME[output_format]
return cls(verbosity=verbosity)

def validate(self, filename):
def validate(self, filename: str | Path) -> int:
checker = SchemaChecker(
schema_loader=self.schema_loader,
instance_loader=InstanceLoader([BinaryFileInput(filename)]),
Expand All @@ -33,4 +35,5 @@ def validate(self, filename):
regex_impl=RegexImplementation(RegexVariantName.default),
)

return checker.run()
result: int = checker.run()
return result
Empty file added src/datex2_xml2json/py.typed
Empty file.
5 changes: 3 additions & 2 deletions src/datex2_xml2json/transform/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .base import (
AbstractTransformer as AbstractTransformer,
TransformerPipeline as TransformerPipeline,
RulesTransformer as RulesTransformer,
)
Expand All @@ -9,5 +10,5 @@
GeoJSONGeometryTransformer as GeoJSONGeometryTransformer,
)
from .geoparquet_transformer import GeoparquetRenderer as GeoparquetRenderer
from .cifs_transformer import CifsTransformer
from .source_setter import SourceSetter
from .cifs_transformer import CifsTransformer as CifsTransformer
from .source_setter import SourceSetter as SourceSetter
30 changes: 17 additions & 13 deletions src/datex2_xml2json/transform/base.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
from datex2_xml2json.util import replace, xpath_dict
from typing import Self

from datex2_xml2json.util import JsonDict, replace, xpath_dict

from .transformation_rules import TransformationRules


class AbstractTransformer:
def transform(self, a_dict: dict) -> dict:
def transform(self, a_dict: JsonDict) -> JsonDict:
return a_dict


class TransformerPipeline(AbstractTransformer):
def __init__(self, transformers: list[AbstractTransformer]):
def __init__(self, transformers: list[AbstractTransformer]) -> None:
self.transformers = list(transformers)

def add_transformer(self, transformer: AbstractTransformer):
def add_transformer(self, transformer: AbstractTransformer) -> Self:
self.transformers.append(transformer)
return self

def transform(self, a_dict: dict) -> dict:
def transform(self, a_dict: JsonDict) -> JsonDict:
result = a_dict
for t in self.transformers:
result = t.transform(result)
Expand All @@ -28,15 +30,15 @@ class RulesTransformer(AbstractTransformer):
def __init__(self, rules: TransformationRules):
self.rules = rules

def transform(self, a_dict: dict) -> dict:
def transform(self, a_dict: JsonDict) -> JsonDict:
# Transforms the result of xml2json transformation into DATEXIIv3 json.
# This includes:
# * renamings of certain properties according to v2 to v3 name changes
# * renamings of certain properties according to changed writing in json
# * casts values of certain properties to intended types
# * ...

return replace(
result: JsonDict = replace(
a_dict,
None,
self.rules.renamings,
Expand All @@ -46,29 +48,31 @@ def transform(self, a_dict: dict) -> dict:
self.rules.keys_to_pull_up,
)

return result


class ProcessingTransformer(AbstractTransformer):
def __init__(self, xpath: str):
def __init__(self, xpath: str) -> None:
self.xpath = xpath

def transform(self, a_dict: dict) -> dict:
def transform(self, a_dict: JsonDict) -> JsonDict:
for elem in xpath_dict(a_dict, self.xpath):
self.process(elem)

return a_dict

def process(self, a_dict: dict):
def process(self, a_dict: JsonDict) -> None:
pass


class SituationRecordTransformer(ProcessingTransformer):
def __init__(self, xpath: str):
def __init__(self, xpath: str) -> None:
super().__init__(xpath)

def process_situation_record(self, situation_record: dict) -> None:
def process_situation_record(self, situation_record: JsonDict) -> None:
pass

def process(self, situation_record_wrapper: dict) -> None:
def process(self, situation_record_wrapper: JsonDict) -> None:
if isinstance(situation_record_wrapper, dict) and len(situation_record_wrapper) == 1:
situation_record = situation_record_wrapper.get(next(iter(situation_record_wrapper.keys())))
else:
Expand Down
53 changes: 29 additions & 24 deletions src/datex2_xml2json/transform/cifs_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import logging
import re

from datex2_xml2json.util import JsonDict

from .jsonata_transformer import JsonataTransformer

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -58,7 +60,7 @@
"DisturbanceActivity": "CHIT_CHAT",
"TransitInformation": "CHIT_CHAT"
};
$lookup($typeBySubtypeLookup , properties.situationRecordSubtype)?:$lookup($typeLookup , properties.type)?:"TODO"),
$lookup($typeBySubtypeLookup , properties.situationRecordSubtype)?:$lookup($typeLookup , properties.type)?:"HAZARD"),
"subtype": (
$subtypeByTypeLookup := {
/* Accident (no subtypes, as DATEXII does not provide accident severity) */
Expand Down Expand Up @@ -134,6 +136,12 @@
}
"""

# In case multiple incidents describe the same situation, usually because of an caused/effect relation,
# we pick the incident, whose type/subtype are ranked highest (most informative/important)
DEFAULT_INCIDENT_PRIORITY = 1
TYPE_PRIORITIES = {'ROAD_CLOSED': 10, 'ACCIDENT': 9, 'JAM': 8, 'HAZARD': 7, 'POLICE': 2, 'CHIT_CHAT': 1}
SUBTYPE_PRIORITIES = {'ROAD_CLOSED': 10, 'ACCIDENT': 9, 'JAM': 8, 'HAZARD': 7, 'POLICE': 2, 'CHIT_CHAT': 1}


class CifsTransformer(JsonataTransformer):
# This pattern is used to exract the common ID prefix of all situation records which
Expand All @@ -143,11 +151,11 @@ class CifsTransformer(JsonataTransformer):
# 2. Any string/char prefix followed by dot + number
situation_record_group_prefix_regexp = r'^(\d+-\d\d\d\dV\d+)$|^(\d+-\d+-\d+-\d+-gegen).*|^(\d+-\d+-\d+-\d+).*|^(.*)\.\d+$'

def __init__(self, **kwargs):
def __init__(self) -> None:
super().__init__(cifs_expression)

def _group_by_common_situation_record_id_substring(self, incidents, pattern):
grouped_incidents = {}
def _group_by_common_situation_record_id_substring(self, incidents: list[JsonDict], pattern: str) -> dict[str, list[JsonDict]]:
grouped_incidents: dict[str, list[JsonDict]] = {}
p = re.compile(pattern)

for incident in incidents:
Expand All @@ -163,19 +171,13 @@ def _group_by_common_situation_record_id_substring(self, incidents, pattern):

return grouped_incidents

def _get_type_sub_type_prio(self, incident):
if incident.get('type') == 'ROAD_CLOSED':
return 10
if incident.get('subtype') == 'HAZARD_ON_ROAD_LANE_CLOSED':
return 4
if incident.get('subtype') == 'HAZARD_ON_ROAD_CONSTRUCTION':
return 3
if incident.get('subtype') == 'HAZARD_ON_ROAD' or incident.get('type') in ['CHIT_CHAT']:
return 1
Comment thread
the-infinity marked this conversation as resolved.
Resolved
else:
return 2
def _get_type_sub_type_prio(self, incident: JsonDict) -> int:
return max(
TYPE_PRIORITIES.get(str(incident.get('type')), DEFAULT_INCIDENT_PRIORITY),
SUBTYPE_PRIORITIES.get(str(incident.get('subtype')), DEFAULT_INCIDENT_PRIORITY),
)

def _merge_incident_group(self, incident_group):
def _merge_incident_group(self, incident_group: list[JsonDict]) -> JsonDict:
# Assumptions: besides type and subtype, all properties are assumed to be equals
# (TODO: we might check this explicitly)
#
Expand All @@ -184,38 +186,41 @@ def _merge_incident_group(self, incident_group):
# * highest priority subtype/type wins
# TODO: subtype for road_closed to be set according to other incidents
# TODO: should jam be communicated in addition?
if not incident_group:
raise ValueError('incident_group must not be empty')

highest_prio = None
highest_prio_type = None
highest_prio_subtype = None
highest_prio_incident = None
highest_prio_incident: JsonDict = incident_group[0]

for incident in incident_group:
current_prio = self._get_type_sub_type_prio(incident)
if highest_prio is None or current_prio > highest_prio:
logger.debug(
f'For {incident["id"]}, replace {highest_prio} {highest_prio_type} {highest_prio_subtype}'
f' by {incident["type"]} {incident.get("subtype")}'
f' by {incident.get("type")} {incident.get("subtype")}'
)
highest_prio = current_prio
highest_prio_type = incident['type']
highest_prio_type = incident.get('type')
highest_prio_subtype = incident.get('subtype')
highest_prio_incident = incident
else:
logger.debug(
f'For {incident["id"]}, do not replace {highest_prio} {highest_prio_type} {highest_prio_subtype}'
f' by {incident["type"]} {incident.get("subtype")}'
f' by {incident.get("type")} {incident.get("subtype")}'
)
return highest_prio_incident

def _transform_polyline_geom(self, linestring_coordinates) -> str:
def _transform_polyline_geom(self, linestring_coordinates: list[list[float]]) -> str:
"""
Converts GeoJSON linestring coordinates array into CIFS polyline string.
The list of lon/lat coords (like [[10.0, 49.0], [11.0, 49.0]]) is converted into a
lat/lon ordered string ("49.0 10.0 49.0 11.0").
"""
return ' '.join([f'{coords[1]} {coords[0]}' for coords in linestring_coordinates])

def _transform_incident_geometry(self, incident: dict) -> list[dict]:
def _transform_incident_geometry(self, incident: JsonDict) -> list[JsonDict]:
"""
Converts GeoJSON geometry of incident into a CIFS polyline.
As the GeoJSON geometry might be a MultiLineString, we return an array
Expand Down Expand Up @@ -248,7 +253,7 @@ def _transform_incident_geometry(self, incident: dict) -> list[dict]:

return [incident]

def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents):
def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents: dict[str, list[JsonDict]]) -> list[JsonDict]:
incidents = []
for key in grouped_incidents:
try:
Expand All @@ -260,7 +265,7 @@ def _merge_grouped_incidents_and_handle_geometry(self, grouped_incidents):

return incidents

def post_transform(self, a_dict: dict) -> dict:
def post_transform(self, a_dict: JsonDict) -> JsonDict:
"""
Retains the most expressive incident of a group of incidents describing
the same situation.
Expand Down
Loading
Loading