"""Match Audio Logic.""" from src.constant import acrcloud as acrcloud_constant from src.model import acrcloud as acrcloud_model from src.model import songwhip as songwhip_model def _get_album(match): """Get Album Name.""" if match.get('album'): return match['album'].get('name') return None def _get_isrc(match): """Get ISRC.""" if match.get('external_ids'): return match['external_ids'].get('isrc') return None def _get_upc(match): """Get UPC.""" if match.get('external_ids'): return match['external_ids'].get('upc') return None def _get_acrid(match): """Get ACRID.""" if match.get('acrid'): return match['acrid'] return None def _get_spotify_id(external_metadata): """Get Spotify ID.""" if external_metadata.get('spotify') and external_metadata['spotify'].get('album'): return external_metadata['spotify']['album'].get('id') return None def _get_deezer_id(external_metadata): """Get Deezer ID.""" if external_metadata.get('deezer') and external_metadata['deezer'].get('album'): return external_metadata['deezer']['album'].get('id') return None def _get_youtube_id(external_metadata): """Get YouTube ID.""" if external_metadata.get('youtube'): return external_metadata['youtube'].get('vid') return None def _get_songwhip_external_links(match): """Get external links from Songwhip-lookup.""" spotify_id = _get_spotify_id(match['external_metadata']) deezer_id = _get_deezer_id(match['external_metadata']) youtube_id = _get_youtube_id(match['external_metadata']) return songwhip_model.lookup_songwhip_links( spotify_id=spotify_id, deezer_id=deezer_id, youtube_id=youtube_id ) def _format_matches(matches): """Format matches.""" return [ { 'acrid': _get_acrid(match), 'album': _get_album(match), 'artists': [ artist['name'] for artist in match['artists'] ], 'isrc': _get_isrc(match), 'title': match['title'], 'label': match.get('label'), 'songwhip_external_links': _get_songwhip_external_links(match), 'songwhip_url': None, 'rights_claim': match.get('rights_claim'), 'score': match.get('score'), 'upc': _get_upc(match) } for match in matches ] def _format_response(matches, acrcloud_response=None): """Format response.""" response = {'matches': matches} if acrcloud_response: response['_acrcloud_response'] = acrcloud_response return response def get_audio_matches(fingerprint): """Get audio matches.""" if not fingerprint: return _format_response(None) acrcloud_response = acrcloud_model.identify(fingerprint) matching_result_status_code = acrcloud_response['status']['code'] if matching_result_status_code == acrcloud_constant.NO_MATCH_FOUND_CODE: return _format_response( matches=None, acrcloud_response=acrcloud_response ) matches = sorted( acrcloud_response['metadata']['music'], key=lambda match: match['score'], reverse=True, ) return _format_response( matches=_format_matches(matches), acrcloud_response=acrcloud_response )