def model_input():
    model = load_model('best_model.h5')
    BUCKET_NAME = 'thunderstruck-duck'
    KEY = 'sample_mp3.mp3'
    s3 = boto3.client('s3', aws_access_key_id='EXAMPLE_KEY', aws_secret_access_key='EXAMPLE_KEY EXAMPLE_KEY')
    BUCKET_NAME = 'thunderstruck-duck'
    try:
        s3.download_file(BUCKET_NAME, KEY, 'sample_mp3.mp3')
    except botocore.exceptions.ClientError as e:
        if (e.response['Error']['Code'] == '404'):
            print('The object does not exist.')
    (wave_data, wave_rate) = librosa.load('sample_mp3.mp3')
    (wave_data, _) = librosa.effects.trim(wave_data)
    song_sample = []
    sample_length = (5 * wave_rate)
    N_mels = 216
    for idx in range(0, len(wave_data), sample_length):
        song_sample = wave_data[idx:(idx + sample_length)]
        if (len(song_sample) >= sample_length):
            mel = melspectrogram(song_sample, n_mels=N_mels)
            db = librosa.power_to_db(mel)
            normalised_db = sklearn.preprocessing.minmax_scale(db)
            filename = 'sample_mel.tif'
            db_array = (np.asarray(normalised_db) * 255).astype(np.uint8)
            db_image = Image.fromarray(np.array([db_array, db_array, db_array]).T)
            db_image.save('{}{}'.format('upload_mel/', filename))
    data_df = pd.DataFrame([{'bird': 'sample bird', 'song_sample': f'/app/upload_mel/{filename}'}])
    callbacks = [ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1, factor=0.7), EarlyStopping(monitor='val_loss', patience=5), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]
    model.compile(loss='categorical_crossentropy', optimizer='adam')
    validation_batch_size_full = 1
    target_size = (216, 216)
    train_datagen_full = ImageDataGenerator(rescale=(1.0 / 255))
    validation_datagen_full = ImageDataGenerator(rescale=(1.0 / 255))
    validation_generator_full = validation_datagen_full.flow_from_dataframe(dataframe=data_df, x_col='song_sample', y_col='bird', directory='/', target_size=target_size, shuffle=False, batch_size=validation_batch_size_full, class_mode='categorical')
    preds = model.predict_generator(validation_generator_full)
    result = np.argmax(preds[0])
    index_df = pd.read_csv('xeno-canto_ca-nv_index.csv')
    bird_list = pd.DataFrame(index_df.english_cname.unique())
    bird_list.columns = ['birds']
    percentage = preds[0][result]
    Name_of_bird = bird_list['birds'][result]
    print(f'This bird is {percentage} likely {Name_of_bird}')
    final_data = {'likelihood': percentage, 'name_of_bird': Name_of_bird}
    return final_data
    if (__name__ == '__main__'):
        print(model_input())
def model_input():
    model = load_model('best_model.h5')
    BUCKET_NAME = 'thunderstruck-duck'
    KEY = 'sample_mp3.mp3'
    s3 = boto3.client('s3', aws_access_key_id='EXAMPLE_KEY', aws_secret_access_key='EXAMPLE_KEY EXAMPLE_KEY')
    BUCKET_NAME = 'thunderstruck-duck'
    try:
        s3.download_file(BUCKET_NAME, KEY, 'sample_mp3.mp3')
    except botocore.exceptions.ClientError as e:
        if (e.response['Error']['Code'] == '404'):
            print('The object does not exist.')
    (wave_data, wave_rate) = librosa.load('sample_mp3.mp3')
    (wave_data, _) = librosa.effects.trim(wave_data)
    song_sample = []
    sample_length = (5 * wave_rate)
    N_mels = 216
    for idx in range(0, len(wave_data), sample_length):
        song_sample = wave_data[idx:(idx + sample_length)]
        if (len(song_sample) >= sample_length):
            mel = melspectrogram(song_sample, n_mels=N_mels)
            db = librosa.power_to_db(mel)
            normalised_db = sklearn.preprocessing.minmax_scale(db)
            filename = 'sample_mel.tif'
            db_array = (np.asarray(normalised_db) * 255).astype(np.uint8)
            db_image = Image.fromarray(np.array([db_array, db_array, db_array]).T)
            db_image.save('{}{}'.format('upload_mel/', filename))
    data_df = pd.DataFrame([{'bird': 'sample bird', 'song_sample': f'/app/upload_mel/{filename}'}])
    callbacks = [ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1, factor=0.7), EarlyStopping(monitor='val_loss', patience=5), ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]
    model.compile(loss='categorical_crossentropy', optimizer='adam')
    validation_batch_size_full = 1
    target_size = (216, 216)
    train_datagen_full = ImageDataGenerator(rescale=(1.0 / 255))
    validation_datagen_full = ImageDataGenerator(rescale=(1.0 / 255))
    validation_generator_full = validation_datagen_full.flow_from_dataframe(dataframe=data_df, x_col='song_sample', y_col='bird', directory='/', target_size=target_size, shuffle=False, batch_size=validation_batch_size_full, class_mode='categorical')
    preds = model.predict_generator(validation_generator_full)
    result = np.argmax(preds[0])
    index_df = pd.read_csv('xeno-canto_ca-nv_index.csv')
    bird_list = pd.DataFrame(index_df.english_cname.unique())
    bird_list.columns = ['birds']
    percentage = preds[0][result]
    Name_of_bird = bird_list['birds'][result]
    print(f'This bird is {percentage} likely {Name_of_bird}')
    final_data = {'likelihood': percentage, 'name_of_bird': Name_of_bird}
    return final_data
    if (__name__ == '__main__'):
        print(model_input())