AttributeError: 'str' object has no attribute 'signed_session' for Python Notebook request to CV API.

Shane Dzartov 45 Reputation points
2023-04-06T11:30:34.25+00:00

I have trained and deployed a custom vision model via an Azure ML Notebook, following the guide: https://video2.skills-academy.com/en-us/azure/cognitive-services/custom-vision-service/quickstarts/image-classification?tabs=visual-studio&pivots=programming-language-python

I'm now trying to send images to the service via the SDK Notebook code:

test_images_folder = '5point2/frames'
output_images_folder = '5point2/output'

# Load the Arial font from the Matplotlib font library
font_path = fm.findfont(fm.FontProperties(family='Arial'))

# Create a PIL ImageFont object using the Arial font
font_size = 16
font = ImageFont.truetype(font_path, font_size)

for filename in os.listdir(test_images_folder):
    if filename.endswith(".jpg"):
        image_path = os.path.join(test_images_folder, filename)

        with open(image_path, "rb") as image_contents:
            predictor1 = CustomVisionPredictionClient(end_point, pred_key)
            headers = {'Prediction-Key': pred_key, 'Content-Type': 'application/octet-stream'}
            results = predictor1.classify_image(project.id, pub_iter_name, image_contents.read(), headers=headers)

            # Load the image and create a drawing context.
            im = Image.open(image_path)
            draw = ImageDraw.Draw(im)

            # Draw the class labels and their probabilities on the image.
            for prediction in results.predictions:
                label = prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100)
                draw.text((10, 10 + 20 * results.predictions.index(prediction)), label, fill="white", font=font)

            # Save the output image.
            output_image_path = os.path.join(output_images_folder, filename)
            im.save(output_image_path)

            # Print the predictions.
            print("Predictions for", filename)
            for prediction in results.predictions:
                print("\t" + prediction.tag_name + ": {0:.2f}%".format(prediction.probability * 100))

        # Delay before sending the next image.
        time.sleep(1)

But I get the following error:

AttributeError                            Traceback (most recent call last)
Input In [114], in <cell line: 18>()
     23 predictor1 = CustomVisionPredictionClient(end_point, pred_key)
     24 headers = {'Prediction-Key': pred_key, 'Content-Type': 'application/octet-stream'}
---> 25 results = predictor1.classify_image(project.id, pub_iter_name, image_contents.read(), headers=headers)
     27 # Load the image and create a drawing context.
     28 im = Image.open(image_path)

File /anaconda/envs/azureml_py310_sdkv2/lib/python3.10/site-packages/azure/cognitiveservices/vision/customvision/prediction/operations/_custom_vision_prediction_client_operations.py:73, in CustomVisionPredictionClientOperationsMixin.classify_image(self, project_id, published_name, image_data, application, custom_headers, raw, **operation_config)
     71 # Construct and send request
     72 request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
---> 73 response = self._client.send(request, stream=False, **operation_config)
     75 if response.status_code not in [200]:
     76     raise models.CustomVisionErrorException(self._deserialize, response)

File /anaconda/envs/azureml_py310_sdkv2/lib/python3.10/site-packages/msrest/service_client.py:336, in ServiceClient.send(self, request, headers, content, **kwargs)
    334 kwargs.setdefault('stream', True)
    335 try:
--> 336     pipeline_response = self.config.pipeline.run(request, **kwargs)
    337     # There is too much thing that expects this method to return a "requests.Response"
    338     # to break it in a compatible release.
    339     # Also, to be pragmatic in the "sync" world "requests" rules anyway.
    340     # However, attach the Universal HTTP response
    341     # to get the streaming generator.
    342     response = pipeline_response.http_response.internal_response

File /anaconda/envs/azureml_py310_sdkv2/lib/python3.10/site-packages/msrest/pipeline/__init__.py:197, in Pipeline.run(self, request, **kwargs)
    195 pipeline_request = Request(request, context)  # type: Request[HTTPRequestType]
    196 first_node = self._impl_policies[0] if self._impl_policies else self._sender
--> 197 return first_node.send(pipeline_request, **kwargs)

File /anaconda/envs/azureml_py310_sdkv2/lib/python3.10/site-packages/msrest/pipeline/__init__.py:150, in _SansIOHTTPPolicyRunner.send(self, request, **kwargs)
    148 self._policy.on_request(request, **kwargs)
    149 try:
--> 150     response = self.next.send(request, **kwargs)
    151 except Exception:
    152     if not self._policy.on_exception(request, **kwargs):

File /anaconda/envs/azureml_py310_sdkv2/lib/python3.10/site-packages/msrest/pipeline/requests.py:65, in RequestsCredentialsPolicy.send(self, request, **kwargs)
     63 session = request.context.session
     64 try:
---> 65     self._creds.signed_session(session)
     66 except TypeError: # Credentials does not support session injection
     67     _LOGGER.warning("Your credentials class does not support session injection. Performance will not be at the maximum.")

AttributeError: 'str' object has no attribute 'signed_session'

I have checked all my credentials and they are all correct.
I am unable to use azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionEndpoint as I am using Python.

I assume this is an SDK issue, please assist.

Thank you.

Azure Machine Learning
Azure Machine Learning
An Azure machine learning service for building and deploying models.
2,892 questions
Azure AI Custom Vision
Azure AI Custom Vision
An Azure artificial intelligence service and end-to-end platform for applying computer vision to specific domains.
247 questions
Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
2,833 questions
{count} votes

Accepted answer
  1. romungi-MSFT 45,961 Reputation points Microsoft Employee
    2023-04-06T13:16:14.7966667+00:00

    @Shane Dzartov I think this error is from the msrest package rather than the custom vision library. I see that you have not used or imported ApiKeyCredentials from msrest and instead the keys are directly passed to prediction client which seems to fail the request.

    Could you add the following in imports section:

    from msrest.authentication import ApiKeyCredentials

    And pass your key to ApiKeyCredentials and then to the prediction client?

    python prediction_credentials = ApiKeyCredentials(in_headers={"Prediction-key": prediction_key})  
    predictor1 = CustomVisionPredictionClient(end_point, prediction_credentials) 
    #Comment the headers declaration since SDK should take care of Content-Type header 
    results = predictor1.classify_image(project.id, pub_iter_name, image_contents.read()) 
    
    

    If this answers your query, do click Accept Answer and Yes for was this answer helpful. And, if you have any further query do let us know.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.