Skip to content

Commit

Permalink
fix(automl): fix TablesClient.predict for list and struct
Browse files Browse the repository at this point in the history
The Predict request payload is proto. Previously Python dict is
automatically converted to proto. However, the conversion failed for
google.protobuf.ListValue and google.protobuf.Struct. Changing the
structure of the Python dict might fix the problem. However, this PR
fixes the problem by generating the proto message directly. So there
is no auto conversion step.

FIXES #9887
  • Loading branch information
Helin Wang committed Dec 18, 2019
1 parent 80f5295 commit f4604f5
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 45 deletions.
51 changes: 36 additions & 15 deletions automl/google/cloud/automl_v1beta1/tables/tables_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
from google.api_core.gapic_v1 import client_info
from google.api_core import exceptions
from google.cloud.automl_v1beta1 import gapic
from google.cloud.automl_v1beta1.proto import data_types_pb2
from google.cloud.automl_v1beta1.proto import data_types_pb2, data_items_pb2
from google.cloud.automl_v1beta1.tables import gcs_client
from google.protobuf import struct_pb2


_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-automl").version
_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -390,21 +392,39 @@ def __column_spec_name_from_args(

return column_spec_name

def __type_code_to_value_type(self, type_code, value):
def __data_type_to_proto_value(self, data_type, value):
type_code = data_type.type_code
if value is None:
return {"null_value": 0}
return struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)
elif type_code == data_types_pb2.FLOAT64:
return {"number_value": value}
elif type_code == data_types_pb2.TIMESTAMP:
return {"string_value": value}
elif type_code == data_types_pb2.STRING:
return {"string_value": value}
return struct_pb2.Value(number_value=value)
elif (
type_code == data_types_pb2.TIMESTAMP
or type_code == data_types_pb2.STRING
or type_code == data_types_pb2.CATEGORY
):
return struct_pb2.Value(string_value=value)
elif type_code == data_types_pb2.ARRAY:
return {"list_value": value}
if isinstance(value, struct_pb2.ListValue):
# in case the user passed in a ListValue.
return struct_pb2.Value(list_value=value)
array = []
for item in value:
array.append(
self.__data_type_to_proto_value(data_type.list_element_type, item)
)
return struct_pb2.Value(list_value=struct_pb2.ListValue(values=array))
elif type_code == data_types_pb2.STRUCT:
return {"struct_value": value}
elif type_code == data_types_pb2.CATEGORY:
return {"string_value": value}
if isinstance(value, struct_pb2.Struct):
# in case the user passed in a Struct.
return struct_pb2.Value(struct_value=value)
struct_value = struct_pb2.Struct()
for k, v in value.items():
field_value = self.__data_type_to_proto_value(
data_type.struct_type.fields[k], v
)
struct_value.fields[k].CopyFrom(field_value)
return struct_pb2.Value(struct_value=struct_value)
else:
raise ValueError("Unknown type_code: {}".format(type_code))

Expand Down Expand Up @@ -2682,16 +2702,17 @@ def predict(

values = []
for i, c in zip(inputs, column_specs):
value_type = self.__type_code_to_value_type(c.data_type.type_code, i)
value_type = self.__data_type_to_proto_value(c.data_type, i)
values.append(value_type)

request = {"row": {"values": values}}
row = data_items_pb2.Row(values=values)
payload = data_items_pb2.ExamplePayload(row=row)

params = None
if feature_importance:
params = {"feature_importance": "true"}

return self.prediction_client.predict(model.name, request, params, **kwargs)
return self.prediction_client.predict(model.name, payload, params, **kwargs)

def batch_predict(
self,
Expand Down
1 change: 1 addition & 0 deletions automl/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
dependencies = [
"google-api-core[grpc] >= 1.14.0, < 2.0.0dev",
'enum34; python_version < "3.4"',
"protobuf >= 3.4.0",
]
extras = {
"pandas": ["pandas>=0.17.1"],
Expand Down
93 changes: 63 additions & 30 deletions automl/tests/unit/gapic/v1beta1/test_tables_client_v1beta1.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
from google.api_core import exceptions
from google.auth.credentials import AnonymousCredentials
from google.cloud import automl_v1beta1
from google.cloud.automl_v1beta1.proto import data_types_pb2
from google.cloud.automl_v1beta1.proto import data_types_pb2, data_items_pb2
from google.protobuf import struct_pb2

PROJECT = "project"
REGION = "region"
Expand Down Expand Up @@ -1116,9 +1117,10 @@ def test_predict_from_array(self):
model.configure_mock(tables_model_metadata=model_metadata, name="my_model")
client = self.tables_client({"get_model.return_value": model}, {})
client.predict(["1"], model_name="my_model")
client.prediction_client.predict.assert_called_with(
"my_model", {"row": {"values": [{"string_value": "1"}]}}, None
payload = data_items_pb2.ExamplePayload(
row=data_items_pb2.Row(values=[struct_pb2.Value(string_value="1")])
)
client.prediction_client.predict.assert_called_with("my_model", payload, None)

def test_predict_from_dict(self):
data_type = mock.Mock(type_code=data_types_pb2.CATEGORY)
Expand All @@ -1131,10 +1133,16 @@ def test_predict_from_dict(self):
model.configure_mock(tables_model_metadata=model_metadata, name="my_model")
client = self.tables_client({"get_model.return_value": model}, {})
client.predict({"a": "1", "b": "2"}, model_name="my_model")
payload = data_items_pb2.ExamplePayload(
row=data_items_pb2.Row(
values=[
struct_pb2.Value(string_value="1"),
struct_pb2.Value(string_value="2"),
]
)
)
client.prediction_client.predict.assert_called_with(
"my_model",
{"row": {"values": [{"string_value": "1"}, {"string_value": "2"}]}},
None,
"my_model", payload, None,
)

def test_predict_from_dict_with_feature_importance(self):
Expand All @@ -1150,10 +1158,16 @@ def test_predict_from_dict_with_feature_importance(self):
client.predict(
{"a": "1", "b": "2"}, model_name="my_model", feature_importance=True
)
payload = data_items_pb2.ExamplePayload(
row=data_items_pb2.Row(
values=[
struct_pb2.Value(string_value="1"),
struct_pb2.Value(string_value="2"),
]
)
)
client.prediction_client.predict.assert_called_with(
"my_model",
{"row": {"values": [{"string_value": "1"}, {"string_value": "2"}]}},
{"feature_importance": "true"},
"my_model", payload, {"feature_importance": "true"},
)

def test_predict_from_dict_missing(self):
Expand All @@ -1167,18 +1181,31 @@ def test_predict_from_dict_missing(self):
model.configure_mock(tables_model_metadata=model_metadata, name="my_model")
client = self.tables_client({"get_model.return_value": model}, {})
client.predict({"a": "1"}, model_name="my_model")
payload = data_items_pb2.ExamplePayload(
row=data_items_pb2.Row(
values=[struct_pb2.Value(string_value="1"), struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE)]
)
)
client.prediction_client.predict.assert_called_with(
"my_model",
{"row": {"values": [{"string_value": "1"}, {"null_value": 0}]}},
None,
"my_model", payload, None,
)

def test_predict_all_types(self):
float_type = mock.Mock(type_code=data_types_pb2.FLOAT64)
timestamp_type = mock.Mock(type_code=data_types_pb2.TIMESTAMP)
string_type = mock.Mock(type_code=data_types_pb2.STRING)
array_type = mock.Mock(type_code=data_types_pb2.ARRAY)
struct_type = mock.Mock(type_code=data_types_pb2.STRUCT)
array_type = mock.Mock(
type_code=data_types_pb2.ARRAY,
list_element_type=mock.Mock(type_code=data_types_pb2.FLOAT64),
)
struct = data_types_pb2.StructType()
struct.fields["a"].CopyFrom(
data_types_pb2.DataType(type_code=data_types_pb2.CATEGORY)
)
struct.fields["b"].CopyFrom(
data_types_pb2.DataType(type_code=data_types_pb2.CATEGORY)
)
struct_type = mock.Mock(type_code=data_types_pb2.STRUCT, struct_type=struct)
category_type = mock.Mock(type_code=data_types_pb2.CATEGORY)
column_spec_float = mock.Mock(display_name="float", data_type=float_type)
column_spec_timestamp = mock.Mock(
Expand Down Expand Up @@ -1211,28 +1238,34 @@ def test_predict_all_types(self):
"timestamp": "EST",
"string": "text",
"array": [1],
"struct": {"a": "b"},
"struct": {"a": "label_a", "b": "label_b"},
"category": "a",
"null": None,
},
model_name="my_model",
)
struct = struct_pb2.Struct()
struct.fields["a"].CopyFrom(struct_pb2.Value(string_value="label_a"))
struct.fields["b"].CopyFrom(struct_pb2.Value(string_value="label_b"))
payload = data_items_pb2.ExamplePayload(
row=data_items_pb2.Row(
values=[
struct_pb2.Value(number_value=1.0),
struct_pb2.Value(string_value="EST"),
struct_pb2.Value(string_value="text"),
struct_pb2.Value(
list_value=struct_pb2.ListValue(
values=[struct_pb2.Value(number_value=1.0)]
)
),
struct_pb2.Value(struct_value=struct),
struct_pb2.Value(string_value="a"),
struct_pb2.Value(null_value=struct_pb2.NullValue.NULL_VALUE),
]
)
)
client.prediction_client.predict.assert_called_with(
"my_model",
{
"row": {
"values": [
{"number_value": 1.0},
{"string_value": "EST"},
{"string_value": "text"},
{"list_value": [1]},
{"struct_value": {"a": "b"}},
{"string_value": "a"},
{"null_value": 0},
]
}
},
None,
"my_model", payload, None,
)

def test_predict_from_array_missing(self):
Expand Down

0 comments on commit f4604f5

Please sign in to comment.