Maintain a list of transform operations which will be applied in sequence. Attributes: transforms (list[Transform])
| 252 | |
| 253 | |
| 254 | class TransformList(Transform): |
| 255 | """ |
| 256 | Maintain a list of transform operations which will be applied in sequence. |
| 257 | Attributes: |
| 258 | transforms (list[Transform]) |
| 259 | """ |
| 260 | |
| 261 | def __init__(self, transforms: List[Transform]): |
| 262 | """ |
| 263 | Args: |
| 264 | transforms (list[Transform]): list of transforms to perform. |
| 265 | """ |
| 266 | super().__init__() |
| 267 | # "Flatten" the list so that TransformList do not recursively contain TransfomList. |
| 268 | # The additional hierarchy does not change semantic of the class, but cause extra |
| 269 | # complexities in e.g, telling whether a TransformList contains certain Transform |
| 270 | tfms_flatten = [] |
| 271 | for t in transforms: |
| 272 | assert isinstance( |
| 273 | t, Transform |
| 274 | ), f"TransformList requires a list of Transform. Got type {type(t)}!" |
| 275 | if isinstance(t, TransformList): |
| 276 | tfms_flatten.extend(t.transforms) |
| 277 | else: |
| 278 | tfms_flatten.append(t) |
| 279 | self.transforms = tfms_flatten |
| 280 | |
| 281 | def _apply(self, x: _T, meth: str) -> _T: |
| 282 | """ |
| 283 | Apply the transforms on the input. |
| 284 | Args: |
| 285 | x: input to apply the transform operations. |
| 286 | meth (str): meth. |
| 287 | Returns: |
| 288 | x: after apply the transformation. |
| 289 | """ |
| 290 | for t in self.transforms: |
| 291 | x = getattr(t, meth)(x) |
| 292 | return x |
| 293 | |
| 294 | def __getattribute__(self, name: str): |
| 295 | # use __getattribute__ to win priority over any registered dtypes |
| 296 | if name.startswith("apply_"): |
| 297 | return lambda x: self._apply(x, name) |
| 298 | return super().__getattribute__(name) |
| 299 | |
| 300 | def __add__(self, other: "TransformList") -> "TransformList": |
| 301 | """ |
| 302 | Args: |
| 303 | other (TransformList): transformation to add. |
| 304 | Returns: |
| 305 | TransformList: list of transforms. |
| 306 | """ |
| 307 | others = other.transforms if isinstance(other, TransformList) else [other] |
| 308 | return TransformList(self.transforms + others) |
| 309 | |
| 310 | def __iadd__(self, other: "TransformList") -> "TransformList": |
| 311 | """ |