"""ACRCloud model.""" import base64 import hashlib import hmac import json import sys import time import requests from src import config from src.config import app_logger from src.constant import acrcloud as acrcloud_constant def identify(audio_fingerprint): """Identify audio fingerprint.""" http_method = 'POST' acrcloud_identification_api_path = '/v1/identify' data_type = 'fingerprint' signature_version = '1' timestamp = time.time() acrcloud_identification_api_url = ( f'{config.ACRCLOUD_IDENTIFICATION_API_HOST}{acrcloud_identification_api_path}') request_info = '\n'.join([ http_method, acrcloud_identification_api_path, config.ACRCLOUD_IDENTIFICATION_API_ACCESS_KEY, data_type, signature_version, str(timestamp) ]) request_signature = base64.b64encode( hmac.new( config.ACRCLOUD_IDENTIFICATION_API_ACCESS_SECRET.encode('ascii'), request_info.encode('ascii'), digestmod=hashlib.sha1 ).digest() ).decode('ascii') filename = None files = [ ('sample', (filename, audio_fingerprint)) ] data = { 'access_key': config.ACRCLOUD_IDENTIFICATION_API_ACCESS_KEY, 'sample_bytes': sys.getsizeof(audio_fingerprint), 'timestamp': str(timestamp), 'signature': request_signature, 'data_type': data_type, 'signature_version': signature_version } audio_matches_response = requests.post(acrcloud_identification_api_url, files=files, data=data) if audio_matches_response.status_code != 200: error_message = ( f'ACRCloud API returned http status code: ' f'{audio_matches_response.status_code}, and text: ' f'{audio_matches_response.text}' ) app_logger.error(error_message) raise Exception(error_message) audio_matches_response.encoding = 'utf-8' audio_matches_response_data = audio_matches_response.json() api_response_code = audio_matches_response_data['status']['code'] if api_response_code not in acrcloud_constant.SUCCESS_CODES: error_message = ( f'ACRCloud API returned http status code: ' f'{audio_matches_response.status_code}, and json: ' f'{json.dumps(audio_matches_response_data)}' ) app_logger.error(error_message) raise Exception(error_message) return audio_matches_response.json()