"""Lambda acrcloud_recognizer function module.""" import argparse import json import subprocess import time import pymysql import config import mysql import query import util def get_or_create_song_id(cursor: pymysql.cursors.Cursor, key: str) -> int: song_name, extension = util.get_audio_name_from_path(key) s3_path = key.split(song_name)[0] cursor.execute(query.SELECT_SONG_ID_BY_NAME, (song_name,)) result = cursor.fetchone() if result: song_id = result['song_id'] else: cursor.execute(query.INSERT_SONG, (song_name, extension, s3_path)) song_id = cursor.lastrowid return song_id def process_file(cursor: pymysql.cursors.Cursor, bucket: str, key: str) -> None: print('processing {}'.format(key)) song_id = get_or_create_song_id(cursor, key) signed_url = config.client.generate_presigned_url( 'get_object', Params={'Bucket': bucket, 'Key': key}, ExpiresIn=3600 * 48 ) am_identify = subprocess.Popen( [ './identify', '-c', 'TestOrchardAN_v40.config', '-i', "{}".format(signed_url), '-e', 'orch-123', ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) # maybe the signed url is not ready just yet? too many 20474 error from AM time.sleep(1) output, _ = am_identify.communicate() response = json.loads(output.replace('\n', '').replace('\t', '').strip()) if response['statusCode'] == 2006: matches = response['matches'] for match in matches: parsed = { 'song_id': song_id, 'amItemID': match['amItemID'], 'label': match['metadata'].get('Label', None), 'upc': match['metadata']['AlbumUPC'], 'isrc': match['metadata'].get('ISRC', None), 'title': match['metadata']['Title'], 'release_date': match['metadata'].get('AlbumReleaseDate', None), 'artist': match['metadata']['Artist'], 'vendor': match['metadata']['Vendor'], 'response': json.dumps(match) } cursor.execute(query.INSERT_AUDIBLEMAGIC_MATCH, parsed) cursor.execute(query.UPDATE_SONG_AUDIBLEMAGIC_IDENTIFIED, (1, song_id,)) else: print(response) if response['statusCode'] == 2005: cursor.execute(query.UPDATE_SONG_AUDIBLEMAGIC_IDENTIFIED, (0, song_id,)) if response['statusCode'] == 20474: print(signed_url) def handler(bucket: str, key: str) -> bool: """Lambda entry point.""" try: with mysql.mysql_connection(**config.DB_CONFIG) as conn: with conn.cursor() as cursor: process_file(cursor, bucket, key) return True except Exception as e: # conn.rollback() print(key, str(e)) raise e if __name__ == '__main__': parser = argparse.ArgumentParser(prog='fingerprinter') parser.add_argument('-b', '--bucket', required=True, help='bucket') parser.add_argument('-o', '--object', required=True, help='object') args = parser.parse_args() handler(bucket=args.bucket, key=args.object)