Sample Code

The following is some sample code that provides an example of performing a basic "identify music" audio search.

main.py
#!/usr/bin/env python3

import json
import pex

CLIENT_ID = "#YOUR_CLIENT_ID_HERE"
CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE"
INPUT_FILE = "/path/to/file.mp3"

def main():
    # Initialize and authenticate the client
    client = pex.PexSearchClient(CLIENT_ID, CLIENT_SECRET)

    # Create an audio fingerprint from input file
    ft = client.fingerprint_file(INPUT_FILE, pex.FingerprintType.AUDIO)

    # Build an identify music search request
    req = pex.PexSearchRequest(fingerprint=ft, type=pex.PexSearchType.IDENTIFY_MUSIC)

    # Perform the lookup
    result = do_lookup(client, req)

    # Print the result
    print(json.dumps(result, indent=2))
    
    
def do_lookup(client, req):
    # These errors are outside of the client's
    # control and often resolve after retrying
    retryable_errs = (
        pex.Code.DEADLINE_EXCEEDED,
        pex.Code.INTERNAL_ERROR,
        pex.Code.LOOKUP_FAILED,
        pex.Code.LOOKUP_TIMED_OUT,
    )

    while True:
        try:
            # Start the search
            future = client.start_search(req)

            # Return the result
            return future.get()

        except pex.Error as err:
            # Raise the error if it's not retryable
            if err.code not in retryable_codes:
                raise err

            # Log the error
            print(err)
            print("retrying lookup...")

            # Sleep for 1s or use exponential backoff
            time.sleep(1)

            # Retry the lookup
            continue


if __name__ == '__main__':
    main()

Last updated