How to handle ServiceRequestError in Python

1k Views Asked by At

I am looking at Face Detection, using Kairos API while working on this program with the following code

def Test():
    image = cap.read()[1]
    cv2.imwrite("opencv_frame.png",image)
    recognized_faces = kairos_face.verify_face(file="filepath/opencv_frame.png", subject_id='David',gallery_name='Test')
    print(recognized_faces)
    if recognized_faces.get('images')[0].get('transaction').get('status') !='success':
        print('No')
    else:
        print('Hello', recognized_faces.get('images')[0].get('transaction').get('subject_id'))

this works fine if i look straight at the camera, but if i turn my head it breaks with the following response.

kairos_face.exceptions.ServiceRequestError: {'Errors': [{'Message': 'no faces found in the image', 'ErrCode': 5002}]}

How can i handle the exception Error, and force the test function to keep running until a face is detected.

1

There are 1 best solutions below

1
Inkane On BEST ANSWER

Can't you just catch the exception and try again?

def Test():
    captured = False
    while not captured:
        try:
            image = cap.read()[1]
            cv2.imwrite("opencv_frame.png",image)
            recognized_faces = kairos_face.verify_face(file="filepath/opencv_frame.png", subject_id='David',gallery_name='Test')
            captured = True
        except kairos_face.exceptions.ServiceRequestError:
            pass # optionally wait
    print(recognized_faces)
    if recognized_faces.get('images')[0].get('transaction').get('status') !='success':
        print('No')
    else:
        print('Hello', recognized_faces.get('images')[0].get('transaction').get('subject_id'))