Merged PR 3143: Million Scale Python SDK update.

This commit is contained in:
Xuan (Sean) Hu 2017-10-11 13:23:22 +00:00 коммит произвёл huxuan
Родитель e985c8e4fb
Коммит 0b6a6bb426
20 изменённых файлов: 1218 добавлений и 66 удалений

Просмотреть файл

@ -7,6 +7,11 @@ Description: Python SDK of the Cognitive Face API.
from . import face
from . import face_list
from . import large_face_list
from . import large_face_list_face
from . import large_person_group
from . import large_person_group_person
from . import large_person_group_person_face
from . import person
from . import person_group
from . import util

Просмотреть файл

@ -43,14 +43,15 @@ def detect(image, face_id=True, landmarks=False, attributes=''):
def find_similars(face_id,
face_list_id=None,
large_face_list_id=None,
face_ids=None,
max_candidates_return=20,
mode='matchPerson'):
"""Given query face's `face_id`, to search the similar-looking faces from a
`face_id` array or a `face_list_id`.
`face_id` array, a `face_list_id` or a `large_face_list_id`.
Parameter `face_list_id` and `face_ids` should not be provided at the same
time.
Parameter `large_face_list_id`, `face_list_id` and `face_ids` should not be
provided at the same time.
Args:
face_id: `face_id` of the query face. User needs to call `face.detect`
@ -59,6 +60,10 @@ def find_similars(face_id,
face_list_id: An existing user-specified unique candidate face list,
created in `face_list.create`. Face list contains a set of
`persisted_face_ids` which are persisted and will never expire.
large_face_list_id: An existing user-specified unique candidate face
list, created in `large_face_list.create`. Large Face list contains
a set of `persisted_face_ids` which are persisted and will never
expire.
face_ids: An array of candidate `face_id`s. All of them are created by
`face.detect` and the `face_id`s will expire in 24 hours after the
detection call. The number of `face_id`s is limited to 1000.
@ -70,12 +75,13 @@ def find_similars(face_id,
Returns:
An array of the most similar faces represented in `face_id` if the
input parameter is `face_ids` or `persisted_face_id` if the input
parameter is `face_list_id`.
parameter is `face_list_id` or `large_face_list_id`.
"""
url = 'findsimilars'
json = {
'faceId': face_id,
'faceListId': face_list_id,
'largeFaceListId': large_face_list_id,
'faceIds': face_ids,
'maxNumOfCandidatesReturned': max_candidates_return,
'mode': mode,
@ -104,10 +110,11 @@ def group(face_ids):
def identify(face_ids,
person_group_id,
person_group_id=None,
large_person_group_id=None,
max_candidates_return=1,
threshold=None):
"""Identify unknown faces from a person group.
"""Identify unknown faces from a person group or a large person group.
Args:
face_ids: An array of query `face_id`s, created by the `face.detect`.
@ -115,6 +122,8 @@ def identify(face_ids,
`face_ids` is between [1, 10].
person_group_id: `person_group_id` of the target person group, created
by `person_group.create`.
large_person_group_id: `large_person_group_id` of the target large
person group, createdJ by `large_person_group.create`.
max_candidates_return: Optional parameter. The range of
`max_candidates_return` is between 1 and 5 (default is 1).
threshold: Optional parameter. Confidence threshold of identification,
@ -127,6 +136,7 @@ def identify(face_ids,
url = 'identify'
json = {
'personGroupId': person_group_id,
'largePersonGroupId': large_person_group_id,
'faceIds': face_ids,
'maxNumOfCandidatesReturned': max_candidates_return,
'confidenceThreshold': threshold,
@ -135,14 +145,17 @@ def identify(face_ids,
return util.request('POST', url, json=json)
def verify(face_id, another_face_id=None, person_group_id=None,
def verify(face_id,
another_face_id=None,
person_group_id=None,
large_person_group_id=None,
person_id=None):
"""Verify whether two faces belong to a same person or whether one face
belongs to a person.
For face to face verification, only `face_id` and `another_face_id` is
necessary. For face to person verification, only `face_id`,
`person_group_id` and `person_id` is needed.
`person_group_id` (or `large_person_group_id`) and `person_id` is needed.
Args:
face_id: `face_id` of one face, comes from `face.detect`.
@ -150,6 +163,9 @@ def verify(face_id, another_face_id=None, person_group_id=None,
person_group_id: Using existing `person_group_id` and `person_id` for
fast loading a specified person. `person_group_id` is created in
`person_group.create`.
large_person_group_id: Using existing `large_person_group_id` and
`person_id` for fast loading a specified person.
`large_person_group_id` is created in `large_person_group.create`.
person_id: Specify a certain person in a person group. `person_id` is
created in `person.create`.
@ -167,6 +183,7 @@ def verify(face_id, another_face_id=None, person_group_id=None,
json.update({
'faceId': face_id,
'personGroupId': person_group_id,
'largePersonGroupId': large_person_group_id,
'personId': person_id,
})

Просмотреть файл

@ -0,0 +1,141 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: large_face_list.py
Description: Large Face List section of the Cognitive Face API.
"""
from . import util
def create(large_face_list_id, name=None, user_data=None):
"""Create an empty large face list with user-specified
`large_face_list_id`, `name` and an optional `user_data`.
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
name: Name of the created large face list, maximum length is 128.
user_data: Optional parameter. User-defined data for the large face
list. Length should not exceed 16KB.
Returns:
An empty response body.
"""
name = name or large_face_list_id
url = 'largefacelists/{}'.format(large_face_list_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('PUT', url, json=json)
def delete(large_face_list_id):
"""Delete an existing large face list according to `large_face_list_id`.
Persisted face images in the large face list will also be deleted.
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
Returns:
An empty response body.
"""
url = 'largefacelists/{}'.format(large_face_list_id)
return util.request('DELETE', url)
def get(large_face_list_id):
"""Retrieve a large face list's information, including
`large_face_list_id`, `name`, `user_data`. Large face list simply
represents a list of faces, and could be treated as a searchable data
source in `face.find_similars`.
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
Returns:
The large face list's information.
"""
url = 'largefacelists/{}'.format(large_face_list_id)
return util.request('GET', url)
def get_status(large_face_list_id):
"""Retrieve the training status of a large face list (completed or
ongoing). Training can be triggered by `large_face_list.train`. The
training will process for a while on the server side.
Args:
large_face_list_id: `large_face_list_id` of the target large face list.
Returns:
The large face list's training status.
"""
url = 'largefacelists/{}/training'.format(large_face_list_id)
return util.request('GET', url)
def list(start=None, top=None):
"""Retrieve information about all existing large face lists. Only
`large_face_list_id`, `name` and `user_data` will be returned.
Args:
start: Optional parameter. List large face lists from the least
`large_face_list_id` greater than the "start". It contains no more
than 64 characters. Default is empty.
top: The number of large face lists to list, ranging in [1, 1000].
Default is 1000.
Returns:
An array of large face lists.
"""
url = 'largefacelists'
params = {
'start': start,
'top': top,
}
return util.request('GET', url, params=params)
def train(large_face_list_id):
"""Queue a large face list training task, the training task may not be
started immediately.
Args:
large_face_list_id: Target large face list to be trained.
Returns:
An empty JSON body.
"""
url = 'largefacelists/{}/train'.format(large_face_list_id)
return util.request('POST', url)
def update(large_face_list_id, name=None, user_data=None):
"""Update information of a large face list, including `name` and `user_data`.
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
name: Name of the created large face list, maximum length is 128.
user_data: Optional parameter. User-defined data for the large face
list. Length should not exceed 16KB.
Returns:
An empty response body.
"""
url = 'largefacelists/{}'.format(large_face_list_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('PATCH', url, json=json)

Просмотреть файл

@ -0,0 +1,131 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: large_face_list_face.py
Description: Large Face List Face section of the Cognitive Face API.
"""
from . import util
def add(image, large_face_list_id, user_data=None, target_face=None):
"""Add a face to a large face list.
The input face is specified as an image with a `target_face` rectangle. It
returns a `persisted_face_id` representing the added face, and
`persisted_face_id` will not expire.
Args:
image: A URL or a file path or a file-like object represents an image.
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
user_data: Optional parameter. User-specified data about the large face
list for any purpose. The maximum length is 1KB.
target_face: Optional parameter. A face rectangle to specify the target
face to be added into the large face list, in the format of
"left,top,width,height". E.g. "10,10,100,100". If there are more
than one faces in the image, `target_face` is required to specify
which face to add. No `target_face` means there is only one face
detected in the entire image.
Returns:
A new `persisted_face_id`.
"""
url = 'largefacelists/{}/persistedFaces'.format(large_face_list_id)
headers, data, json = util.parse_image(image)
params = {
'userData': user_data,
'targetFace': target_face,
}
return util.request(
'POST', url, headers=headers, params=params, json=json, data=data)
def delete(large_face_list_id, persisted_face_id):
"""Delete an existing face from a large face list (given by a
`persisted_face_id` and a `large_face_list_id`). Persisted image related to
the face will also be deleted.
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
persisted_face_id: `persisted_face_id` of an existing face. Valid
character is letter in lower case or digit or '-' or '_', maximum
length is 64.
Returns:
An empty response body.
"""
url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id,
persisted_face_id)
return util.request('DELETE', url)
def get(large_face_list_id, persisted_face_id):
"""Retrieve information about a persisted face (specified by
`persisted_face_id` and a `large_face_list_id`).
Args:
large_face_list_id: Valid character is letter in lower case or digit or
'-' or '_', maximum length is 64.
persisted_face_id: `persisted_face_id` of an existing face. Valid
character is letter in lower case or digit or '-' or '_', maximum
length is 64.
Returns:
The target persisted face's information (`persisted_face_id` and
`user_data`).
"""
url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id,
persisted_face_id)
return util.request('GET', url)
def list(large_face_list_id, start=None, top=None):
"""Retrieve information (`persisted_face_id` and `user_data`) about
existing persisted faces in a large face list.
Args:
start: Optional parameter. List large face lists from the least
`large_face_list_id` greater than the "start". It contains no more
than 64 characters. Default is empty.
top: The number of large face lists to list, ranging in [1, 1000].
Default is 1000.
Returns:
An array of persisted faces and their information (`persisted_face_id`
and `user_data`).
"""
url = 'largefacelists/{}/persistedFaces'.format(large_face_list_id)
params = {
'start': start,
'top': top,
}
return util.request('GET', url, params=params)
def update(large_face_list_id, persisted_face_id, user_data=None):
"""Update a persisted face's `user_data` field in a large face list.
Args:
large_face_list_id: largeFaceListId of an existing large face list.
person.
person_id: `person_id` of the target person.
persisted_face_id: `persisted_face_id` of the target face, which is
persisted and will not expire.
user_data: Optional parameter. Attach `user_data` to person's
persisted face. The size limit is 1KB.
Returns:
An empty response body.
"""
url = 'largefacelists/{}/persistedFaces/{}'.format(large_face_list_id,
persisted_face_id)
json = {
'userData': user_data,
}
return util.request('PATCH', url, json=json)

Просмотреть файл

@ -0,0 +1,143 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: large_person_group.py
Description: Large Person Group section of the Cognitive Face API.
"""
from . import util
def create(large_person_group_id, name=None, user_data=None):
"""Create a new large person group with specified `large_person_group_id`,
`name` and user-provided `user_data`.
Args:
large_person_group_id: User-provided `large_person_group_id` as a
string. The valid characters include numbers, English letters in
lower case, '-' and '_'. The maximum length is 64.
name: Name of the created large person group, maximum length is 128.
user_data: Optional user defined data for the large person group.
Length should not exceed 16KB.
Returns:
An empty response body.
"""
name = name or large_person_group_id
url = 'largepersongroups/{}'.format(large_person_group_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('PUT', url, json=json)
def delete(large_person_group_id):
"""Delete an existing large person group. Persisted face images of all
people in the large person group will also be deleted.
Args:
large_person_group_id: The `large_person_group_id` of the large person
group to be deleted.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}'.format(large_person_group_id)
return util.request('DELETE', url)
def get(large_person_group_id):
"""Retrieve the information of a large person group, including its `name`
and `user_data`.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
Returns:
The large person group's information.
"""
url = 'largepersongroups/{}'.format(large_person_group_id)
return util.request('GET', url)
def get_status(large_person_group_id):
"""Retrieve the training status of the large person group (completed or
ongoing). Training can be triggered by `large_person_group.train`. The
training will process for a while on the server side.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
Returns:
The large person group's training status.
"""
url = 'largepersongroups/{}/training'.format(large_person_group_id)
return util.request('GET', url)
def list(start=None, top=None):
"""List large person groups and their information.
Args:
start: Optional parameter. List large person groups from the least
`large_person_group_id` greater than the "start". It contains no
more than 64 characters. Default is empty.
top: The number of large person groups to list, ranging in [1, 1000].
Default is 1000.
Returns:
An array of large person groups and their information
(`large_person_group_id`, `name` and `user_data`).
"""
url = 'largepersongroups'
params = {
'start': start,
'top': top,
}
return util.request('GET', url, params=params)
def train(large_person_group_id):
"""Queue a large person group training task, the training task may not be
started immediately.
Args:
large_person_group_id: Target large person group to be trained.
Returns:
An empty JSON body.
"""
url = 'largepersongroups/{}/train'.format(large_person_group_id)
return util.request('POST', url)
def update(large_person_group_id, name=None, user_data=None):
"""Update an existing large person group's `name` and `user_data`. The
properties which does not appear in request body will not be updated.
Args:
large_person_group_id: `large_person_group_id` of the large person
group to be updated.
name: Optional parameter. Large person group display name. The maximum
length is 128.
user_data: Optional parameter. User-provided data attached to the large
person group. The size limit is 16KB.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}'.format(large_person_group_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('PATCH', url, json=json)

Просмотреть файл

@ -0,0 +1,114 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: large_person_group_person.py
Description: Large Person Group Person section of the Cognitive Face API.
"""
from . import util
def create(large_person_group_id, name, user_data=None):
"""Create a new person in a specified large person group. A newly created
person have no registered face.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
name: Name of the created person, maximum length is 128.
user_data: Optional user defined data for the person. Length should not
exceed 16KB.
Returns:
A new `person_id` created.
"""
url = 'largepersongroups/{}/persons'.format(large_person_group_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('POST', url, json=json)
def delete(large_person_group_id, person_id):
"""Delete an existing person from a large person group. Persisted face
images of the person will also be deleted.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: personId of the target person.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}/persons/{}'.format(large_person_group_id,
person_id)
return util.request('DELETE', url)
def get(large_person_group_id, person_id):
"""Retrieve a person's information, including registered persisted faces,
`name` and `user_data`.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: Specifying the target person.
Returns:
The person's information.
"""
url = 'largepersongroups/{}/persons/{}'.format(large_person_group_id,
person_id)
return util.request('GET', url)
def list(large_person_group_id, start=None, top=None):
"""List `top` persons in a large person group with `person_id` greater than
`start`, and retrieve person information (including `person_id`, `name`,
`user_data` and `persisted_face_ids` of registered faces of the person).
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
start: List persons from the least `person_id` greater than this.
top: The number of persons to list, rangeing in [1, 1000]. Default is
1000.
Returns:
An array of person information that belong to the large person group.
"""
url = 'largepersongroups/{}/persons'.format(large_person_group_id)
params = {
'start': start,
'top': top,
}
return util.request('GET', url, params=params)
def update(large_person_group_id, person_id, name=None, user_data=None):
"""Update `name` or `user_data` of a person.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: `person_id` of the target person.
name: Name of the created person, maximum length is 128.
user_data: Optional user defined data for the person. Length should not
exceed 16KB.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}/persons/{}'.format(large_person_group_id,
person_id)
json = {
'name': name,
'userData': user_data,
}
return util.request('PATCH', url, json=json)

Просмотреть файл

@ -0,0 +1,111 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: large_person_group_person_face.py
Description: Large Person Group Person Face section of the Cognitive Face API.
"""
from . import util
def add(image,
large_person_group_id,
person_id,
user_data=None,
target_face=None):
"""Add a representative face to a person for identification. The input face
is specified as an image with a `target_face` rectangle. It returns a
`persisted_face_id` representing the added face and this
`persisted_face_id` will not expire.
Args:
image: A URL or a file path or a file-like object represents an image.
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: `person_id` of the target person.
user_data: Optional parameter. User-specified data about the face list
for any purpose. The maximum length is 1KB.
target_face: Optional parameter. A face rectangle to specify the target
face to be added into the face list, in the format of
"left,top,width,height". E.g. "10,10,100,100". If there are more
than one faces in the image, `target_face` is required to specify
which face to add. No `target_face` means there is only one face
detected in the entire image.
Returns:
A new `persisted_face_id`.
"""
url = 'largepersongroups/{}/persons/{}/persistedFaces'.format(
large_person_group_id, person_id)
headers, data, json = util.parse_image(image)
params = {
'userData': user_data,
'targetFace': target_face,
}
return util.request(
'POST', url, headers=headers, params=params, json=json, data=data)
def delete(large_person_group_id, person_id, persisted_face_id):
"""Delete a face from a person. Relative image for the persisted face will
also be deleted.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: `person_id` of the target person.
persisted_face_id: The persisted face to remove.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}/persons/{}/persistedFaces/{}'.format(
large_person_group_id, person_id, persisted_face_id)
return util.request('DELETE', url)
def get(large_person_group_id, person_id, persisted_face_id):
"""Retrieve information about a persisted face (specified by
`persisted_face_ids`, `person_id` and its belonging
`large_person_group_id`).
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: `person_id` of the target person.
persisted_face_id: The `persisted_face_id` of the target persisted face
of the person.
Returns:
The target persisted face's information (`persisted_face_id` and
`user_data`).
"""
url = 'largepersongroups/{}/persons/{}/persistedFaces/{}'.format(
large_person_group_id, person_id, persisted_face_id)
return util.request('GET', url)
def update(large_person_group_id, person_id, persisted_face_id, user_data):
"""Update a person persisted face's `user_data` field.
Args:
large_person_group_id: `large_person_group_id` of the target large
person group.
person_id: `person_id` of the target person.
persisted_face_id: The `persisted_face_id` of the target persisted face
of the person.
user_data: Attach `user_data` to person's persisted face. The size
limit is 1KB.
Returns:
An empty response body.
"""
url = 'largepersongroups/{}/persons/{}/persistedFaces/{}'.format(
large_person_group_id, person_id, persisted_face_id)
json = {
'userData': user_data,
}
return util.request('PATCH', url, json=json)

Просмотреть файл

@ -10,8 +10,7 @@ try:
except ImportError:
raise Exception(
'Please setup unittest configuration `config.py` properly by '
'referring to `config.sample.py` so as to perform the unittests.'
)
'referring to `config.sample.py` so as to perform the unittests.')
import cognitive_face as CF
@ -29,9 +28,11 @@ def setUpModule():
print("setUpModule Begin.")
CF.Key.set(config.KEY)
CF.BaseUrl.set(config.BASE_URL)
util.DataStore.setup_person_group()
util.DataStore.setup_face_list()
util.DataStore.setup_face()
util.DataStore.setup_face_list()
util.DataStore.setup_large_face_list()
util.DataStore.setup_large_person_group()
util.DataStore.setup_person_group()
print("setUpModule End.")
@ -44,4 +45,6 @@ def tearDownModule():
print("tearDownModule Begin.")
CF.util.clear_face_lists()
CF.util.clear_person_groups()
CF.util.clear_large_face_lists()
CF.util.clear_large_person_groups()
print("tearDownModule End.")

Просмотреть файл

@ -23,12 +23,30 @@ class TestFace(unittest.TestCase):
self.assertIsInstance(res, list)
util.wait()
def test_find_similars(self):
"""Unittest for `face.find_similars`."""
def test_find_similars_face_ids(self):
"""Unittest for `face.find_similars` with face ids."""
res = CF.face.find_similars(
util.DataStore.face_id, face_ids=util.DataStore.face_ids)
print(res)
self.assertIsInstance(res, list)
util.wait()
def test_find_similars_face_list(self):
"""Unittest for `face.find_similars` in face list."""
res = CF.face.find_similars(
util.DataStore.face_id, face_list_id=util.DataStore.face_list_id)
print(res)
self.assertIsInstance(res, list)
util.wait()
def test_find_similars_large_face_list(self):
"""Unittest for `face.find_similars` in large face list."""
CF.util.wait_for_large_face_list_training(
util.DataStore.large_face_list_id)
res = CF.face.find_similars(
util.DataStore.face_id,
face_ids=util.DataStore.face_ids
)
large_face_list_id=util.DataStore.large_face_list_id)
print(res)
self.assertIsInstance(res, list)
util.wait()
@ -43,28 +61,63 @@ class TestFace(unittest.TestCase):
self.assertIsInstance(res, dict)
util.wait()
def test_identify(self):
"""Unittest for `face.identify`."""
CF.util.wait_for_training(util.DataStore.person_group_id)
def test_identify_person_group(self):
"""Unittest for `face.identify` in person gorup."""
CF.util.wait_for_person_group_training(util.DataStore.person_group_id)
res = CF.face.identify(
util.DataStore.face_ids,
util.DataStore.person_group_id,
)
person_group_id=util.DataStore.person_group_id)
print(res)
self.assertIsInstance(res, list)
util.wait()
def test_verify(self):
"""Unittest for `face.verify`."""
def test_identify_large_person_group(self):
"""Unittest for `face.identify` in large person gorup."""
CF.util.wait_for_large_person_group_training(
util.DataStore.large_person_group_id)
res = CF.face.identify(
util.DataStore.face_ids,
large_person_group_id=util.DataStore.large_person_group_id)
print(res)
self.assertIsInstance(res, list)
util.wait()
def test_verify_face_ids(self):
"""Unittest for `face.verify` with face ids."""
res = CF.face.verify(
util.DataStore.face_id,
person_group_id=util.DataStore.person_group_id,
person_id=util.DataStore.person_id['Dad'],
)
another_face_id=util.DataStore.another_face_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_verify_person_group(self):
"""Unittest for `face.verify` in person group."""
CF.util.wait_for_person_group_training(util.DataStore.person_group_id)
res = CF.face.verify(
util.DataStore.face_id,
person_group_id=util.DataStore.person_group_id,
person_id=util.DataStore.person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_verify_large_person_group(self):
"""Unittest for `face.verify` in large person group."""
CF.util.wait_for_large_person_group_training(
util.DataStore.large_person_group_id)
res = CF.face.verify(
util.DataStore.face_id,
large_person_group_id=util.DataStore.large_person_group_id,
person_id=util.DataStore.large_person_group_person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
if __name__ == '__main__':
unittest.main()

Просмотреть файл

@ -28,10 +28,8 @@ class TestFaceList(unittest.TestCase):
persisted_face_id = res['persistedFaceId']
res = CF.face_list.delete_face(
util.DataStore.face_list_id,
persisted_face_id,
)
res = CF.face_list.delete_face(util.DataStore.face_list_id,
persisted_face_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()

Просмотреть файл

@ -0,0 +1,68 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: test_large_face_list.py
Description: Unittests for Large Face List section of the Cognitive Face API.
"""
import uuid
import unittest
import cognitive_face as CF
from . import util
class TestFaceList(unittest.TestCase):
"""Unittests for Large Face List section."""
def test_large_face_list(self):
"""Unittests for `large_face_list.create`, `large_face_list.train`,
`large_face_list.update`, large_face_list.get_status` and
`large_face_list.delete`.
"""
large_face_list_id = str(uuid.uuid1())
res = CF.large_face_list.create(large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
# Fake a face to satisfy training.
image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format(
util.BASE_URL_IMAGE)
res = CF.large_face_list_face.add(image, large_face_list_id)
res = CF.large_face_list.train(large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_face_list.update(large_face_list_id, 'test')
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_face_list.get_status(large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_face_list.delete(large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_get(self):
"""Unittest for `large_face_list.get`."""
res = CF.large_face_list.get(util.DataStore.large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_list(self):
"""Unittest for `large_face_list.list`."""
res = CF.large_face_list.list()
print(res)
self.assertIsInstance(res, list)
util.wait()

Просмотреть файл

@ -0,0 +1,59 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: test_large_face_list_face.py
Description: Unittests for Large Face List Face section of the Cognitive Face
API.
"""
import unittest
import cognitive_face as CF
from . import util
class TestFaceList(unittest.TestCase):
"""Unittests for Large Face List Face section."""
def test_face(self):
"""Unittests for `large_face_list_face.add`,
`large_face_list_face.update` and `large_face_list_face.delete`."""
image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format(
util.BASE_URL_IMAGE)
res = CF.large_face_list_face.add(image,
util.DataStore.large_face_list_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
persisted_face_id = res['persistedFaceId']
res = CF.large_face_list_face.update(util.DataStore.large_face_list_id,
persisted_face_id, "TempUserData")
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_face_list_face.delete(util.DataStore.large_face_list_id,
persisted_face_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_get(self):
"""Unittests for `large_face_list_face.get`."""
res = CF.large_face_list_face.get(
util.DataStore.large_face_list_id,
util.DataStore.large_face_list_face_id['Dad'][0])
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_list(self):
"""Unittest for `large_face_list_face.list`."""
res = CF.large_face_list_face.list(util.DataStore.large_face_list_id)
print(res)
self.assertIsInstance(res, list)
util.wait()

Просмотреть файл

@ -0,0 +1,73 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: test_large_person_group.py
Description: Unittests for Large Person Group section of the Cognitive Face
API.
"""
import uuid
import unittest
import cognitive_face as CF
from . import util
class TestLargePersonGroup(unittest.TestCase):
"""Unittests for Large Person Group section."""
def test_large_person_group(self):
"""Unittests for `large_person_group.create`,
`large_person_group.train`, `large_person_group.update`,
`large_person_group.get_status` and `large_person_group.delete`.
"""
large_person_group_id = str(uuid.uuid1())
res = CF.large_person_group.create(large_person_group_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
# Fake a person and a face to satisfy training.
res = CF.large_person_group_person.create(large_person_group_id,
'TempPerson')
person_id = res['personId']
image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format(
util.BASE_URL_IMAGE)
res = CF.large_person_group_person_face.add(
image, large_person_group_id, person_id)
res = CF.large_person_group.train(large_person_group_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_person_group.update(large_person_group_id, 'name')
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_person_group.get_status(large_person_group_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_person_group.delete(large_person_group_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_get(self):
"""Unittest for `large_person_group.get`."""
res = CF.large_person_group.get(util.DataStore.large_person_group_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_list(self):
"""Unittest for `large_person_group.list`."""
res = CF.large_person_group.list()
print(res)
self.assertIsInstance(res, list)
util.wait()

Просмотреть файл

@ -0,0 +1,59 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: test_large_person_group_person.py
Description: Unittests for Large Person Group Person section of the Cognitive
Face API.
"""
import unittest
import cognitive_face as CF
from . import util
class TestLargePersonGroupPerson(unittest.TestCase):
"""Unittests for Large Person Group Person section."""
def test_person(self):
"""Unittests for `large_person_group_person.create`,
`large_person_group_person.update` and
`large_person_group_person.delete`.
"""
res = CF.large_person_group_person.create(
util.DataStore.large_person_group_id, 'TempPerson')
print(res)
self.assertIsInstance(res, dict)
util.wait()
person_id = res['personId']
res = CF.large_person_group_person.update(
util.DataStore.large_person_group_id, person_id, 'TP')
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_person_group_person.delete(
util.DataStore.large_person_group_id, person_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_get(self):
"""Unittest for `large_person_group_person.get`."""
res = CF.large_person_group_person.get(
util.DataStore.large_person_group_id,
util.DataStore.large_person_group_person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_list(self):
"""Unittest for `large_person_group_person.list`."""
res = CF.large_person_group_person.list(
util.DataStore.large_person_group_id)
print(res)
self.assertIsInstance(res, list)
util.wait()

Просмотреть файл

@ -0,0 +1,60 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: test_large_person_group_person_face.py
Description: Unittests for Large Person Group Person Face section of the
Cognitive Face API.
"""
import unittest
import cognitive_face as CF
from . import util
class TestLargePersonGroupPersonFace(unittest.TestCase):
"""Unittests for Large Person Group Person Face section."""
def test_face(self):
"""Unittests for `large_person_group_person_face.add`,
`large_person_group_person_face.update` and
`large_person_group_person_face.delete`.
"""
image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format(
util.BASE_URL_IMAGE)
res = CF.large_person_group_person_face.add(
image, util.DataStore.large_person_group_id,
util.DataStore.large_person_group_person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
persisted_face_id = res['persistedFaceId']
res = CF.large_person_group_person_face.update(
util.DataStore.large_person_group_id,
util.DataStore.large_person_group_person_id['Dad'],
persisted_face_id, 'TempUserData')
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.large_person_group_person_face.delete(
util.DataStore.large_person_group_id,
util.DataStore.large_person_group_person_id['Dad'],
persisted_face_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
def test_get(self):
"""Unittest for `large_person_group_person_face.get`."""
res = CF.large_person_group_person_face.get(
util.DataStore.large_person_group_id,
util.DataStore.large_person_group_person_id['Dad'],
util.DataStore.large_person_group_person_face_id['Dad'][0])
print(res)
self.assertIsInstance(res, dict)
util.wait()

Просмотреть файл

@ -22,32 +22,24 @@ class TestPerson(unittest.TestCase):
image = '{}PersonGroup/Family1-Dad/Family1-Dad3.jpg'.format(
util.BASE_URL_IMAGE)
res = CF.person.add_face(
image,
util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
)
res = CF.person.add_face(image, util.DataStore.person_group_id,
util.DataStore.person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
persisted_face_id = res['persistedFaceId']
res = CF.person.update_face(
util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
persisted_face_id,
'TempUserData',
)
res = CF.person.update_face(util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
persisted_face_id, 'TempUserData')
print(res)
self.assertIsInstance(res, dict)
util.wait()
res = CF.person.delete_face(
util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
persisted_face_id,
)
res = CF.person.delete_face(util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
persisted_face_id)
print(res)
self.assertIsInstance(res, dict)
util.wait()
@ -75,10 +67,8 @@ class TestPerson(unittest.TestCase):
def test_get(self):
"""Unittest for `person.get`."""
res = CF.person.get(
util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
)
res = CF.person.get(util.DataStore.person_group_id,
util.DataStore.person_id['Dad'])
print(res)
self.assertIsInstance(res, dict)
util.wait()
@ -86,10 +76,8 @@ class TestPerson(unittest.TestCase):
def test_get_face(self):
"""Unittest for `person.get_face`."""
res = CF.person.get_face(
util.DataStore.person_group_id,
util.DataStore.person_id['Dad'],
util.DataStore.person_persisted_face_id['Dad'][0],
)
util.DataStore.person_group_id, util.DataStore.person_id['Dad'],
util.DataStore.person_persisted_face_id['Dad'][0])
print(res)
self.assertIsInstance(res, dict)
util.wait()

Просмотреть файл

@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: person_group.py
File: test_person_group.py
Description: Unittests for Person Group section of the Cognitive Face API.
"""

Просмотреть файл

@ -14,10 +14,8 @@ import cognitive_face as CF
from . import config
# Base URL of online images.
BASE_URL_IMAGE = (
'https://raw.githubusercontent.com/'
'Microsoft/Cognitive-Face-Windows/master/Data/'
)
BASE_URL_IMAGE = ('https://raw.githubusercontent.com/'
'Microsoft/Cognitive-Face-Windows/master/Data/')
# Notification of wait.
MSG_WAIT = 'Wait for {} seconds so as to avoid exceeding free quote.'
@ -108,8 +106,8 @@ class DataStore(object):
image = '{}PersonGroup/Family1-{}/Family1-{}{}.jpg'.format(
BASE_URL_IMAGE, name, name, idx)
res = CF.person.add_face(
image, cls.person_group_id, cls.person_id[name])
res = CF.person.add_face(image, cls.person_group_id,
cls.person_id[name])
cls.person_persisted_face_id[name].append(
res['persistedFaceId'])
print('[person_persisted_face_id.{}.{}] res: {}'.format(
@ -121,3 +119,76 @@ class DataStore(object):
res = CF.person_group.train(cls.person_group_id)
print('[person_group.train]res: {}', res)
wait()
@classmethod
def setup_large_face_list(cls):
"""Setup Large Face List related data."""
cls.large_face_list_id = str(uuid.uuid1())
res = CF.large_face_list.create(cls.large_face_list_id)
print('[large_face_list_id] res: {}'.format(res))
print('[large_face_list_id]: {}'.format(cls.large_face_list_id))
wait()
cls.large_face_list_face_id = {}
for name in ['Dad', 'Daughter', 'Mom', 'Son']:
cls.large_face_list_face_id[name] = []
for idx in range(1, 3):
image = '{}PersonGroup/Family1-{}/Family1-{}{}.jpg'.format(
BASE_URL_IMAGE, name, name, idx)
res = CF.large_face_list_face.add(image,
cls.large_face_list_id)
cls.large_face_list_face_id[name].append(
res['persistedFaceId'])
print('[large_face_list_face_id.{}.{}] res: {}'.format(
name, idx, res))
print('[large_face_list_face_id.{}]: {}'.format(
name, cls.large_face_list_face_id[name]))
wait()
res = CF.large_face_list.train(cls.large_face_list_id)
print('[large_face_list.train]res: {}', res)
wait()
@classmethod
def setup_large_person_group(cls):
"""Setup Large Person Group related data."""
cls.large_person_group_id = str(uuid.uuid1())
res = CF.large_person_group.create(cls.large_person_group_id)
print('[large_person_group_id] res: {}'.format(res))
print('[large_person_group_id]: {}'.format(cls.large_person_group_id))
wait()
cls.large_person_group_person_id = {}
cls.large_person_group_person_face_id = {}
for name in ['Dad', 'Daughter', 'Mom', 'Son']:
res = CF.large_person_group_person.create(
cls.large_person_group_id, name)
cls.large_person_group_person_id[name] = res['personId']
print(
'[large_person_group_person_id.{}] res: {}'.format(name, res))
print('[large_person_group_person_id.{}]: {}'.format(
name, cls.large_person_group_person_id[name]))
wait()
cls.large_person_group_person_face_id[name] = []
for idx in range(1, 3):
image = '{}PersonGroup/Family1-{}/Family1-{}{}.jpg'.format(
BASE_URL_IMAGE, name, name, idx)
res = CF.large_person_group_person_face.add(
image, cls.large_person_group_id,
cls.large_person_group_person_id[name])
cls.large_person_group_person_face_id[name].append(
res['persistedFaceId'])
print('[large_person_group_person_face_id.{}.{}] res: {}'.
format(name, idx, res))
print('[large_person_group_person_face_id.{}]: {}'.format(
name, cls.large_person_group_person_face_id[name]))
wait()
res = CF.large_person_group.train(cls.large_person_group_id)
print('[large_person_group.train]res: {}', res)
wait()

Просмотреть файл

@ -82,7 +82,13 @@ def request(method, url, data=None, json=None, headers=None, params=None):
headers['Ocp-Apim-Subscription-Key'] = Key.get()
response = requests.request(
method, url, params=params, data=data, json=json, headers=headers)
method,
url,
params=params,
data=data,
json=json,
headers=headers,
verify=False)
# Handle result and raise custom exception when something wrong.
result = None
@ -133,8 +139,8 @@ def parse_image(image):
return headers, None, json
def wait_for_training(person_group_id):
"""Wait for the finish of person_group training."""
def wait_for_person_group_training(person_group_id):
"""Wait for the finish of person group training."""
idx = 1
while True:
res = CF.person_group.get_status(person_group_id)
@ -146,6 +152,32 @@ def wait_for_training(person_group_id):
idx += 1
def wait_for_large_face_list_training(large_face_list_id):
"""Wait for the finish of large face list training."""
idx = 1
while True:
res = CF.large_face_list.get_status(large_face_list_id)
if res['status'] in ('succeeded', 'failed'):
break
print('The training of Large Face List {} is onging: #{}'.format(
large_face_list_id, idx))
time.sleep(2**idx)
idx += 1
def wait_for_large_person_group_training(large_person_group_id):
"""Wait for the finish of large person group training."""
idx = 1
while True:
res = CF.large_person_group.get_status(large_person_group_id)
if res['status'] in ('succeeded', 'failed'):
break
print('The training of Large Person Group {} is onging: #{}'.format(
large_person_group_id, idx))
time.sleep(2**idx)
idx += 1
def clear_face_lists():
"""[Dangerous] Clear all the face lists and all related persisted data."""
face_lists = CF.face_list.lists()
@ -158,7 +190,7 @@ def clear_face_lists():
def clear_person_groups():
"""[Dangerous] Clear all the person gourps and all related persisted data.
"""[Dangerous] Clear all the person groups and all related persisted data.
"""
person_groups = CF.person_group.lists()
time.sleep(TIME_SLEEP)
@ -167,3 +199,29 @@ def clear_person_groups():
CF.person_group.delete(person_group_id)
print('Deleting Person Group {}'.format(person_group_id))
time.sleep(TIME_SLEEP)
def clear_large_face_lists():
"""[Dangerous] Clear all the large face lists and all related persisted
data.
"""
large_face_lists = CF.large_face_list.list()
time.sleep(TIME_SLEEP)
for large_face_list in large_face_lists:
large_face_list_id = large_face_list['largeFaceListId']
CF.large_face_list.delete(large_face_list_id)
print('Deleting Large Face List {}'.format(large_face_list_id))
time.sleep(TIME_SLEEP)
def clear_large_person_groups():
"""[Dangerous] Clear all the large person groups and all related persisted
data.
"""
large_person_groups = CF.large_person_group.list()
time.sleep(TIME_SLEEP)
for large_person_group in large_person_groups:
large_person_group_id = large_person_group['largePersonGroupId']
CF.large_person_group.delete(large_person_group_id)
print('Deleting Large Person Group {}'.format(large_person_group_id))
time.sleep(TIME_SLEEP)

Просмотреть файл

@ -20,7 +20,7 @@ def readme():
setup(
name='cognitive_face',
version='1.3.1',
version='1.4.0',
packages=find_packages(exclude=['tests']),
install_requires=['requests'],
author='Microsoft',