def test_predict(self): # Setup Expected Response expected_response = {} expected_response = prediction_service_pb2.PredictResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) patch = mock.patch("google.api_core.grpc_helpers.create_channel") with patch as create_channel: create_channel.return_value = channel client = automl_v1.PredictionServiceClient() # Setup Request name = client.model_path("[PROJECT]", "[LOCATION]", "[MODEL]") payload = {} response = client.predict(name, payload) assert expected_response == response assert len(channel.requests) == 1 expected_request = prediction_service_pb2.PredictRequest( name=name, payload=payload) actual_request = channel.requests[0][1] assert expected_request == actual_request
def predict( self, name, payload, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Perform an online prediction. The prediction result is directly returned in the response. Available for following ML scenarios, and their expected request payloads: AutoML Vision Classification - An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. AutoML Vision Object Detection - An image in .JPEG, .GIF or .PNG format, image_bytes up to 30MB. AutoML Natural Language Classification - A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in .PDF, .TIF or .TIFF format with size upto 2MB. AutoML Natural Language Entity Extraction - A TextSnippet up to 10,000 characters, UTF-8 NFC encoded or a document in .PDF, .TIF or .TIFF format with size upto 20MB. AutoML Natural Language Sentiment Analysis - A TextSnippet up to 60,000 characters, UTF-8 encoded or a document in .PDF, .TIF or .TIFF format with size upto 2MB. AutoML Translation - A TextSnippet up to 25,000 characters, UTF-8 encoded. AutoML Tables - A row with column values matching the columns of the model, up to 5MB. Not available for FORECASTING ``prediction_type``. Example: >>> from google.cloud import automl_v1 >>> >>> client = automl_v1.PredictionServiceClient() >>> >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') >>> >>> # TODO: Initialize `payload`: >>> payload = {} >>> >>> response = client.predict(name, payload) Args: name (str): Required. Name of the model requested to serve the prediction. payload (Union[dict, ~google.cloud.automl_v1.types.ExamplePayload]): Required. Payload to perform a prediction on. The payload must match the problem type that the model was trained to solve. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.automl_v1.types.ExamplePayload` params (dict[str -> str]): Additional domain-specific parameters, any string must be up to 25000 characters long. AutoML Vision Classification ``score_threshold`` : (float) A value from 0.0 to 1.0. When the model makes predictions for an image, it will only produce results that have at least this confidence score. The default is 0.5. AutoML Vision Object Detection ``score_threshold`` : (float) When Model detects objects on the image, it will only produce bounding boxes which have at least this confidence score. Value in 0 to 1 range, default is 0.5. ``max_bounding_box_count`` : (int64) The maximum number of bounding boxes returned. The default is 100. The number of returned bounding boxes might be limited by the server. AutoML Tables ``feature_importance`` : (boolean) Whether ``feature_importance`` is populated in the returned list of ``TablesAnnotation`` objects. The default is false. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.automl_v1.types.PredictResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "predict" not in self._inner_api_calls: self._inner_api_calls[ "predict"] = google.api_core.gapic_v1.method.wrap_method( self.transport.predict, default_retry=self._method_configs["Predict"].retry, default_timeout=self._method_configs["Predict"].timeout, client_info=self._client_info, ) request = prediction_service_pb2.PredictRequest( name=name, payload=payload, params=params, ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header) metadata.append(routing_metadata) return self._inner_api_calls["predict"](request, retry=retry, timeout=timeout, metadata=metadata)
def predict( self, name, payload, params=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Perform an online prediction. The prediction result will be directly returned in the response. Available for following ML problems, and their expected request payloads: - Translation - TextSnippet, content up to 25,000 characters, UTF-8 encoded. Example: >>> from google.cloud import automl_v1 >>> >>> client = automl_v1.PredictionServiceClient() >>> >>> name = client.model_path('[PROJECT]', '[LOCATION]', '[MODEL]') >>> >>> # TODO: Initialize `payload`: >>> payload = {} >>> >>> response = client.predict(name, payload) Args: name (str): Name of the model requested to serve the prediction. payload (Union[dict, ~google.cloud.automl_v1.types.ExamplePayload]): Required. Payload to perform a prediction on. The payload must match the problem type that the model was trained to solve. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.automl_v1.types.ExamplePayload` params (dict[str -> str]): Additional domain-specific parameters, any string must be up to 25000 characters long. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.automl_v1.types.PredictResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "predict" not in self._inner_api_calls: self._inner_api_calls[ "predict"] = google.api_core.gapic_v1.method.wrap_method( self.transport.predict, default_retry=self._method_configs["Predict"].retry, default_timeout=self._method_configs["Predict"].timeout, client_info=self._client_info, ) request = prediction_service_pb2.PredictRequest(name=name, payload=payload, params=params) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header) metadata.append(routing_metadata) return self._inner_api_calls["predict"](request, retry=retry, timeout=timeout, metadata=metadata)