Skip to content

ratiopath.parsers.Darwin7JSONParser

Parser for Darwin7 JSON format annotation files.

Extracts geometries and metadata from Darwin JSON structures into a GeoDataFrame. Supports Polygon, Point, and bounding box geometries. Expected JSON schema:

Root
└── annotations (list)
    ├── Feature (Polygon)
       ├── id: "uuid"
       ├── name: "class_name"
       ├── properties: [...] or {...}
       ├── slot_names: [...]
       └── polygon
           └── paths: [ [ {x, y}, ... ], [holes...] ]
    ├── Feature (Bounding Box)
       ├── id: "uuid"
       └── bounding_box: {x, y, w, h}
    └── Feature (Point)
        ├── id: "uuid"
        └── point: {x, y}

Source code in ratiopath/parsers/darwin7_json_parser.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
class Darwin7JSONParser:
    """Parser for Darwin7 JSON format annotation files.

    Extracts geometries and metadata from Darwin JSON structures into a GeoDataFrame.
    Supports Polygon, Point, and bounding box geometries.
    Expected JSON schema:
    ```bash
    Root
    └── annotations (list)
        ├── Feature (Polygon)
        │   ├── id: "uuid"
        │   ├── name: "class_name"
        │   ├── properties: [...] or {...}
        │   ├── slot_names: [...]
        │   └── polygon
        │       └── paths: [ [ {x, y}, ... ], [holes...] ]
        ├── Feature (Bounding Box)
        │   ├── id: "uuid"
        │   └── bounding_box: {x, y, w, h}
        └── Feature (Point)
            ├── id: "uuid"
            └── point: {x, y}
    ```
    """

    def __init__(self, file_path: Path | str | TextIO) -> None:
        if isinstance(file_path, str | Path):
            with open(file_path, encoding="utf-8") as f:
                data = json.load(f)
        else:
            data = json.load(file_path)

        records = []
        for ann in data.get("annotations", []):
            props = ann.get("properties", [])
            records.append(
                {
                    "id": ann.get("id"),
                    "name": ann.get("name"),
                    "properties": json.dumps(props)
                    if isinstance(props, list | dict)
                    else props,
                    "slot_names": json.dumps(ann.get("slot_names", [])),
                    "geometry": self._parse_geometry(ann),
                }
            )

        if records:
            self.gdf = GeoDataFrame(pd.DataFrame(records), geometry="geometry")
        else:
            self.gdf = GeoDataFrame(
                columns=["id", "name", "properties", "slot_names", "geometry"],
                geometry="geometry",
            )

    @staticmethod
    def _parse_geometry(ann: dict[str, Any]) -> BaseGeometry | None:
        """Construct Shapely geometry objects from Darwin annotation dictionaries."""
        if "polygon" in ann:
            paths = ann["polygon"].get("paths", [])
            if paths:
                exterior = [(pt["x"], pt["y"]) for pt in paths[0]]
                holes = [
                    [(pt["x"], pt["y"]) for pt in hole]
                    for hole in paths[1:]
                    if len(hole) >= 3
                ]
                if len(exterior) >= 3:
                    return Polygon(exterior, holes)
        elif "bounding_box" in ann:
            bbox = ann["bounding_box"]
            return box(
                bbox["x"], bbox["y"], bbox["x"] + bbox["w"], bbox["y"] + bbox["h"]
            )
        elif "point" in ann:
            return Point(ann["point"]["x"], ann["point"]["y"])

        return None

    @staticmethod
    def extract_nested(val: Any, path: list[str]) -> Any:
        """Extract a nested value from a JSON-like structure using a list of keys."""
        if isinstance(val, str):
            try:
                val = json.loads(val)
            except json.JSONDecodeError:
                return None
        for key in path:
            if isinstance(val, dict) and key in val:
                val = val[key]
            elif isinstance(val, list) and key.isdigit():
                idx = int(key)
                if idx < len(val):
                    val = val[idx]
                else:
                    return None
            else:
                return None
        return val

    def get_filtered_geodataframe(
        self, separator: str = "_", **kwargs: str
    ) -> GeoDataFrame:
        """Filter the GeoDataFrame based on property values.

        Supports filtering by top-level columns or nested attributes within JSON-like
        columns (e.g., 'properties'). Nested keys are accessed by joining column
        names and keys with the separator.

        Args:
            separator: String used to separate nested keys in kwargs.
            **kwargs: Keyword arguments where keys represent (possibly nested)
                columns and values are regex patterns to match.

        Returns:
            A GeoDataFrame containing only the rows that match all filter criteria.
            If a requested top-level column is missing, an empty GeoDataFrame
            with the original schema is returned.
        """
        filtered_gdf = self.gdf

        for key, pattern in kwargs.items():
            subkeys = key.split(separator)
            if not subkeys or subkeys[0] not in filtered_gdf.columns:
                return self.gdf.iloc[0:0]

            series = filtered_gdf[subkeys[0]]

            if len(subkeys) > 1:
                series = series.apply(
                    lambda x, sk=subkeys[1:]: self.extract_nested(x, sk)
                )
                mask = series.notna()
                filtered_gdf = filtered_gdf[mask]
                series = series[mask]

            if filtered_gdf.empty:
                return filtered_gdf

            series = series.astype(str)
            mask = series.str.match(pattern, na=False)
            filtered_gdf = filtered_gdf[mask]

        return filtered_gdf

    def get_polygons(self, **kwargs: str) -> Iterable[Polygon]:
        """Get polygons from the GeoDataFrame.

        Args:
            **kwargs: Keyword arguments containing regex patterns for filtering properties.

        Yields:
            Shapely Polygon objects.
        """
        filtered_gdf = self.get_filtered_geodataframe(**kwargs)
        yield from filtered_gdf[filtered_gdf.geom_type == "Polygon"].geometry

    def get_points(self, **kwargs: str) -> Iterable[Point]:
        """Get points from the GeoDataFrame.

        Args:
            **kwargs: Keyword arguments containing regex patterns for filtering properties.

        Yields:
            Shapely Point objects.
        """
        filtered_gdf = self.get_filtered_geodataframe(**kwargs)
        yield from filtered_gdf[filtered_gdf.geom_type == "Point"].geometry

gdf = GeoDataFrame(pd.DataFrame(records), geometry='geometry') instance-attribute

__init__(file_path)

Source code in ratiopath/parsers/darwin7_json_parser.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def __init__(self, file_path: Path | str | TextIO) -> None:
    if isinstance(file_path, str | Path):
        with open(file_path, encoding="utf-8") as f:
            data = json.load(f)
    else:
        data = json.load(file_path)

    records = []
    for ann in data.get("annotations", []):
        props = ann.get("properties", [])
        records.append(
            {
                "id": ann.get("id"),
                "name": ann.get("name"),
                "properties": json.dumps(props)
                if isinstance(props, list | dict)
                else props,
                "slot_names": json.dumps(ann.get("slot_names", [])),
                "geometry": self._parse_geometry(ann),
            }
        )

    if records:
        self.gdf = GeoDataFrame(pd.DataFrame(records), geometry="geometry")
    else:
        self.gdf = GeoDataFrame(
            columns=["id", "name", "properties", "slot_names", "geometry"],
            geometry="geometry",
        )

extract_nested(val, path) staticmethod

Extract a nested value from a JSON-like structure using a list of keys.

Source code in ratiopath/parsers/darwin7_json_parser.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@staticmethod
def extract_nested(val: Any, path: list[str]) -> Any:
    """Extract a nested value from a JSON-like structure using a list of keys."""
    if isinstance(val, str):
        try:
            val = json.loads(val)
        except json.JSONDecodeError:
            return None
    for key in path:
        if isinstance(val, dict) and key in val:
            val = val[key]
        elif isinstance(val, list) and key.isdigit():
            idx = int(key)
            if idx < len(val):
                val = val[idx]
            else:
                return None
        else:
            return None
    return val

get_filtered_geodataframe(separator='_', **kwargs)

Filter the GeoDataFrame based on property values.

Supports filtering by top-level columns or nested attributes within JSON-like columns (e.g., 'properties'). Nested keys are accessed by joining column names and keys with the separator.

Parameters:

Name Type Description Default
separator str

String used to separate nested keys in kwargs.

'_'
**kwargs str

Keyword arguments where keys represent (possibly nested) columns and values are regex patterns to match.

{}

Returns:

Type Description
GeoDataFrame

A GeoDataFrame containing only the rows that match all filter criteria.

GeoDataFrame

If a requested top-level column is missing, an empty GeoDataFrame

GeoDataFrame

with the original schema is returned.

Source code in ratiopath/parsers/darwin7_json_parser.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def get_filtered_geodataframe(
    self, separator: str = "_", **kwargs: str
) -> GeoDataFrame:
    """Filter the GeoDataFrame based on property values.

    Supports filtering by top-level columns or nested attributes within JSON-like
    columns (e.g., 'properties'). Nested keys are accessed by joining column
    names and keys with the separator.

    Args:
        separator: String used to separate nested keys in kwargs.
        **kwargs: Keyword arguments where keys represent (possibly nested)
            columns and values are regex patterns to match.

    Returns:
        A GeoDataFrame containing only the rows that match all filter criteria.
        If a requested top-level column is missing, an empty GeoDataFrame
        with the original schema is returned.
    """
    filtered_gdf = self.gdf

    for key, pattern in kwargs.items():
        subkeys = key.split(separator)
        if not subkeys or subkeys[0] not in filtered_gdf.columns:
            return self.gdf.iloc[0:0]

        series = filtered_gdf[subkeys[0]]

        if len(subkeys) > 1:
            series = series.apply(
                lambda x, sk=subkeys[1:]: self.extract_nested(x, sk)
            )
            mask = series.notna()
            filtered_gdf = filtered_gdf[mask]
            series = series[mask]

        if filtered_gdf.empty:
            return filtered_gdf

        series = series.astype(str)
        mask = series.str.match(pattern, na=False)
        filtered_gdf = filtered_gdf[mask]

    return filtered_gdf

get_points(**kwargs)

Get points from the GeoDataFrame.

Parameters:

Name Type Description Default
**kwargs str

Keyword arguments containing regex patterns for filtering properties.

{}

Yields:

Type Description
Iterable[Point]

Shapely Point objects.

Source code in ratiopath/parsers/darwin7_json_parser.py
169
170
171
172
173
174
175
176
177
178
179
def get_points(self, **kwargs: str) -> Iterable[Point]:
    """Get points from the GeoDataFrame.

    Args:
        **kwargs: Keyword arguments containing regex patterns for filtering properties.

    Yields:
        Shapely Point objects.
    """
    filtered_gdf = self.get_filtered_geodataframe(**kwargs)
    yield from filtered_gdf[filtered_gdf.geom_type == "Point"].geometry

get_polygons(**kwargs)

Get polygons from the GeoDataFrame.

Parameters:

Name Type Description Default
**kwargs str

Keyword arguments containing regex patterns for filtering properties.

{}

Yields:

Type Description
Iterable[Polygon]

Shapely Polygon objects.

Source code in ratiopath/parsers/darwin7_json_parser.py
157
158
159
160
161
162
163
164
165
166
167
def get_polygons(self, **kwargs: str) -> Iterable[Polygon]:
    """Get polygons from the GeoDataFrame.

    Args:
        **kwargs: Keyword arguments containing regex patterns for filtering properties.

    Yields:
        Shapely Polygon objects.
    """
    filtered_gdf = self.get_filtered_geodataframe(**kwargs)
    yield from filtered_gdf[filtered_gdf.geom_type == "Polygon"].geometry