"""Custom methods for validation of audio metadata.""" import trafaret as t from constants import errors # noqa from constants import audio_standards # noqa def sample_rate_validation(audio_meta): """Validate sample_rate value for default schema. Args: audio_meta (dict): input audio metadata. { 'sample_rate': 44100, 'bits_per_sample': 16 } Returns: dict: sample_rate value or trafaret.DataError exception. """ bits_per_sample = audio_meta['bits_per_sample'] sample_rate = audio_meta['sample_rate'] if bits_per_sample not in audio_standards.ALLOWED_BIT_SAMPLE_RATE: error_message = errors.INVALID_INPUT_VALUE_ERROR_MESSAGE.format( name='bits_per_sample', expected=[16, 24] ) return {'sample_rate': t.DataError(error_message)} available_sample_rates = ( audio_standards.ALLOWED_BIT_SAMPLE_RATE[bits_per_sample]) if sample_rate not in available_sample_rates: error_message = errors.INVALID_INPUT_VALUE_ERROR_MESSAGE.format( name='sample_rate', expected=available_sample_rates ) return {'sample_rate': t.DataError(error_message)} return {'sample_rate': sample_rate} def wav_bitrate_validation(audio_meta): """Validate bitrate value for wav schema. Args: audio_meta (dict): input audio metadata. { 'bitrate': 1411318, 'bits_per_sample': 16, 'channels': 2, 'sample_rate': 44100 } Returns: dict: bitrate value or trafaret.DataError exception. """ expected_bitrate = ( audio_meta['channels'] * audio_meta['sample_rate'] * audio_meta['bits_per_sample'] ) if audio_meta['bitrate'] != expected_bitrate: error_message = errors.INVALID_INPUT_VALUE_ERROR_MESSAGE.format( name='bitrate', expected=expected_bitrate ) return {'bitrate': t.DataError(error_message)} return {'bitrate': audio_meta['bitrate']} def wav_file_size_validation(audio_meta): """Validate file_size value for wav schema. Args: audio_meta (dict): input audio metadata. { 'file_size': 2560000, 'playtime_seconds': 12000 # ms } Returns: dict: file_size value or trafaret.DataError exception. """ file_size_minimum = ( (audio_standards.FILE_SIZE_PER_SECOND * audio_meta['playtime_seconds']) / 1000 ) if file_size_minimum > audio_meta['file_size']: expected_file_size_msg = 'greater than {}'.format(file_size_minimum) error_message = errors.INVALID_INPUT_VALUE_ERROR_MESSAGE.format( name='file_size', expected=expected_file_size_msg ) return {'file_size': t.DataError(error_message)} return {'file_size': audio_meta['file_size']}