def simple_identify(video): cap = cv2.VideoCapture(video) success, frame = cap.read() count = 0 faces_ids = [] while success: if count % 5 == 0: frame = imutils.resize(frame, width=WIDTH) face_api_response = detect(frame) if face_api_response is not None: faces_ids += [face_api_response['faceId']] if len(faces_ids) == 5: break count += 1 success, frame = cap.read() if len(faces_ids) < 5: print_error('The video does not follow requirements') person_id = identify_person_id(faces_ids) if person_id is None: print_error('The person was not found') return person_id
def create_person(name, data=None): try: response = cf.person.create(GROUP_ID, name, data) return response['personId'] except cf.CognitiveFaceException as err: if err.code == 'PersonGroupNotFound': print_error('The group does not exist')
def detect_all(video): faces_images = [] cap = cv2.VideoCapture(video) success, frame = cap.read() count = 0 while success: if count % 5 == 0: frame = imutils.resize(frame, width=WIDTH) face_api_response = detect(frame) if face_api_response is not None: if check_same_person(face_api_response['faceId']): print_error('The same person already exists') faces_images.append(frame) if len(faces_images) == 5: return faces_images count += 1 success, frame = cap.read() return None
def detect_by_conditions(video, conditions, face_api=True): cur = 0 faces_images = [] cap = cv2.VideoCapture(video) success, frame = cap.read() count = 0 while success: if count % 3 == 0: frame = imutils.resize(frame, width=WIDTH) face_api_response = detect(frame) if face_api else 0 if face_api_response is not None and conditions[cur].check_face(frame, face_api_response): if face_api_response != 0 and check_same_person(face_api_response['faceId']): print_error('The same person already exists') faces_images.append(frame) cur += 1 if cur == len(conditions): return faces_images count += 1 success, frame = cap.read() return None
def change_owner(new_owner): if get_owner() != private_key_to_address(PRIVATE_KEY): print_error('Request cannot be executed') build_and_send_tx( PRIVATE_KEY, REGISTRAR_ADDRESS, web3.keccak(text='transferOwnership(address)')[:4] + encode_int(new_owner[2:], 16))
def delete_person(person_id): try: cf.person.delete(GROUP_ID, person_id) mark_group('dirty') except cf.CognitiveFaceException as err: if err.code == 'PersonGroupNotFound': print_error('The group does not exist') if err.code == 'PersonNotFound': print_error('The person does not exist')
def check_registrar(): if REGISTRAR_ADDRESS is None: print_error('No contract address') b1 = web3.eth.getCode(REGISTRAR_ADDRESS).hex()[2:] b2 = compiled_registrar_bytecode if b1 != b2[-len(b1):]: print_error( 'Seems that the contract address is not the registrar contract')
def check_certificates(): if CERTIFICATES_ADDRESS is None: print_error('No contract address') b1 = web3.eth.getCode(CERTIFICATES_ADDRESS).hex()[2:] b2 = compiled_certificates_bytecode if b1 != b2[-len(b1):]: print_error( 'Seems that the contract address is not the certificates contract')
def check_date(date_str): try: date = dt.strptime(date_str, '%H:%M %d.%m.%Y') except ValueError: print_error('Expiration date is invalid') delta = int((date - dt.now()).total_seconds()) if delta <= 0: print_error('Expiration date is invalid') return delta
def identify_person_id(faces_ids): if not is_group_up_to_date(): print_error('The service is not ready') responses = cf.face.identify(faces_ids, person_group_id=GROUP_ID, threshold=CONFIDENCE_THRESHOLD) person_id = '' for response in responses: candidates = response['candidates'] if len(candidates) != 1 or person_id not in ['', candidates[0]['personId']]: return None person_id = candidates[0]['personId'] return person_id
def cancel_request(user_private_key): request_type = get_request_type(private_key_to_address(user_private_key)) try: tx_receipt = build_and_send_tx(user_private_key, REGISTRAR_ADDRESS, web3.keccak(text='cancelRequest()')[:4]) return request_type, tx_receipt['transactionHash'].hex() except ValueError as err: if err.args[0]['code'] == -32016: if request_type == 0: print_error('No requests found') if err.args[0]['code'] == -32010: print_error('No funds to send the request')
def identify_person_id_old(image): response = cf.face.detect(FileLike(image_to_jpeg(image)), True, False) if len(response) != 1: print_error('There should be exactly 1 person on image') face_id = response[0]['faceId'] response = cf.face.identify([face_id], person_group_id=GROUP_ID, threshold=CONFIDENCE_THRESHOLD) candidates = response[0]['candidates'] print(candidates) if len(candidates) == 0: print_error('Cannot identify face') return candidates[0]['personId']
def send_transaction(user_private_key, to, value): try: addr = phone_to_address(to) if addr is None: print_error('No account with the phone number +%s' % to) tx_receipt = build_and_send_tx( user_private_key, to=addr, value=value, message='Payment of %s to +%s scheduled' % (normalize_value(value), to)) return tx_receipt['transactionHash'].hex() except ValueError as err: if err.args[0]['code'] == -32010: print_error('No funds to send the payment')
def create_approval(user_private_key, value, time_to_expire): try: tx_receipt = build_and_send_tx( user_private_key, CERTIFICATES_ADDRESS, web3.keccak(text='approve(uint256)')[:4] + encode_int(time_to_expire), value) id_hex = tx_receipt['logs'][0]['topics'][1] message = web3.eth.account.signHash(id_hex, user_private_key) return id_hex.hex()[2:] + message['signature'].hex()[2:] except ValueError as err: if err.args[0]['code'] == -32010: print_error('No funds to create a certificate')
def confirm(address): if get('network.privKey') is None: print_error('No admin account found') try: tx_receipt = build_and_send_tx( PRIVATE_KEY, REGISTRAR_ADDRESS, web3.keccak(text='confirm(address)')[:4] + encode_int(address[2:], 16), gas_estimation=False) return tx_receipt['status'], tx_receipt['transactionHash'].hex() except ValueError as err: if err.args[0]['code'] == -32010: print_error('No funds to confirm the request')
def identify(video, actions): cap = cv2.VideoCapture(video) success, frame = cap.read() actions = list(map(action_to_face_condition, actions)) count = 0 cur = 0 faces_ids = [] while success: if count % 5 == 0: frame = imutils.resize(frame, width=WIDTH) face_api_response = detect(frame) if face_api_response is not None and actions[cur].check(frame, face_api_response): faces_ids += [face_api_response['faceId']] cur += 1 if cur == len(actions): break count += 1 success, frame = cap.read() if cur < len(actions): print_error('The video does not follow requirements') person_id = identify_person_id(faces_ids) if person_id is None: print_error('The person was not found') return person_id
def train(): try: if is_group_up_to_date(): print_error('Already trained') if len(cf.person.lists(GROUP_ID)) == 0: print_error('There is nothing to train') cf.person_group.train(GROUP_ID) mark_group('ok') except cf.CognitiveFaceException as err: if err.code == 'PersonGroupNotFound': print_error('There is nothing to train')
def delete_request(user_private_key): request_type = get_request_type(private_key_to_address(user_private_key)) try: tx_receipt = build_and_send_tx(user_private_key, REGISTRAR_ADDRESS, web3.keccak(text='deleteRequest()')[:4]) return tx_receipt['transactionHash'].hex() except ValueError as err: if err.args[0]['code'] == -32016: if request_type == 4: print_error('Unregistration request already sent') else: print_error('Account is not registered yet') if err.args[0]['code'] == -32010: print_error('No funds to send the request')
def register_request(user_private_key, phone_number): try: tx_receipt = build_and_send_tx( user_private_key, REGISTRAR_ADDRESS, web3.keccak(text='registerRequest(uint256)')[:4] + encode_int(phone_number)) return tx_receipt['transactionHash'].hex() except ValueError as err: if err.args[0]['code'] == -32016: request_type = get_request_type( private_key_to_address(user_private_key)) if request_type == 3: print_error('Registration request already sent') else: print_error('Such phone number already registered') if err.args[0]['code'] == -32010: print_error('No funds to send the request')
def check_message(message): if len(message) != 140: print_error('Message should have length 140') return message
def check_address(address): if not web3.isChecksumAddress(address): print_error('Wrong address format') return address
private_key = args.withdraw[0] cancel_approvals(private_key) print('Cancelled approvals') if args.ops: check_registrar() check_certificates() address = private_key_to_address(args.ops[0]).lower() tx_list = get_tx_list(address) if len(tx_list) == 0: print_error('No operations found') print('Operations:') for tx in tx_list: date = datetime.fromtimestamp(int(tx['timeStamp'])) if int(tx['blockNumber']) >= get('registrar.registrar.startBlock'): if tx['to'] == address: from_phone = address_to_phone(tx['from'], int(tx['blockNumber'])) if from_phone != 'UNKNOWN': print('%s FROM: %s %s' % (date.strftime('%H:%M:%S %d.%m.%Y'), from_phone, normalize_value(int(tx['value']), 'ether'))) else: to_phone = address_to_phone(tx['to'], int(tx['blockNumber']))
def check_phone_number(phone_number): if len(phone_number) != 12 or not phone_number[1:].isdecimal( ) or phone_number[0] != '+': print_error('Incorrect phone number') return phone_number[1:]
def check_pin_code(pin_code): if len(pin_code) != 4 or not pin_code.isdecimal(): print_error('Pin code should have length 4 and contain only digits') return pin_code
def pin_code_to_private_key(pin_code): pin_code = check_pin_code(pin_code) person_id = get('person.id') if person_id is None: print_error('ID is not found') return get_private_key(person_id, pin_code)
def list_people_ids(): try: return list(map(lambda person: person['personId'], cf.person.lists(GROUP_ID))) except cf.CognitiveFaceException as err: if err.code == 'PersonGroupNotFound': print_error('The group does not exist')
from video_detector import detect_all parser = ArgumentParser(prog='Faces management') parser.add_argument('--simple-add', nargs=1, metavar='VIDEO', help='Adds 5 faces from video') args = parser.parse_args() if args.simple_add: video = args.simple_add[0] faces = detect_all(video) if faces is None: print_error('Video does not contain any face') create_group_if_not_exists() print('%d frames extracted' % len(faces)) person_id = create_person('1') print('PersonId: %s' % person_id) print('FaceIds') print('=======') for face in faces: print(add_face(face, person_id))
def image_to_jpeg(image): status, encoded_image = cv2.imencode('.jpeg', image) if not status: print_error('Failed to encode frame into jpeg') return encoded_image.tostring()
nargs=1, type=check_phone_number, metavar='PHONE', help='Prints address associated with given phone number') args = parser.parse_args() if args.list: check_registrar() request_type = args.list[0] lst = [] if request_type == 'add': lst = sorted(get_reg_requests()) if len(lst) == 0: print_error('No KYC registration requests found') elif request_type == 'del': lst = sorted(get_del_requests()) if len(lst) == 0: print_error('No KYC unregistration requests found') for phone, address in lst: print('%s: +%s' % (address, str(phone))) if args.confirm: check_registrar() address = args.confirm[0] status, tx_hash = confirm(address) if status == 1:
def check_name(name): if len(name) > 128 or not name.isalpha(): print_error( 'Name should have length at most 128 and contain only letters') return name