Error while creating person group person in microsoft cognitive face API - python

I have a code which uses older API. I don't know new API. Those who know help me with modifying the code.
import cognitive_face as CF
from global_variables import personGroupId
import sqlite3
Key = '###################'
CF.Key.set(Key)
BASE_URL = 'https://region.api.cognitive.microsoft.com/face/v1.0/'
CF.BaseUrl.set(BASE_URL)
if len(sys.argv) is not 1:
res = CF.person.create(personGroupId, str(sys.argv[1])) #error line
print(res)
extractId = str(sys.argv[1])[-2:]
connect = sqlite3.connect("studentdb")
cmd = "SELECT * FROM Students WHERE id = " + extractId
cursor = connect.execute(cmd)
isRecordExist = 0
for row in cursor:
isRecordExist = 1
if isRecordExist == 1:
connect.execute("UPDATE Students SET personID = ? WHERE ID = ?",(res['personId'], extractId))
connect.commit()
connect.close()

As you mentioned you are using older API. You are expected to use the new API. Refer this (official documentation) for installing the package and further reference.
PACKAGE:
pip install --upgrade azure-cognitiveservices-vision-face
Import the following libraries (excluding other basic libraries)
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, SnapshotObjectType, OperationStatusType
The updated API command is as follows:
res = face_client.person_group_person.create(person_group_id, str(sys.argv[1]))

In addition to what Soorya answered above, For those who want the sample code reference, you can see the latest API sample code from here
def build_person_group(client, person_group_id, pgp_name):
print('Create and build a person group...')
# Create empty Person Group. Person Group ID must be lower case, alphanumeric, and/or with '-', '_'.
print('Person group ID:', person_group_id)
client.person_group.create(person_group_id = person_group_id, name=person_group_id)

Related

Key Error Running Python Script (Using Atom)

I have never used python before. I'm following a short guide on how to use an API with Python. I'm using Atom text editor plus the Hydrogen module to run said code.
I am getting KeyError: '203' when I run the following segment.
champ_dict = {}
for key in static_champ_list['data']:
row = static_champ_list['data'][key]
champ_dict[row['key']] = row['id']
for row in participants:
print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])
row['championName'] = champ_dict[str(row['champion'])]
# print dataframe
df = pd.DataFrame(participants)
df
the error occurs on the following line
print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])
I get that it's lookup error but I'm lost as how to resolve it.
Here is the full version of my code
#Test Script for interacting with
#RIOT API
#Built from 'Towards Data Science' guide
#If you want to use Hydrogen, install
#the Hydrogen Package and run
# python3 -m pip install ipykernel
# python3 -m ipykernel install --user
#This might allow pandas, idk
#-------------------------------------------
#Get installed module for Python
import riotwatcher
#Import tools.
from riotwatcher import LolWatcher, ApiError
#Import pandas
import pandas as pd
# Global variables
# Get new API from
# https://developer.riotgames.com/
api_key = 'RGAPI-XXXX-XXXX-XXXX-XXXX-XXXXXXXXXX'
watcher = LolWatcher(api_key)
my_region = 'euw1'
#Use 'watcher' to get basic stats
me = watcher.summoner.by_name(my_region, 'RGE lnspired')
print(me)
#Use 'watcher' to get ranked ranked stats
my_ranked_stats = watcher.league.by_summoner(my_region, me['id'])
print(my_ranked_stats)
# Setup retrieval of match info
my_matches = watcher.match.matchlist_by_account(my_region, me['accountId'])
# Fetch info about last match
last_match = my_matches['matches'][0]
match_detail = watcher.match.by_id(my_region, last_match['gameId'])
#Setup Data Frame to view some of this stuff
participants = []
for row in match_detail['participants']:
participants_row = {}
participants_row['champion'] = row['championId']
participants_row['spell1'] = row['spell1Id']
participants_row['spell2'] = row['spell2Id']
participants_row['win'] = row['stats']['win']
participants_row['kills'] = row['stats']['kills']
participants_row['deaths'] = row['stats']['deaths']
participants_row['assists'] = row['stats']['assists']
participants_row['totalDamageDealt'] = row['stats']['totalDamageDealt']
participants_row['goldEarned'] = row['stats']['goldEarned']
participants_row['champLevel'] = row['stats']['champLevel']
participants_row['totalMinionsKilled'] = row['stats']['totalMinionsKilled']
participants_row['item0'] = row['stats']['item0']
participants_row['item1'] = row['stats']['item1']
participants.append(participants_row)
df = pd.DataFrame(participants)
df
#So now we can look at what is referred
#to as 'Static Data'
# check league's latest version
latest = watcher.data_dragon.versions_for_region(my_region)['n']['champion']
# Lets get some champions static information
static_champ_list = watcher.data_dragon.champions(latest, False, 'en_US')
# champ static list data to dict for looking up
champ_dict = {}
for key in static_champ_list['data']:
row = static_champ_list['data'][key]
champ_dict[row['key']] = row['id']
for row in participants:
print(str(row['champion']) + ' ' + champ_dict[str(row['champion'])])
row['championName'] = champ_dict[str(row['champion'])]
# print dataframe
df = pd.DataFrame(participants)
df
In order to retrieve a value from a standard dictionary in python with a key, it must be a valid or else a KeyError will be raised. So your code is attempting to use the key '203' with the dictionary champ_dict, however '203' is not a valid key (hence the KeyError). To see which keys are currently present in the dict, you can call the dict.keys method on champ_dict. Example would be something like
>>> champ_dict = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
>>> champ_dict.keys()
dict_keys(['key1', 'key2', 'key3'])

azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidImageSize) Image size is too small

ERROR MESSAGE
I am trying to upload images of reasonable size(around 20KB). But according to documentation image of size 1KB to 6MB can be uploaded. I hope there is some part of the program that needs modification to rectify the error.
File "add_person_faces.py", line 46, in <module>
res = face_client.person_group_person.add_face_from_stream(global_var.personGroupId, person_id, img_data)
File "C:\Python\Python36\lib\site-packages\azure\cognitiveservices\vision\face\operations\_person_group_person_operations.py", line 785, in add_face_from_stream
raise models.APIErrorException(self._deserialize, response)
azure.cognitiveservices.vision.face.models._models_py3.APIErrorException: (InvalidImageSize) Image size is too small.
CODE
import os, time
import global_variables as global_var
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face.models import TrainingStatusType, Person, SnapshotObjectType, OperationStatusType
import urllib
import sqlite3
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
KEY = global_var.key
ENDPOINT = 'https://centralindia.api.cognitive.microsoft.com'
face_client = FaceClient(ENDPOINT,CognitiveServicesCredentials(KEY))
def get_person_id():
person_id = ''
extractId = str(sys.argv[1])[-2:]
connect = sqlite3.connect("Face-DataBase")
c = connect.cursor()
cmd = "SELECT * FROM Students WHERE ID = " + extractId
c.execute(cmd)
row = c.fetchone()
person_id = row[3]
connect.close()
return person_id
if len(sys.argv) is not 1:
currentDir = os.path.dirname(os.path.abspath(__file__))
imageFolder = os.path.join(currentDir, "dataset/" + str(sys.argv[1]))
person_id = get_person_id()
for filename in os.listdir(imageFolder):
if filename.endswith(".jpg"):
print(filename)
img_data = open(os.path.join(imageFolder,filename), "rb")
res = face_client.face.detect_with_stream(img_data)
if not res:
print('No face detected from image {}'.format(filename))
continue
res = face_client.person_group_person.add_face_from_stream(global_var.personGroupId, person_id, img_data)
print(res)
time.sleep(6)
else:
print("supply attributes please from dataset folder")
After looking through the API calls you are making, I realized there are some elements missing. You might not have posted the entire code, but I will add a sample below that illustrates the steps. Using the steps avoids any image errors, so the 'wrong size' image error could have likely been from missing steps.
In your code, before you can add an image to a Person Group Person (PGP), you have to create a Person Group(PG) for that PGP to belong to. Then after you create the Person Group (it is empty at the start), you must create a Person Group Person with that PG ID in it. Once those two things are created, then you can start adding images to your Person Group Person.
So here are the steps summarized above:
Create a Person Group with the API call create()
Create a Person Group Person with its API call for create()
Add your image(s) to the Person Group Person with the API call add_face_from_stream()
Once you have added all your images that belong to your Person Group Person, then you can use data from it however you like.
See the code sample below, where a single local image is uploaded and added to a Person Group Person. I'll include the image I am using if you wanted to download and test.
import os
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
KEY = os.environ['FACE_SUBSCRIPTION_KEY']
ENDPOINT = os.environ['FACE_ENDPOINT']
face_client = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))
person_group_id = 'women_person_group'
person_id = 'women_hats'
image_name = 'woman_with_sunhat.jpg'
# Create empty Person Group. Person Group ID must be lower case, alphanumeric, and/or with '-', '_'.
print('Creating a Person Group:', person_group_id)
face_client.person_group.create(person_group_id=person_group_id, name=person_group_id)
# Create a Person Group Person.
print('Creating the Person Group Person:', person_id)
women_hat_group = face_client.person_group_person.create(person_group_id, person_id)
# Add image to our Person Group Person.
print('Adding face to the Person Group Person:', person_id)
face_image = open(image_name, 'r+b')
face_client.person_group_person.add_face_from_stream(person_group_id, women_hat_group.person_id, face_image)
# Print ID from face.
print('Person ID:', women_hat_group.person_id)
# Since testing, delete the Person Group, so no duplication conflicts if script is run again.
face_client.person_group.delete(person_group_id)
print()
print("Deleted the person group {} from the Azure Face account.".format(person_group_id))

How can i filter the ellbv2(Application ELB) based on their State: Active using Python?

I need to filter ELBV2 based on their state: Active.
Python Code:
import boto3
elbv2 = boto3.client('elbv2')
bals = elbv2.describe_load_balancers()
for elb in bals['LoadBalancers']:
set2 = elb['LoadBalancerName']
elbv2_count.append(set2)
elb2 = len(elbv2_count)
print('elbV2->'+str(len(elbv2_count)))
What i am trying:
available = [i['LoadBalancers'] for i in bals['LoadBalancerName'] if
i['State']=='active']
getting an error:
KeyError: 'LoadBalancerName'
Finally, it worked with help from Stack overflow users.
What I changed:
bals = elbv2.describe_load_balancers()
available = [i['LoadBalancerName'] for i in bals['LoadBalancers'] if i['State']
['Code']=='active']
print("elbv2 try ->" + str(len(available)))
hola!!! It worked. just interchanged the name and elb in for loop and added ['Code']

Python evernote api Error

Trying to build app that connects with Evernote API, in Python/Django. For the below code i get the following error message: " 'Store' object has no attribute 'NoteFilter' " from http://dev.evernote.com/documentation/reference/NoteStore.html#Svc_NoteStore One can see, that NoteFilter is attribute of NoteStore.
def list(request):
nbname="mihkel's notebook"
client = EvernoteClient(token=token, sandbox=False)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks()
for nb in notebooks:
if nbname == nb.name:
nb = nb
filter = note_store.NoteFilter()
filter.notebookGuid = nb.guid
notelist = note_store.findNotes(token,filter,0,10)
break
return render_to_response('list.html', {'nb': nb, 'notelist':notelist})
Solution:
from evernote.edam.notestore import NoteStore
....
....
def list.. :
...
Filter = NoteStore.NoteFilter()
notestore/ttypes.py has the definition for NoteFilter
Some of the examples in the API code import like this
import evernote.edam.notestore.NoteStore as NoteStore
import evernote.edam.type.ttypes as Types
Not sure if this would be an acceptable way to correct, but I added this:
import evernote.edam.notestore.ttypes as NoteStoreTypes
and created my filter like this:
filter = NoteStoreTypes.NoteFilter()

Python: How to get group ids of one username (like id -Gn )

getpwname can only get the gid of a username.
import pwd
myGroupId = pwd.getpwnam(username).pw_gid
getgroups can only get groups of the script user.
import os
myGroupIds = os.getgroups()
How can I get all groups of one arbitrary username, like the id -Gn command?
id -Gn `whoami`
The following works assuming you are only interested in local users only, it will not work for things such as sssd backed by a catalog server (for instance, ldap).
#!/usr/bin/env python
import grp, pwd
user = "myname"
groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
print groups
If you want the current user's groups.
import os, grp
[grp.getgrgid(g).gr_name for g in os.getgroups()]
os.getgroups() returns the list of gids of the current user.
grp.getgrgid(g) returns details about a group
The only way I found to make this work correctly when having users non local to the system (e.g. ldap, sssd+ldap, freeIPA) without calling id in a subprocess is by calling the getgrouplist c function (which is called by id eventually after going trough some abstractions):
#!/usr/bin/python
import grp, pwd, os
from ctypes import *
from ctypes.util import find_library
libc = cdll.LoadLibrary(find_library('libc'))
getgrouplist = libc.getgrouplist
# 50 groups should be enough, if not, we'll repeat the request with the correct nr bellow
ngroups = 50
getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint * ngroups), POINTER(c_int)]
getgrouplist.restype = c_int32
grouplist = (c_uint * ngroups)()
ngrouplist = c_int(ngroups)
user = pwd.getpwuid(2540485)
ct = getgrouplist(bytes(user.pw_name, 'UTF-8'), user.pw_gid, byref(grouplist), byref(ngrouplist))
# if 50 groups was not enough this will be -1, try again
# luckily the last call put the correct number of groups in ngrouplist
if ct < 0:
getgrouplist.argtypes = [c_char_p, c_uint, POINTER(c_uint *int(ngrouplist.value)), POINTER(c_int)]
grouplist = (c_uint * int(ngrouplist.value))()
ct = getgrouplist(user.pw_name, user.pw_gid, byref(grouplist), byref(ngrouplist))
for i in range(0, ct):
gid = grouplist[i]
print(grp.getgrgid(gid).gr_name)
The result of id -Gn when the user belongs to one or more groups in which several group names map to the same gid might not be the same as the posted answer. For instance if /etc/groups is similar to this:
% ypcat group | grep mygroup
mygroup:*:66485:user1,user2,user3,...
mygroup1:*:66485:user101,user102,user103,...
mygroup2:*:66485:user201,user202,user203,...
...
And if the user is not listed in mygroup but in mygroup<n>, id -Gn returns mygroup but the posted answer returns mygroup<n>.
It seems that in my environment, because UNIX groups can have hundreds or thousands of users, this is a common group management policy, although I don't know exactly what is the user limit per group and why id -Gn always returns mygroup.
Nevertheless, with the code below I got a match with id -Gn:
import pwd, grp
def getgroups(user):
gids = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
gid = pwd.getpwnam(user).pw_gid
gids.append(grp.getgrgid(gid).gr_gid)
return [grp.getgrgid(gid).gr_name for gid in gids]
Since Python 3.3:
import os
import pwd
uid = os.getuid()
user = pwd.getpwuid(uid)
gl = os.getgrouplist(user.pw_name, user.pw_gid)
print(gl)

Categories