Bing Image Search SDK for Python: Getting 'Permission Denied' - python-3.x

I'm trying to use the example program provided by Microsoft here to test out the Bing Image Search Service associated with their Cognitive Service offering on Azure. I type the code in character by character (of course, using my own API key) and I get the below error message when I execute the program:
Traceback (most recent call last):
File "x.py", line 9, in <module>
image_results = client.images.search(query=search_term)
File "/home/rsbrownjr/anaconda3/envs/ibing/lib/python3.6/site-packages/azure/cognitiveservices/search/imagesearch/operations/images_operations.py", line 485, in search
raise models.ErrorResponseException(self._deserialize, response)
azure.cognitiveservices.search.imagesearch.models.error_response_py3.ErrorResponseException: Operation returned an invalid status code 'PermissionDenied'
I know without a doubt that I have the right API key put into the program. I'm on pricing tier S0 pay-as-you-go but I don't have any other options either. This has got to have a simple solution.
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials
subscription_key = "MY API KEY HERE"
search_term = "canadian rockies"
client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
image_results = client.images.search(query=search_term)
if image_results.value:
first_image_result = image_results.value[0]
print("Total number of images returned: {}".format(len(image_results.value)))
print("First image thumbnail url: {}".format(
first_image_result.thumbnail_url))
print("First image content url: {}".format(first_image_result.content_url))
else:
print("No image results returned!")

I just tested the code, the code is fine. So you must provided the wrong API key.
Here is my test key 52c32221ceaa4f388b26a2b85fb79bff. It is a 7 days free trial key. I got it here.

Related

How to use yolov5 api with flask offline?

I was able to run the Flask app with yolov5 on a PC with an internet connection. I followed the steps mentioned in yolov5 docs and used this file: yolov5/utils/flask_rest_api/restapi.py,
But I need to achieve the same offline(On a particular PC). Now the issue is, when I am using the following:
model = torch.hub.load("ultralytics/yolov5", "yolov5", force_reload=True)
It tries to download model from internet. And throws an error.
Urllib.error.URLError: <urlopen error [Errno - 2] name or service not known>
How to get the same results offline.
Thanks in advance.
If you want to run detection offline, you need to have the model already downloaded.
So, download the model (for example yolov5s.pt) from https://github.com/ultralytics/yolov5/releases and store it for example to the yolov5/models.
After that, replace
# model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache
with
model = torch.hub.load(r'C:\Users\Milan\Projects\yolov5', 'custom', path=r'C:\Users\Milan\Projects\yolov5\models\yolov5s.pt', source='local')
With this line, you can run detection also offline.
Note: When you start the app for the first time with the updated torch.hub.load, it will download the model if not present (so you do not need to download it from https://github.com/ultralytics/yolov5/releases).
There is one more issue involved here. When this code is run on a machine that has no internet connection at all. Then you may face the following error.
Downloading https://ultralytics.com/assets/Arial.ttf to /home/<local_user>/.config/Ultralytics/Arial.ttf...
Traceback (most recent call last):
File "/home/<local_user>/Py_Prac_WSL/yolov5-flask-master/yolov5/utils/plots.py", line 56, in check_pil_font
return ImageFont.truetype(str(font) if font.exists() else font.name, size)
File "/home/<local_user>/.local/share/virtualenvs/23_Jun-82xb8nrB/lib/python3.8/site-packages/PIL/ImageFont.py", line 836, in truetype
return freetype(font)
File "/home/<local_user>/.local/share/virtualenvs/23_Jun-82xb8nrB/lib/python3.8/site-packages/PIL/ImageFont.py", line 833, in freetype
return FreeTypeFont(font, size, index, encoding, layout_engine)
File "/home/<local_user>/.local/share/virtualenvs/23_Jun-82xb8nrB/lib/python3.8/site-packages/PIL/ImageFont.py", line 193, in __init__
self.font = core.getfont(
OSError: cannot open resource
To overcome this error, you need to download manually, the Arial.ttf file from https://ultralytics.com/assets/Arial.ttf and paste it to the following location, on Linux:
/home/<your_pc_user>/.config/Ultralytics
On windows, paste Arial.ttf here:
C:\Windows\Fonts
The first line of the error message mentions the same thing. After this, the code runs smoothly in offline mode.
Further as mentioned at https://docs.ultralytics.com/tutorials/pytorch-hub/, any custom-trained-model other than the one uploaded at PyTorch-model-hub can be accessed by this code.
path_hubconfig = 'absolute/path/to/yolov5'
path_trained_model = 'absolute/path/to/best.pt'
model = torch.hub.load(path_hubconfig, 'custom', path=path_trained_model, source='local') # local repo
With this code, object detection is carried out by the locally saved custom-trained model. Once, the custom trained model is saved locally this piece of code access it directly avoiding any necessity of the internet.

Discord py Attachments

I am creating a bot that creates a backup of discord guilds in mysql. (Basically it allows me to make a website that is an extension of the discord channel.)
I am going to be downloading and saving attachments in then (guild,channel,user) folder path so I can query them on the website.
Also I am going to be purging inactive users by checking to see who is active withing the last 24 hours, last week, etc.
Anyway so I am trying to check to see if a message has an attachment using the following script,
#client.event
def on_message(message):
msg = str(message.content)
channel = str(message.channel)
guild = str(message.guild)
author=str(message.author)
if checkfordb(guild) == 1:
if checkfortable(channel,guild) == 1:
addmsg(channel,guild,msg,author)
else:
createtb(channel,guild)
addmsg(channel,guild,msg,author)
else:
createdb(guild)
createtb(channel,guild)
addmsg(channel,guild,msg,author)
if message.Attachment.size > 0:
print("There is an attachment")
else:
print("There is no attachment")
The problem is that when I run this script I get the following error,
Ignoring exception in on_message
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "bot2.py", line 145, in on_message
if message.Attachment.size > 0:
AttributeError: 'Message' object has no attribute 'Attachment'
So I checked the documentation and sure enough despite tons of other people saying they are using it there is no attachment attribute for message. The documentation under attachment says you can use class discord.attachment. So I looked at the classes and I see no way to pull an attachment when it is posted. Does anyone have any ideas on how to do this?
Any and all help is appreciated.
The correct attribute name is Message.attachments as Patrick Haugh suggested. You could use the len() function on that to get the "size" of it since it's just a normal python list of discord.Attachment objects.
if message.attachments:
Simple as that!

Error in google cloud speech API

I am trying to convert audio to text using Google Cloud Speech API, but I am getting the following error:
Traceback (most recent call last):
File "/home/prateek/Google Drive/projects/linuxAI/src/linuxAI.py", line 6, in <module>
client = speech.SpeechClient()
File "/usr/lib/python3.6/site-packages/google/cloud/gapic/speech/v1/speech_client.py", line 146, in __init__
ssl_credentials=ssl_credentials)
File "/usr/lib/python3.6/site-packages/google/gax/grpc.py", line 106, in create_stub
credentials = _grpc_google_auth.get_default_credentials(scopes)
File "/usr/lib/python3.6/site-packages/google/gax/_grpc_google_auth.py", line 62, in get_default_credentials
credentials, _ = google.auth.default(scopes=scopes)
File "/usr/lib/python3.6/site-packages/google/auth/_default.py", line 283, in default
raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.
I am using this code:
"""Transcribe the given audio file."""
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
client = speech.SpeechClient()
speech_file = "output.wav"
with open(speech_file, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = types.RecognitionConfig(
encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code='en-US')
response = client.recognize(config, audio)
# Each result is for a consecutive portion of the audio. Iterate through
# them to get the transcripts for the entire audio file.
for result in response.results:
# The first alternative is the most likely one for this portion.
print('Transcript: {}'.format(result.alternatives[0].transcript))
I found tutorial from here.
Did you authenticated using credentials?
First you need to create api keys.
https://support.google.com/cloud/answer/6158862?hl=en
Read this tutorial to authenticate.
https://cloud.google.com/speech/docs/auth
You can see some sample applications provided by Google.
https://github.com/GoogleCloudPlatform/python-docs-samples/tree/master/speech/cloud-client

Python - LinkedIn API get profile error

This is for an internal project. My end goal is to get details of my connections. who are in same city as I am.
I am new in using LinkedIn API . I have used code mentioned in answer here to generate the access token. Now I am using below line to get my LinkedIn profile.
application.get_profile(access_token['oauth_token'])
But I am getting below error.
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
application.get_profile(access_token['oauth_token'])
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 189, in get_profile
response = self.make_request('GET', url, params=params, headers=headers)
File "C:\Python34\lib\site-packages\python_linkedin-2.0-py3.4.egg\linkedin\linkedin.py", line 169, in make_request
params.update({'oauth2_access_token': self.authentication.token.access_token})
AttributeError: 'str' object has no attribute 'token'
Can someone please help me?
It is a bit late I guess. But for future reference, this error comes from the fact that you need to call explicitly the token element from the linkedin application.
For instance, to generate the application, you need to enter the following:
from linkedin_v2 import linkedin
application = linkedin.LinkedInApplication(token=access_token['oauth_token'])
From there, you can then call the different function from application (like "application.get_profile()").
BR
I don't think you need to pass the auth token again to get your profile. I am also using the python lib.
application.get_profile()
Should return the basic information for your profile. Then look into using selectors to specify what endpoints you want.

Azure storage queues - create_queue - getting 'binascii.Error: Incorrect padding'

EDIT: Where can I find my "user" and "password" for my storage account in Azure ? (see below).
I simply try to create a queue with the python sdk in python3.4 but with this code:
from azure.storage import QueueService
q = QueueService("user", "password")
q.create_queue('testqueue')
I get:
Traceback (most recent call last):
File "new.py", line 4, in <module>
q.create_queue('testqueue')
File "/usr/local/lib/python3.4/dist-packages/azure/storage/queueservice.py", line 151, in create_queue
request, self.account_name, self.account_key)
File "/usr/local/lib/python3.4/dist-packages/azure/storage/__init__.py", line 447, in _update_storage_queue_header
return _update_storage_blob_header(request, account_name, account_key)
File "/usr/local/lib/python3.4/dist-packages/azure/storage/__init__.py", line 440, in _update_storage_blob_header
account_key)))
File "/usr/local/lib/python3.4/dist-packages/azure/storage/__init__.py", line 516, in _sign_storage_blob_request
_sign_string(account_key, string_to_sign)
File "/usr/local/lib/python3.4/dist-packages/azure/__init__.py", line 988, in _sign_string
key = _decode_base64_to_bytes(key)
File "/usr/local/lib/python3.4/dist-packages/azure/__init__.py", line 167, in _decode_base64_to_bytes
return base64.b64decode(data)
File "/usr/lib/python3.4/base64.py", line 90, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
The thing is that I'm trying to create a linux auto-scaling farm of ubuntu VMs with a single queue. when this queue contains more than x message, the farm scales up and instead of using 1 VM, it uses 2 or 3.
I already have my VMs , I configured the availability set, the load-balancing but I'm stopped on queues.
It somebody could help, it would be great!
Thanks
Answer
I've finally found an answer here Where can I find my Azure account name and account key?
Thanks to Jason Hogg - MSFT for poiting my real problem, I thought it was another thing.
I've finally found an answer here Where can I find my Azure account name and account key?
Thanks to Jason Hogg - MSFT for poiting my real problem, I thought it was another thing.
Have you tried substituting "user" for your storage account name and "password" for the access key associated with your storage account?
Jason

Resources