|
| 1 | +# Copyright 2020 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import absolute_import |
| 15 | +from google.cloud.aiplatform.helpers import value_converter |
| 16 | + |
| 17 | +from proto.marshal import Marshal |
| 18 | +from proto.marshal.rules.struct import ValueRule |
| 19 | +from google.protobuf.struct_pb2 import Value |
| 20 | + |
| 21 | + |
| 22 | +class ConversionValueRule(ValueRule): |
| 23 | + def to_python(self, value, *, absent: bool = None): |
| 24 | + return super().to_python(value, absent=absent) |
| 25 | + |
| 26 | + def to_proto(self, value): |
| 27 | + |
| 28 | + # Need to check whether value is an instance |
| 29 | + # of an enhanced type |
| 30 | + if callable(getattr(value, "to_value", None)): |
| 31 | + return value.to_value() |
| 32 | + else: |
| 33 | + return super().to_proto(value) |
| 34 | + |
| 35 | + |
| 36 | +def _add_methods_to_classes_in_package(pkg): |
| 37 | + classes = dict( |
| 38 | + [(name, cls) for name, cls in pkg.__dict__.items() if isinstance(cls, type)] |
| 39 | + ) |
| 40 | + |
| 41 | + for class_name, cls in classes.items(): |
| 42 | + # Add to_value() method to class with docstring |
| 43 | + setattr(cls, "to_value", value_converter.to_value) |
| 44 | + cls.to_value.__doc__ = value_converter.to_value.__doc__ |
| 45 | + |
| 46 | + # Add from_value() method to class with docstring |
| 47 | + setattr(cls, "from_value", _add_from_value_to_class(cls)) |
| 48 | + cls.from_value.__doc__ = value_converter.from_value.__doc__ |
| 49 | + |
| 50 | + # Add from_map() method to class with docstring |
| 51 | + setattr(cls, "from_map", _add_from_map_to_class(cls)) |
| 52 | + cls.from_map.__doc__ = value_converter.from_map.__doc__ |
| 53 | + |
| 54 | + |
| 55 | +def _add_from_value_to_class(cls): |
| 56 | + def _from_value(value): |
| 57 | + return value_converter.from_value(cls, value) |
| 58 | + |
| 59 | + return _from_value |
| 60 | + |
| 61 | + |
| 62 | +def _add_from_map_to_class(cls): |
| 63 | + def _from_map(map_): |
| 64 | + return value_converter.from_map(cls, map_) |
| 65 | + |
| 66 | + return _from_map |
| 67 | + |
| 68 | + |
| 69 | +marshal = Marshal(name="google.cloud.aiplatform.v1beta1") |
| 70 | +marshal.register(Value, ConversionValueRule(marshal=marshal)) |
0 commit comments