def get_a_person(self, personId, personGroupId): headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({}) try: conn = http.client.HTTPSConnection(self.host) conn.request( "GET", "/face/v1.0/persongroups/" + personGroupId + "/persons/" + personId + "?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() personjson = json.loads(str(data, 'UTF-8')) conn.close() try: if ClassUtils.isFaceAPIError(personjson): return None except MyException.RateLimitExceededError as e: time.sleep(10) return self.get_a_person(personId, personGroupId) except MyException.UnspecifiedError as e: return except MyException.PersonGroupNotTrainedError as e: print('ERROR: get_a_person.PersonGroupNotTrainedError') return return personjson except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror))
def ListPersonGroups(self): #print('列出所有的 person Groups') headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters #'start': '{string}', 'top': '1000', }) try: conn = http.client.HTTPSConnection(self.host) conn.request("GET", "/face/v1.0/persongroups?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() personGroups = json.loads(str(data, 'UTF-8')) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) try: if ClassUtils.isFaceAPIError(personGroups): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.ListPersonGroups() except MyException.UnspecifiedError as e: return return personGroups
def personGroup_status(self, personGroupId): print("personGroup_status: 查看一個 personGroup 的狀態,也就是看看訓練是否成功!") headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({'personGroupId': personGroupId}) try: conn = http.client.HTTPSConnection(self.host) conn.request( "GET", "/face/v1.0/persongroups/" + personGroupId + "/training?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() status = json.loads(str(data, 'UTF-8')) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) try: if ClassUtils.isFaceAPIError(status): return None return status except MyException.UnspecifiedError as e: return
def getPersonGroup(self, personGroupId): print('搜尋 personGroupid =', personGroupId) headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({}) try: conn = http.client.HTTPSConnection(self.host) conn.request( "GET", "/face/v1.0/persongroups/" + personGroupId + "?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() personGroup = json.loads(str(data, 'UTF-8')) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) try: if ClassUtils.isFaceAPIError(personGroup): pass return personGroup except MyException.UnspecifiedError as e: return
def detectLocalImage(self, imagepath): start = int(round(time.time() * 1000)) print('開始計時 detectLocalImage 0 ms') headers = { # Request headers 'Content-Type': 'application/octet-stream', # 用本地圖檔辨識 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters 'returnFaceId': 'true', 'returnFaceLandmarks': 'true', 'returnFaceAttributes': 'age,gender,emotion' }) #'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure' print('imagepath=', imagepath) requestbody = open(imagepath, "rb").read() try: conn = http.client.HTTPSConnection(self.host) conn.request("POST", "/face/v1.0/detect?%s" % params, requestbody, headers) response = conn.getresponse() data = response.read() print('detectLocalImage.data=', data) detectfaces = json.loads(str(data, 'UTF-8')) print("detectLocalImage.faces=", detectfaces) #print(parsed[0]['faceId']) #faceids.append(parsed[0]['faceId']) conn.close() try: if ClassUtils.isFaceAPIError(detectfaces): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.detectLocalImage(imagepath) except MyException.PersonGroupNotTrainedError as e: print( 'ERROR: detectLocalImage MyException.PersonGroupNotTrainedError' ) return except MyException.UnspecifiedError as e: return print("detectLocalImage:", imagepath + "偵測到 {0} 個人".format(len(detectfaces))) self.__detectFaces_Save(detectfaces, imagepath) return detectfaces except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror))
def identify(self, faceidkeys, personGroupId): print("def Face.identify 開始辨識。faceidkeys=", faceidkeys) if len(faceidkeys) == 0: return [] start = int(round(time.time() * 1000)) print('開始辨識 identify 0 ms') headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({}) requestbody = '''{ "personGroupId": "''' + personGroupId + '''", "faceIds":''' + str(faceidkeys) + ''', "maxNumOfCandidatesReturned":1, "confidenceThreshold": ''' + str(config['confidence']) + ''' }''' #print('requestbody=', requestbody) try: conn = http.client.HTTPSConnection(self.host) conn.request("POST", "/face/v1.0/identify?%s" % params, requestbody, headers) response = conn.getresponse() data = response.read() identifiedfaces = json.loads(str(data, 'UTF-8')) print('Face.Identify.identifiedfaces=', identifiedfaces) conn.close() # ClassUtils.tryFaceAPIError(identifyfaces) except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) sys.exit() try: if ClassUtils.isFaceAPIError(identifiedfaces): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.identify(faceidkeys, personGroupId) except MyException.PersonGroupNotFoundError as e: personGroupAPI = PersonGroup(self.api_key, self.host) personGroupAPI.createPersonGroup(personGroupId, config['personGroupName'], 'group userdata') return self.identify(faceidkeys, personGroupId) except MyException.UnspecifiedError as e: return [] except MyException.PersonGroupNotTrainedError as e: print('丟出 MyException.PersonGroupNotTrainedError 例外') raise print('超過 raise') # if ClassUtils.isFaceAPIError(identifyfaces): # return [] return identifiedfaces
def add_a_person_face(self, imagepath, personId, personGroupId): print("'add_a_person_face': 用一個圖片放入一個 person 當中 personId=" + personId, 'imagepath=', imagepath) #display(Image(url=imagepath)) headers = { # Request headers # 'Content-Type': 'application/json', 'Content-Type': 'application/octet-stream', #上傳圖檔 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters 'personGroupId': personGroupId, #'personId': '03cb1134-ad35-4b80-8bf2-3200f44eef31', 'personId': personId, #'userData': '{string}', #'targetFace': '{string}', }) #"https://lh3.googleusercontent.com/AuJtzSdWCTZ6pWW9pMxec86gVZEjP00O7qvl8RNbzYfmJvsiUfDL-BXfel5Sw2jgPNUy7rcIVQ-HFDxDEFuIZxp56NpKwOjYncgMjL_dt0-FnoBIYyUpplx4LlE5ShN2hJ3-URLwOA4=w597-h796-no" # requestbody = '{"url": "'+imageurl+'"}' requestbody = open(imagepath, "rb").read() try: conn = http.client.HTTPSConnection(self.host) conn.request( "POST", "/face/v1.0/persongroups/" + personGroupId + "/persons/" + personId + "/persistedFaces?%s" % params, requestbody, headers) response = conn.getresponse() data = response.read() jsondata = json.loads(str(data, 'UTF-8')) conn.close() # if 'error' in jsondata: # if 'RateLimitExceeded' == jsondata['error']['code']: # time.sleep(10) # else: # print("EXCEPTION: ", jsondata['error']['code'] + ":", # jsondata['error']['message']) except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) try: if ClassUtils.isFaceAPIError(jsondata): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.add_a_person_face(imagepath, personId, personGroupId) except MyException.UnspecifiedError as e: return
def detectURLImages_NoDownload(self, imageurl): headers = { # Request headers 'Content-Type': 'application/json', # 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters 'returnFaceId': 'true', 'returnFaceLandmarks': 'false', 'returnFaceAttributes': 'age,gender,emotion' }) #'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure' print('imageurl=', imageurl) requestbody = '{"url": "' + imageurl + '"}' try: conn = http.client.HTTPSConnection(self.host) conn.request("POST", "/face/v1.0/detect?%s" % params, requestbody, headers) response = conn.getresponse() data = response.read() detectfaces = json.loads(str(data, 'UTF-8')) print("detecURLImage.faces 偵測到 faces 長度=", len(detectfaces)) for index, face in enumerate(detectfaces): print('face[' + str(index) + ']=', face) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) #return [] try: if ClassUtils.isFaceAPIError(detectfaces): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.detectURLImages(imageurl) except MyException.UnspecifiedError as e: return self.__detectFaces_Save(detectfaces, imageurl) return detectfaces
def list_persons_in_group(self, personGroupId): headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters #'start': '{string}', #'top': '1000', }) try: conn = http.client.HTTPSConnection(self.host) conn.request( "GET", "/face/v1.0/persongroups/" + personGroupId + "/persons?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() persons = json.loads(str(data, 'UTF-8')) conn.close() try: if ClassUtils.isFaceAPIError(persons): pass except MyException.RateLimitExceededError as e: time.sleep(10) return self.list_persons_in_group(personGroupId) except MyException.PersonGroupNotFoundError as e: self.createPersonGroup(config['personGroupId'], config['personGroupName'], 'group userdata') return self.list_persons_in_group(config['personGroupId']) if 'error' in persons: message = '取得 persons 出錯!\n' message += '錯誤編號 = ' + persons['error']['code'] + '\n' message += '錯誤訊息 = ' + persons['error']['message'] raise MyException.responseError(message) return persons except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror))
def list_persons_in_group(self, personGroupId): print("'list_persons_in_group'") headers = { # Request headers 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({ # Request parameters #'start': '{string}', #'top': '1000', }) try: conn = http.client.HTTPSConnection(self.host) conn.request( "GET", "/face/v1.0/persongroups/" + personGroupId + "/persons?%s" % params, "{body}", headers) response = conn.getresponse() data = response.read() persons = json.loads(str(data, 'UTF-8')) #print('def list_persons_in_group:', persons) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) return [] try: if ClassUtils.isFaceAPIError(persons): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.list_persons_in_group(personGroupId) except MyException.PersonGroupNotFoundError as e: personGroupAPI = PersonGroup(self.api_key, self.host) personGroupAPI.createPersonGroup(config['personGroupId'], config['personGroupName'], 'group userdata') return self.list_persons_in_group(personGroupId) except MyException.UnspecifiedError as e: return return persons
def create_a_person(self, personGroupId, name, userData): print("'create_a_person': 在 personGroupid=" + personGroupId + " 裡 建立一個 person name=" + name) headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': self.api_key, } params = urllib.parse.urlencode({'personGroupId': personGroupId}) requestbody = '{"name":"' + name + '","userData":"' + userData + '"}' try: conn = http.client.HTTPSConnection(self.host) conn.request( "POST", "/face/v1.0/persongroups/" + personGroupId + "/persons?%s" % params, requestbody.encode('UTF-8'), headers) response = conn.getresponse() data = response.read() create_a_person_json = json.loads(str(data, 'UTF-8')) conn.close() except Exception as e: print("[Errno {0}]連線失敗!請檢查網路設定。 {1}".format(e.errno, e.strerror)) try: if ClassUtils.isFaceAPIError(create_a_person_json): return [] except MyException.RateLimitExceededError as e: time.sleep(10) return self.create_a_person(personGroupId, name, userData) except MyException.PersonGroupNotFoundError as e: personGroupApi = PersonGroup(self.api_key, self.host) personGroupApi.createPersonGroup(config['personGroupId'], config['personGroupName'], 'group userdata') return self.create_a_person(personGroupId, name, userData) except MyException.UnspecifiedError as e: return return create_a_person_json['personId']