Skip to content

parse_image

Strategy class for parsing an image to a DLite instance.

LOGGER = logging.getLogger('oteapi_dlite.strategies') module-attribute

DLiteImageConfig

Bases: ImageConfig, DLiteResult

Configuration for DLite image parser.

Source code in oteapi_dlite/strategies/parse_image.py
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
class DLiteImageConfig(ImageConfig, DLiteResult):
    """Configuration for DLite image parser."""

    # Resource config
    mediaType: Annotated[
        Optional[
            Literal[
                "image/vnd.dlite-jpg",
                "image/vnd.dlite-jpeg",
                "image/vnd.dlite-jp2",
                "image/vnd.dlite-png",
                "image/vnd.dlite-gif",
                "image/vnd.dlite-tiff",
                "image/vnd.dlite-eps",
            ]
        ],
        Field(description=ResourceConfig.model_fields["mediaType"].description),
    ] = None

    # Parser config
    image_label: Annotated[
        str,
        Field(
            description="Label to assign to the image in the collection.",
        ),
    ] = "image"

image_label: Annotated[str, Field(description='Label to assign to the image in the collection.')] = 'image' class-attribute instance-attribute

mediaType: Annotated[Optional[Literal['image/vnd.dlite-jpg', 'image/vnd.dlite-jpeg', 'image/vnd.dlite-jp2', 'image/vnd.dlite-png', 'image/vnd.dlite-gif', 'image/vnd.dlite-tiff', 'image/vnd.dlite-eps']], Field(description=ResourceConfig.model_fields['mediaType'].description)] = None class-attribute instance-attribute

DLiteImageParseStrategy

Parse strategy for image files.

Registers strategies:

  • ("mediaType", "image/vnd.dlite-gif")
  • ("mediaType", "image/vnd.dlite-jpeg")
  • ("mediaType", "image/vnd.dlite-jpg")
  • ("mediaType", "image/vnd.dlite-jp2")
  • ("mediaType", "image/vnd.dlite-png")
  • ("mediaType", "image/vnd.dlite-tiff")
Source code in oteapi_dlite/strategies/parse_image.py
 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
@dataclass
class DLiteImageParseStrategy:
    """Parse strategy for image files.

    **Registers strategies**:

    - `("mediaType", "image/vnd.dlite-gif")`
    - `("mediaType", "image/vnd.dlite-jpeg")`
    - `("mediaType", "image/vnd.dlite-jpg")`
    - `("mediaType", "image/vnd.dlite-jp2")`
    - `("mediaType", "image/vnd.dlite-png")`
    - `("mediaType", "image/vnd.dlite-tiff")`

    """

    parse_config: DLiteImageParserConfig

    def initialize(self) -> DLiteResult:
        """Initialize."""
        return DLiteResult(
            collection_id=get_collection(
                self.parse_config.configuration.collection_id
            ).uuid
        )

    def get(self) -> DLiteResult:
        """Execute the strategy.

        This method will be called through the strategy-specific
        endpoint of the OTE-API Services.  It assumes that the image to
        parse is stored in a data cache, and can be retrieved via a key
        that is supplied in the parser configuration.

        Returns:
            Reference to a DLite collection ID.

        """
        config = self.parse_config.configuration

        if config.downloadUrl is None:
            raise ValueError("downloadUrl is required.")
        if config.mediaType is None:
            raise ValueError("mediaType is required.")

        # Configuration for ImageDataParseStrategy in oteapi-core
        core_config = {
            "parserType": "parser/image",
            "configuration": config.model_dump(),
            "entity": self.parse_config.entity,
        }
        core_config["configuration"]["mediaType"] = (
            "image/" + config.mediaType.split("-")[-1]
        )

        output = create_strategy("parse", core_config).get()

        cache = DataCache()
        data = cache.get(output["image_key"])
        if isinstance(data, bytes):
            data = np.asarray(
                Image.frombytes(
                    data=data,
                    mode=output["image_mode"],
                    size=output["image_size"],
                )
            )
        if not isinstance(data, np.ndarray):
            raise TypeError(
                "Expected image data to be a numpy array, instead it was "
                f"{type(data)}."
            )

        meta = get_meta(str(self.parse_config.entity))
        inst = meta(dimensions=data.shape)
        inst["data"] = data

        coll = get_collection(config.collection_id)
        coll.add(config.image_label, inst)

        update_collection(coll)
        return DLiteResult(collection_id=coll.uuid)

parse_config: DLiteImageParserConfig instance-attribute

get()

Execute the strategy.

This method will be called through the strategy-specific endpoint of the OTE-API Services. It assumes that the image to parse is stored in a data cache, and can be retrieved via a key that is supplied in the parser configuration.

Returns:

Type Description
DLiteResult

Reference to a DLite collection ID.

Source code in oteapi_dlite/strategies/parse_image.py
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
def get(self) -> DLiteResult:
    """Execute the strategy.

    This method will be called through the strategy-specific
    endpoint of the OTE-API Services.  It assumes that the image to
    parse is stored in a data cache, and can be retrieved via a key
    that is supplied in the parser configuration.

    Returns:
        Reference to a DLite collection ID.

    """
    config = self.parse_config.configuration

    if config.downloadUrl is None:
        raise ValueError("downloadUrl is required.")
    if config.mediaType is None:
        raise ValueError("mediaType is required.")

    # Configuration for ImageDataParseStrategy in oteapi-core
    core_config = {
        "parserType": "parser/image",
        "configuration": config.model_dump(),
        "entity": self.parse_config.entity,
    }
    core_config["configuration"]["mediaType"] = (
        "image/" + config.mediaType.split("-")[-1]
    )

    output = create_strategy("parse", core_config).get()

    cache = DataCache()
    data = cache.get(output["image_key"])
    if isinstance(data, bytes):
        data = np.asarray(
            Image.frombytes(
                data=data,
                mode=output["image_mode"],
                size=output["image_size"],
            )
        )
    if not isinstance(data, np.ndarray):
        raise TypeError(
            "Expected image data to be a numpy array, instead it was "
            f"{type(data)}."
        )

    meta = get_meta(str(self.parse_config.entity))
    inst = meta(dimensions=data.shape)
    inst["data"] = data

    coll = get_collection(config.collection_id)
    coll.add(config.image_label, inst)

    update_collection(coll)
    return DLiteResult(collection_id=coll.uuid)

initialize()

Initialize.

Source code in oteapi_dlite/strategies/parse_image.py
107
108
109
110
111
112
113
def initialize(self) -> DLiteResult:
    """Initialize."""
    return DLiteResult(
        collection_id=get_collection(
            self.parse_config.configuration.collection_id
        ).uuid
    )

DLiteImageParserConfig

Bases: ParserConfig

Parser config for DLite image parser.

Source code in oteapi_dlite/strategies/parse_image.py
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
class DLiteImageParserConfig(ParserConfig):
    """Parser config for DLite image parser."""

    parserType: Annotated[
        Literal["image/vnd.dlite-image"],
        Field(description=ParserConfig.model_fields["parserType"].description),
    ] = "image/vnd.dlite-image"

    configuration: Annotated[
        DLiteImageConfig,
        Field(
            description="Image parse strategy-specific configuration.",
        ),
    ] = DLiteImageConfig()

    entity: Annotated[
        AnyHttpUrl,  # Keep this type to avoid changing the original type
        Field(description=ParserConfig.model_fields["entity"].description),
    ] = AnyHttpUrl("http://onto-ns.com/meta/1.0/Image")

    @field_validator("entity", mode="after")
    @classmethod
    def _validate_entity(cls, value: AnyHttpUrl) -> AnyHttpUrl:
        """Ensure that the entity is the Image URI."""
        fixed_uri = "http://onto-ns.com/meta/1.0/Image"

        if value != AnyHttpUrl(fixed_uri):
            raise ValueError(f"Entity must be exactly equal to: {fixed_uri}")

        return value

configuration: Annotated[DLiteImageConfig, Field(description='Image parse strategy-specific configuration.')] = DLiteImageConfig() class-attribute instance-attribute

entity: Annotated[AnyHttpUrl, Field(description=ParserConfig.model_fields['entity'].description)] = AnyHttpUrl('http://onto-ns.com/meta/1.0/Image') class-attribute instance-attribute

parserType: Annotated[Literal['image/vnd.dlite-image'], Field(description=ParserConfig.model_fields['parserType'].description)] = 'image/vnd.dlite-image' class-attribute instance-attribute