├── predict.sh
├── preprocess
├── resample_wavs_to_16k.sh
├── xmltodict.py
└── loadData.py
├── doall.sh
├── train
├── io_utils_mod.py
├── generateImages.py
├── log.py
├── model-BirdClef.py
├── MapCallback.py
├── model-AlexNet.py
└── trainModel.py
├── README.md
├── predict
└── predict.py
└── LICENSE
/predict.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | cd predict
3 | python predict.py
4 | cd ..
5 |
--------------------------------------------------------------------------------
/preprocess/resample_wavs_to_16k.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | ORIGINALDIR=$(dirname $0)
3 | DIR=$1
4 | cd $DIR
5 | mkdir ../wav_16khz
6 | FILES=*
7 | for f in $FILES
8 | do
9 | echo "Processing ./$f file to ../wav_16khz/$f"
10 | # take action on each file. $f store current file name
11 | sox ./$f -r 16000 ../wav_16khz/$f
12 | done
13 | cd $ORIGINALDIR
14 |
--------------------------------------------------------------------------------
/doall.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | mkdir -p birdclef_data
3 | cd birdclef_data
4 | wget -nc http://otmedia.lirmm.fr/LifeCLEF/BirdCLEF2016/BirdCLEF2016TestSet.tar.gz
5 | wget -nc http://otmedia.lirmm.fr/LifeCLEF/BirdCLEF2016/BirdCLEF2016TrainingSet.tar.gz
6 | unp *.tar.gz
7 | cd ..
8 | preprocess/resample_wavs_to_16k.sh birdclef_data/TrainingSet/wav
9 | preprocess/resample_wavs_to_16k.sh birdclef_data/test/wav2015
10 | cd preprocess
11 | python loadData.py
12 | cd ..
13 | cd train
14 | mkdir modelWeights
15 | python trainModel.py
16 | cd ..
17 |
--------------------------------------------------------------------------------
/train/io_utils_mod.py:
--------------------------------------------------------------------------------
1 | from __future__ import absolute_import
2 | import h5py
3 | import numpy as np
4 | from collections import defaultdict
5 |
6 |
7 | class HDF5Matrix():
8 | refs = defaultdict(int)
9 |
10 | def __init__(self, datapath, dataset, start, end, normalizer=None):
11 | if datapath not in list(self.refs.keys()):
12 | f = h5py.File(datapath)
13 | self.refs[datapath] = f
14 | else:
15 | f = self.refs[datapath]
16 | self.start = start
17 | self.end = end
18 | self.data = f[dataset]
19 | self.normalizer = normalizer
20 |
21 | def __len__(self):
22 | return self.end - self.start
23 |
24 | def __getitem__(self, key):
25 | if isinstance(key, slice):
26 | if key.stop + self.start <= self.end:
27 | idx = slice(key.start+self.start, key.stop + self.start)
28 | else:
29 | raise IndexError
30 | elif isinstance(key, int):
31 | if key + self.start < self.end:
32 | idx = key+self.start
33 | else:
34 | raise IndexError
35 | elif isinstance(key, np.ndarray):
36 | if np.max(key) + self.start < self.end:
37 | idx = (self.start + key).tolist()
38 | else:
39 | raise IndexError
40 | elif isinstance(key, list):
41 | if max(key) + self.start < self.end:
42 | idx = [x + self.start for x in key]
43 | else:
44 | raise IndexError
45 | if self.normalizer is not None:
46 | return self.normalizer(self.data[idx])
47 | else:
48 | return self.data[idx]
49 |
50 | @property
51 | def shape(self):
52 | ret = []
53 | ret.append(self.end - self.start)
54 | ret = ret + [dim for dim in list(self.data.shape[1:])]
55 | return tuple(ret)
56 |
57 |
58 | def save_array(array, name):
59 | import tables
60 | f = tables.open_file(name, 'w')
61 | atom = tables.Atom.from_dtype(array.dtype)
62 | ds = f.createCArray(f.root, 'data', atom, array.shape)
63 | ds[:] = array
64 | f.close()
65 |
66 |
67 | def load_array(name):
68 | import tables
69 | f = tables.open_file(name)
70 | array = f.root.data
71 | a = np.empty(shape=array.shape, dtype=array.dtype)
72 | a[:] = array[:]
73 | f.close()
74 | return a
--------------------------------------------------------------------------------
/train/generateImages.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Báint Czeba, Bálint Pál Tóth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Bálint Pál Tóth, Bálint Czeba,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | # this script generates images from the preprocessed spectograms
26 |
27 | from scipy import io
28 | import pandas as pd
29 | import numpy as np
30 | import time
31 | import pickle
32 | import os
33 | import h5py
34 |
35 | hdf5path = '../birdclef_data/data_top999_nozero.hdf5' # it takes long if we save all the spectorgram, maybe it is better to call processNMostCommon from loadData.py with a small N (eg. =3)
36 | todirrootpath = '../images_bw_3/'
37 |
38 | f = h5py.File(hdf5path, 'r')
39 | X = f.get('X')
40 | y = f.get('y')
41 | mediaId = f.get('MediaId')
42 | classId = f.get('ClassId')
43 | print(mediaId[0])
44 |
45 | y_class = np.empty((0,1))
46 | for row in y:
47 | for i in range(len(row)):
48 | if row[i]==1:
49 | y_class=np.vstack((y_class,i))
50 |
51 | import matplotlib
52 | matplotlib.use('Agg')
53 | import matplotlib.pyplot as plt
54 | plt.ioff()
55 |
56 | fig = plt.figure(frameon=False)
57 | ax = fig.add_axes([0, 0, 1, 1])
58 | ax.axis('off')
59 |
60 | i=0
61 | lenX=X.shape[0]
62 | img_artist = ax.imshow(np.flipud(X[0][0]), cmap=plt.cm.binary)
63 |
64 | if not os.path.exists(todirrootpath):
65 | os.makedirs(todirrootpath)
66 |
67 | for i in range(X.shape[0]):
68 | directory=os.path.join(todirrootpath,'{}'.format(classId[i][0]))
69 | if not os.path.exists(directory):
70 | os.makedirs(directory)
71 | print('{}/{}'.format(i, lenX))
72 | img_artist.set_data(np.flipud(X[i][0]))
73 | fileNumber=0
74 | while(os.path.isfile(os.path.join(directory, '{}_{}.png'.format(int(mediaId[i][0]), fileNumber)))):
75 | fileNumber=fileNumber+1;
76 | print(fileNumber)
77 |
78 | with open(os.path.join(directory, '{}_{}.png'.format(int(mediaId[i][0]), fileNumber)), 'w') as outfile:
79 | fig.canvas.print_png(outfile)
80 |
81 | f.close()
82 |
--------------------------------------------------------------------------------
/train/log.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 |
4 | def appendDfToPickle(df, filePath):
5 | import os
6 | import pandas as pd
7 | if not os.path.isfile(filePath):
8 | df.to_pickle(filePath)
9 | else:
10 | tempDF=pd.read_pickle(filePath)
11 | tempDF=tempDF.append(df, ignore_index = True)
12 | tempDF.to_pickle(filePath)
13 |
14 | def appendDfToExcel(df, excelFilePath):
15 | import os
16 | if not os.path.isfile(excelFilePath):
17 | df.to_excel(excelFilePath, index=False)
18 | else:
19 | tempDF=pd.read_excel(excelFilePath)
20 | tempDF=tempDF.append(df)
21 | tempDF.to_excel(excelFilePath, index=False)
22 |
23 | def appendDfToCSV(df, csvFilePath):
24 | import os
25 | if not os.path.isfile(csvFilePath):
26 | df.to_csv(csvFilePath, index=False, sep='\t')
27 | else:
28 | tempDF=pd.read_csv(csvFilePath, sep='\t')
29 | tempDF=tempDF.append(df)
30 | tempDF.to_csv(csvFilePath, index=False, sep='\t')
31 |
32 | def modelToDict(model):
33 | layerNumber=0;
34 | d=dict()
35 | for layer in model.layers:
36 | columnHeader="zz_layer({:02d})".format(layerNumber) #zz: to put it to the last columns
37 | layerNumber+=1;
38 | d[columnHeader]=str(layerToDict(layer))
39 |
40 | #for k,v in model.get_config().iteritems(): ##not working since keras 1.0.0
41 | # if k in ['loss', 'optimizer']:
42 | # d[k]=str(v)
43 | d['optimizer']=str(model.optimizer.get_config())
44 | d['loss']=str(model.loss)
45 | d['output_dim'] = model.layers[-1].get_config()['output_dim']
46 | return d
47 |
48 | def layerToDict(layer):
49 | d=dict()
50 | for k,v in layer.get_config().iteritems():
51 | if k in [\
52 | #Basic
53 | 'input_shape', 'init', 'name', 'output_dim', 'activation', 'p', \
54 | #Convolution1D
55 | 'nb_filter', 'pool_length', 'filter_length', 'border_mode', \
56 | #Convolution2D
57 | 'nb_row','nb_col', 'subsample', 'pool_size']:
58 | d[k]=v
59 | d['output_shape']=layer.output_shape
60 | return d
61 |
62 | def resultToDict(result):
63 | d=dict()
64 | d['epochs']=len(result.epoch)
65 | minIsGood=['loss', 'val_loss']
66 | maxIsGood=['acc', 'val_acc']
67 | for k,v in result.history.iteritems():
68 | if k in minIsGood:
69 | d['final_' + k]=v[-1]
70 | d['best_' + k]=np.min(v)
71 | d['best_' + k + '_epoch']=np.argmin(v) + 1 #!!!!!
72 | elif k in maxIsGood:
73 | d['final_' + k]=v[-1]
74 | d['best_' + k]=np.max(v)
75 | d['best_' + k + '_epoch']=np.argmax(v) + 1 #!!!!!
76 | return d
77 |
78 | def logToDataFrame(model=None, fitting_result=None, otherDict=None):
79 | d=dict()
80 | if model is not None:
81 | d.update(modelToDict(model))
82 | if fitting_result is not None:
83 | d.update(resultToDict(fitting_result))
84 | if otherDict is not None:
85 | d.update(otherDict)
86 | return pd.DataFrame(d, index=[0])
87 |
88 | def logToXLS(filepath, model=None, fitting_result=None, otherDict=None):
89 | appendDfToExcel(logToDataFrame(model, fitting_result, otherDict), filepath)
90 |
91 | def logToCSV(filepath, model=None, fitting_result=None, otherDict=None):
92 | appendDfToCSV(logToDataFrame(model, fitting_result, otherDict), filepath)
--------------------------------------------------------------------------------
/train/model-BirdClef.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Báint Czeba, Bálint Pál Tóth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Bálint Pál Tóth, Bálint Czeba,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | from keras.models import Sequential
26 | from keras.layers.core import Dense, Activation, Dropout, Flatten
27 | from keras.optimizers import SGD, RMSprop
28 | from keras.layers.recurrent import LSTM
29 | from keras.callbacks import EarlyStopping, ModelCheckpoint
30 | from keras.layers.convolutional import Convolution2D, MaxPooling2D
31 | from keras.layers import BatchNormalization
32 |
33 | model = Sequential()
34 |
35 | # convolutional layers
36 | model.add(Convolution2D(input_shape=(1,200,310),
37 | nb_filter=128,
38 | nb_row=16,
39 | nb_col=16,
40 | border_mode='valid',
41 | init='lecun_uniform',
42 | activation='relu',
43 | subsample=(8, 8)
44 | ))
45 | model.add(MaxPooling2D(pool_size=(2,2)))
46 |
47 | model.add(Convolution2D(nb_filter=256,
48 | nb_row=5,
49 | nb_col=3,
50 | border_mode='valid',
51 | init='lecun_uniform',
52 | activation='relu'
53 | ))
54 | model.add(BatchNormalization())
55 | model.add(MaxPooling2D(pool_size=(2,2)))
56 |
57 | model.add(Convolution2D(nb_filter=384,
58 | nb_row=3,
59 | nb_col=3,
60 | border_mode='same',
61 | init='lecun_uniform',
62 | activation='relu'
63 | ))
64 |
65 | model.add(Convolution2D(nb_filter=384,
66 | nb_row=3,
67 | nb_col=3,
68 | border_mode='same',
69 | init='lecun_uniform',
70 | activation='relu'
71 | ))
72 |
73 | model.add(BatchNormalization())
74 | model.add(MaxPooling2D(pool_size=(2,2)))
75 |
76 | # dense layers
77 | model.add(Flatten())
78 | model.add(Dense(2048, activation='relu'))
79 | model.add(Dropout(0.5))
80 | model.add(Dense(2048, activation='relu'))
81 | model.add(Dropout(0.5))
82 | model.add(Dense(output_dim=output_dim, activation='softmax'))
83 |
--------------------------------------------------------------------------------
/train/MapCallback.py:
--------------------------------------------------------------------------------
1 | from sklearn.metrics import average_precision_score
2 | class Callback(object):
3 | '''Abstract base class used to build new callbacks.
4 | # Properties
5 | params: dict. Training parameters
6 | (eg. verbosity, batch size, number of epochs...).
7 | model: instance of `keras.models.Model`.
8 | Reference of the model being trained.
9 | The `logs` dictionary that callback methods
10 | take as argument will contain keys for quantities relevant to
11 | the current batch or epoch.
12 | Currently, the `.fit()` method of the `Sequential` model class
13 | will include the following quantities in the `logs` that
14 | it passes to its callbacks:
15 | on_epoch_end: logs include `acc` and `loss`, and
16 | optionally include `val_loss`
17 | (if validation is enabled in `fit`), and `val_acc`
18 | (if validation and accuracy monitoring are enabled).
19 | on_batch_begin: logs include `size`,
20 | the number of samples in the current batch.
21 | on_batch_end: logs include `loss`, and optionally `acc`
22 | (if accuracy monitoring is enabled).
23 | '''
24 | def __init__(self):
25 | pass
26 |
27 | def set_params(self, params):
28 | self.params = params
29 |
30 | def set_model(self, model):
31 | self.model = model
32 |
33 | def on_epoch_begin(self, epoch, logs={}):
34 | pass
35 |
36 | def on_epoch_end(self, epoch, logs={}):
37 | pass
38 |
39 | def on_batch_begin(self, batch, logs={}):
40 | pass
41 |
42 | def on_batch_end(self, batch, logs={}):
43 | pass
44 |
45 | def on_train_begin(self, logs={}):
46 | pass
47 |
48 | def on_train_end(self, logs={}):
49 | pass
50 |
51 | class MapCallback(Callback):
52 |
53 | '''Abstract base class used to build new callbacks.
54 | # Properties
55 | params: dict. Training parameters
56 | (eg. verbosity, batch size, number of epochs...).
57 | model: instance of `keras.models.Model`.
58 | Reference of the model being trained.
59 | The `logs` dictionary that callback methods
60 | take as argument will contain keys for quantities relevant to
61 | the current batch or epoch.
62 | Currently, the `.fit()` method of the `Sequential` model class
63 | will include the following quantities in the `logs` that
64 | it passes to its callbacks:
65 | on_epoch_end: logs include `acc` and `loss`, and
66 | optionally include `val_loss`
67 | (if validation is enabled in `fit`), and `val_acc`
68 | (if validation and accuracy monitoring are enabled).
69 | on_batch_begin: logs include `size`,
70 | the number of samples in the current batch.
71 | on_batch_end: logs include `loss`, and optionally `acc`
72 | (if accuracy monitoring is enabled).
73 | '''
74 | def __init__(self):
75 | super(Callback, self).__init__()
76 |
77 | def set_params(self, params):
78 | self.params = params
79 |
80 | def set_model(self, model):
81 | self.model = model
82 |
83 | def on_epoch_begin(self, epoch, logs={}):
84 | pass
85 |
86 | def on_epoch_end(self, epoch, logs={}):
87 | X_validation = self.model.validation_data[0]
88 | y_validation = self.model.validation_data[1]
89 | y_result=self.model.predict(X_validation)
90 |
91 | map = average_precision_score(y_validation.data[y_validation.start: y_validation.end], y_result, average='micro')
92 |
93 | logs['val_map']=map
94 |
95 | print("val_MAP: {}\n".format(map))
96 |
97 | def on_batch_begin(self, batch, logs={}):
98 | pass
99 |
100 | def on_batch_end(self, batch, logs={}):
101 | pass
102 |
103 | def on_train_begin(self, logs={}):
104 | pass
105 |
106 | def on_train_end(self, logs={}):
107 | pass
108 |
--------------------------------------------------------------------------------
/train/model-AlexNet.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Báint Czeba, Bálint Pál Tóth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Bálint Pál Tóth, Bálint Czeba,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | from keras.models import Sequential
26 | from keras.layers.core import Dense, Activation, Dropout, Flatten
27 | from keras.layers import BatchNormalization
28 | from keras.optimizers import SGD, RMSprop
29 | from keras.layers.recurrent import LSTM
30 | from keras.callbacks import EarlyStopping, ModelCheckpoint
31 | from keras.layers.convolutional import Convolution2D, MaxPooling2D
32 |
33 | # Strongly AlexNet based convolutional neural network
34 |
35 | model = Sequential()
36 |
37 | # convolutional layer
38 | model.add(Convolution2D(input_shape=(1,200,310),
39 | nb_filter=48*2,
40 | nb_row=16,
41 | nb_col=16,
42 | border_mode='valid',
43 | init='glorot_normal', #glorot_normal lecun_uniform he_uniform
44 | activation='relu',
45 | subsample=(6, 6)
46 | ))
47 | model.add(BatchNormalization())
48 | model.add(MaxPooling2D(pool_size=(2,2)))
49 |
50 | model.add(Convolution2D(nb_filter=128*2,
51 | nb_row=3,
52 | nb_col=3,
53 | border_mode='valid',
54 | init='lecun_uniform', #glorot_normal lecun_uniform he_uniform
55 | activation='relu'
56 | ))
57 | model.add(BatchNormalization())
58 | model.add(MaxPooling2D(pool_size=(2,2)))
59 |
60 | model.add(Convolution2D(nb_filter=192*2,
61 | nb_row=3,
62 | nb_col=3,
63 | border_mode='same',
64 | init='lecun_uniform', #glorot_normal lecun_uniform he_uniform
65 | activation='relu'
66 | ))
67 |
68 | model.add(Convolution2D(nb_filter=192*2,
69 | nb_row=3,
70 | nb_col=3,
71 | border_mode='same',
72 | init='lecun_uniform', #glorot_normal lecun_uniform he_uniform
73 | activation='relu'
74 | ))
75 |
76 | model.add(Convolution2D(nb_filter=128*2,
77 | nb_row=3,
78 | nb_col=3,
79 | border_mode='same',
80 | init='lecun_uniform', #glorot_normal lecun_uniform he_uniform
81 | activation='relu'
82 | ))
83 |
84 | model.add(BatchNormalization())
85 | model.add(MaxPooling2D(pool_size=(2,2)))
86 |
87 | # dense layers
88 | model.add(Flatten())
89 | model.add(Dropout(0.5))
90 | model.add(Dense(4096, activation='relu'))
91 | model.add(Dropout(0.5))
92 | model.add(Dense(4096, activation='relu'))
93 | model.add(Dropout(0.5))
94 | model.add(Dense(output_dim = output_dim, activation='softmax'))
95 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Trainig scripts for deep convolutional neural network based audio classification in Keras
2 |
3 | The following scripts were created for the BirdCLEF 2016 competition by Bálint Czeba and Bálint Pál Tóth.
4 |
5 | *The LifeCLEF bird identification challenge provides a largescale
6 | testbed for the system-oriented evaluation of bird species identifi-
7 | cation based on audio recordings. One of its main strength is that the
8 | data used for the evaluation is collected through Xeno-Canto, the largest
9 | network of bird sound recordists in the world. This makes the task closer
10 | to the conditions of a real-world application than previous, similar initiatives.
11 | The main novelty of the 2016-th edition of the challenge was the
12 | inclusion of soundscape recordings in addition to the usual xeno-canto
13 | recordings that focus on a single foreground species. This paper reports
14 | the methodology of the conducted evaluation, the overview of the systems
15 | experimented by the 6 participating research groups and a synthetic
16 | analysis of the obtained results.* (More details: http://www.imageclef.org/lifeclef/2016/bird)
17 |
18 | With some tweeks (reading meta-data and modifing network structure / how the spectogram is preprocessed) it is possible to apply it to arbitrary audio classification problems.
19 |
20 | # Citation
21 |
22 | Please cite the following paper if this code was useful for your research:
23 |
24 | *Tóth Bálint Pál, Czeba Bálint, "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment", In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8*
25 | Download from here (PDF): http://ceur-ws.org/Vol-1609/16090560.pdf
26 |
27 | ```
28 | @article{tothczeba,
29 | author = "B\'{a}lint P\'{a}l T\'{o}th, B\'{a}lint Czeba",
30 | title = "{Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment}",
31 | booktitle = "{Working Notes of Conference and Labs of the Evaluation Forum},
32 | pages = "8",
33 | year = "2016",
34 | }
35 | ```
36 |
37 | # Prerequisites
38 | You will need SOX for wave file resampling and Keras deep learning frameworks and some necessary modules. At the time of writeing you can install them in the following way:
39 | ```
40 | sudo apt-get install sox
41 | sudo apt-get install python-tk
42 | sudo pip install scipy
43 | sudo pip install matplotlib
44 | sudo pip install sklearn
45 | sudo pip install tensorflow-gpu
46 | sudo pip install keras
47 | ```
48 | The code is tested under Python 2.7. with TensorFlow (GPU) 1.0.0a0 and Keras 1.1.1. backend, NVidia Titan X 12GB GPU.
49 |
50 | If you use TensorFlow as a backend with Keras 1.x you should set
51 | ```
52 | "image_dim_ordering": "th",
53 | ```
54 | in ~/.keras/keras.json configuration file.
55 |
56 | In Keras 2 "image_dim_ordering" is deprecated. If you use TensorFlow + Keras 2.x, you should change the "image_data_format" setting to "channels_first".
57 |
58 | # Directory structure and files
59 | ```
60 | doall.sh - run this script and it will do everything (you will need plenty of disk space > 100 GB)
61 | preprocess/loadData.py - responsible for preprocessing the data (wavs and XML meta-data)
62 | preprocess/sample_wavs_to_16k.sh - simple script that resamples wave files to 16 kHz with SOX
63 | preprocess/xmltodict.py - XML processing from https://github.com/martinblech/xmltodict
64 | train/trainModel.py - after preprocessing this script trains the neural networks
65 | train/model-AlexNet.py - AlexNet inspired model for audio classification
66 | train/model-BirdClef.py - Another convolutional neural net model for audio classification
67 | train/MAPCallback.py - Script to calculate MAP scores during training the neural nets
68 | train/generateImages.py - Generate images from the preprocessed spectogram for visualization purposes
69 | train/io_utils_mod.py - Functions for loading and saving data to HDF5
70 | train/log.py - Functions for logging purposes
71 | predict/predict.py - Predict after preprocessing and training is done
72 | ```
73 |
74 | # Training (and download data and preprocess)
75 |
76 | For training you have to simply run
77 | ```
78 | ./doall.sh
79 | ```
80 | Be aware that this will download all the data (>50 GB) from http://otmedia.lirmm.fr/LifeCLEF/BirdCLEF2016/ to
81 | ```
82 | birdclef_data
83 | ```
84 | directory, unpack it and resample to 16 kHz and preprocess it into HDF5 files. You need cca. 280 GB of free space for the whole process. If you would like to put the data to somewhere else, please modify the doall.sh, preprocess/loadData.py and train/trainModel.py scripts.
85 |
86 | The download process, preprocessing and training takes 4-5 days on an i7 CPU + Titan X GPU.
87 |
88 | # Prediction
89 |
90 | After the preprocessing and training is do simpy run the following script to make predictions on test data:
91 |
92 | ```
93 | ./predict.sh
94 | ```
95 | The prediction results will be written in a .csv file in the predict/ directory.
96 |
--------------------------------------------------------------------------------
/predict/predict.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Báint Czeba, Bálint Pál Tóth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Bálint Pál Tóth, Bálint Czeba,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | from scipy import io
26 | from scipy.io import wavfile
27 | import pandas as pd
28 | import numpy as np
29 | np.random.seed(0)
30 | import time
31 | import pickle
32 | import os
33 | import h5py
34 | import sys, getopt
35 | import datetime
36 | from sklearn.metrics import average_precision_score, accuracy_score
37 | sys.path.append('../preprocess/')
38 | import loadData
39 |
40 | # prediction related paths, should be consistent with /preprocess/loadData.py and /train/trainModel.py
41 | PATH_TEST_IN_16KWAVS = '../birdclef_data/test/wav_16khz'
42 | PATH_TEST_IN_XMLPICKLEFILE = '../birdclef_data/test/xml_data.pickle'
43 | modelPath = '../train/model-AlexNet.py'
44 | modelWeightsPath = '../train/modelWeights/best_val_map_999.hdf5'
45 | labelBinarizerPath = "../birdclef_data/labelBinarizer_top999.pickle"
46 |
47 | output_dim = 999
48 | scalerFilePath = None
49 |
50 | if __name__ == "__main__":
51 | argv=sys.argv[1:]
52 |
53 | try:
54 | opts, args = getopt.getopt(argv,"he:p:m:s:",["nbepochs=","hdf5path=","scalerpath"])
55 | except getopt.GetoptError:
56 | print 'trainModel.py -p '
57 | sys.exit(2)
58 | for opt, arg in opts:
59 | if opt == '-h':
60 | print 'trainModel.py -p -m '
61 | sys.exit()
62 | elif opt in ("-p", "--p"):
63 | hdf5path = arg
64 | elif opt in ("-m", "--m"):
65 | modelPath = arg
66 | elif opt in ("-s", "--s"):
67 | scalerFilePath = arg
68 |
69 | # function to convert probabilities to classes
70 | def proba_to_class(a):
71 | classCount = len(a[0])
72 | to_return = np.empty((0,classCount))
73 | for row in a:
74 | maxind = np.argmax(row)
75 | to_return = np.vstack((to_return,[1 if i==maxind else 0 for i in range(classCount)]))
76 | return to_return
77 |
78 | # run preprocessing and prediction on one file
79 | def runModelOnWavByPath(model, path):
80 | (tempSpecUnfiltered, tempSpecFiltered) = loadData.audioToFilteredSpectrogram(io.wavfile.read(path)[1], expandByOne=True)
81 | tempList = list()
82 | tempList.append(tempSpecFiltered)
83 | X,_,_,_ = loadData.spectrogramListToT4(tempList, N = 5*62) # the N must be consistent with /preprocess/loadData.py
84 | result = model.predict(X)
85 |
86 | return result
87 |
88 | scaler = None
89 | scaleData = None
90 | if scalerFilePath is not None:
91 | scaler = pickle.load(open(scalerFilePath, 'rb'))
92 | # Can't use the build in scaler.transform because it only supports 2d arrays.
93 | def scaleData(X):
94 | return (X-scaler.mean_)/scaler.scale_
95 |
96 | # load the meta-data saved into a pickle file
97 | df = pd.read_pickle(PATH_TEST_IN_XMLPICKLEFILE)
98 | df = df.iloc[np.random.permutation(len(df))]
99 | df.reset_index(drop=True, inplace=True)
100 | lb = pickle.load(open(labelBinarizerPath, 'rb'))
101 |
102 | # calculate prediction time
103 | startTime = time.time()
104 |
105 | # Build model and load saved weights
106 | execfile(modelPath)
107 | model.load_weights(modelWeightsPath)
108 |
109 | ap=[]
110 | i=0
111 |
112 | # writeing predictions
113 | resultColumns = lb.inverse_transform(np.diag([1 for i in range(999)]))
114 | resultsFileName = "test_2015_{}_{}.csv".format(os.path.split(modelPath)[-1], datetime.datetime.now().strftime('%Y-%m-%d-%H-%M'))
115 |
116 | # running test with all the data
117 | for i in range(int(df.shape[0]*0.0),df.shape[0]):
118 | print ('{}/{}'.format(i, df.shape[0]))
119 | result = runModelOnWavByPath(model, os.path.join(PATH_TEST_IN_16KWAVS, df.FileName[i]))
120 |
121 | result_avg = np.mean(result, axis=0)
122 | result_avg = result_avg/np.sum(result_avg)
123 |
124 | singleResultDF = pd.DataFrame([result_avg], columns = resultColumns)
125 | singleResultDF['MediaId'] = df.MediaId[i]
126 | with open(resultsFileName, "a") as myfile:
127 | for row in singleResultDF.iterrows():
128 | for k,v in row[1].iterkv():
129 | if (k is not 'MediaId'):
130 | resultLine = "{};{};{:.16f}\n".format(row[1].MediaId, k, v)
131 | myfile.write(resultLine)
132 |
133 | elapsed = time.time()-startTime;
134 | print("Execution time: {0} s".format(elapsed))
135 |
--------------------------------------------------------------------------------
/train/trainModel.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Báint Czeba, Bálint Pál Tóth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Bálint Pál Tóth, Bálint Czeba,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | # this script is responsible for training the neural networks
26 |
27 | from scipy import io
28 | import pandas as pd
29 | import numpy as np
30 | import time
31 | import pickle
32 | import os
33 | import h5py
34 | import sys, getopt
35 | import datetime
36 | from MapCallback import MapCallback
37 |
38 | if __name__ == "__main__":
39 | argv=sys.argv[1:]
40 |
41 | nb_epochs = 20000 # number of epochs, should be high, the end of the learning process is controled by early stoping
42 | es_patience = 100 # patience for early stoping
43 | batchSize = 1350 # batch size for mini-batch training
44 | hdf5path = '../birdclef_data/data_top999_nozero.hdf5' # training data generated by loadData.py
45 | modelPath = './model-AlexNet.py' # filename of the model to use (currently model-birdClef.py or model-AlexNet.py)
46 | logfileName = 'log.xls'
47 | #scalerFilePath = '../birdclef_data/standardScaler_5000.pickle'
48 | scalerFilePath = None
49 | preTrainedModelWeightsPath = None # path and filename to pretrained network: if there is a pretrained network, we can load it and continue to train it
50 | tensorflowBackend = False # set true if Keras has TensorFlow backend - this way we set TF not to allocate all the GPU memory
51 |
52 | if (tensorflowBackend):
53 | import tensorflow as tf
54 | config = tf.ConfigProto()
55 | config.gpu_options.allow_growth=True
56 | sess = tf.Session(config=config)
57 | from keras import backend as K
58 | K.set_session(sess)
59 |
60 | print('nb_epochs: %d, hdf5path: %s, scalerFilePath: %s' % (nb_epochs, hdf5path,scalerFilePath))
61 |
62 | scaler = None
63 | scaleData = None
64 | # if a scaler file generated by loadData.py is given, than load it and define a scaler function that will be used later
65 | if scalerFilePath is not None:
66 | scaler = pickle.load(open(scalerFilePath, 'rb'))
67 | # Can't use scaler.transform because it only supports 2d arrays.
68 | def scaleData(X):
69 | return (X-scaler.mean_)/scaler.scale_
70 |
71 | from io_utils_mod import HDF5Matrix
72 | f = h5py.File(hdf5path, 'r')
73 | X = f.get('X')
74 | y = f.get('y')
75 | print("Shape of X: ")
76 | print(X.shape)
77 | dataSetLength = X.shape[0]
78 | output_dim = y.shape[1] #len(y_train[0])
79 | # test and validation splits
80 | testSplit = 0.01 # 1%
81 | validationSplit = 0.05 # 5%
82 | f.close()
83 | # load training data
84 | X_train = HDF5Matrix(hdf5path, 'X', 0, int(dataSetLength*(1-(testSplit+validationSplit))), normalizer = scaleData)
85 | y_train = HDF5Matrix(hdf5path, 'y', 0, int(dataSetLength*(1-(testSplit+validationSplit))))
86 | # load validation data
87 | X_validation = HDF5Matrix(hdf5path, 'X', int(dataSetLength*(1-(testSplit+validationSplit)))+1, int(dataSetLength*(1-testSplit)), normalizer = scaleData)
88 | y_validation = HDF5Matrix(hdf5path, 'y', int(dataSetLength*(1-(testSplit+validationSplit)))+1, int(dataSetLength*(1-testSplit)))
89 | # load test data
90 | X_test = HDF5Matrix(hdf5path, 'X', int(dataSetLength*(1-testSplit))+1, dataSetLength, normalizer = scaleData)
91 | y_test = HDF5Matrix(hdf5path, 'y', int(dataSetLength*(1-testSplit))+1, dataSetLength)
92 |
93 | print("Shape of X_train after train-validation-test split:")
94 | print(X_train.shape)
95 |
96 | # store the starting time
97 | startTime = time.time()
98 |
99 | # load model and compile it, we use RMSprop here, other optimizer algorithm should be tested
100 | execfile(modelPath)
101 | model.compile(loss='categorical_crossentropy', optimizer='rmsprop')#, metrics=["accuracy"])
102 |
103 | # print the model
104 | print("The following model is used: ")
105 | for layer in model.layers:
106 | print("{} output shape: {}".format(layer.name, layer.output_shape))
107 |
108 | # load pretrained model if it is set
109 | if preTrainedModelWeightsPath is not None:
110 | model.load_weights(preTrainedModelWeightsPath)
111 | print("Reloaded weights from: {}".format(preTrainedModelWeightsPath))
112 |
113 | # define callback functions
114 | mapcallback = MapCallback()
115 | earlyStopping = EarlyStopping(monitor='val_loss', patience = es_patience) # early stoping
116 | # save best models based on accuracy, loss and MAP metrics
117 | #bestModelFilePath_val_map = './modelWeights/best_val_map_{}_{}.hdf5'.format(output_dim, datetime.datetime.now().strftime('%Y-%m-%d-%M-%S'))
118 | #bestModelFilePath_val_acc = './modelWeights/best_val_acc_{}_{}.hdf5'.format(output_dim, datetime.datetime.now().strftime('%Y-%m-%d-%M-%S'))
119 | #bestModelFilePath_val_loss = './modelWeights/best_val_loss_{}_{}.hdf5'.format(output_dim, datetime.datetime.now().strftime('%Y-%m-%d-%M-%S'))
120 | bestModelFilePath_val_acc = './modelWeights/best_val_acc_{}.hdf5'.format(output_dim)
121 | bestModelFilePath_val_loss = './modelWeights/best_val_loss_{}.hdf5'.format(output_dim)
122 | bestModelFilePath_val_map = './modelWeights/best_val_map_{}.hdf5'.format(output_dim)
123 | checkpointer_val_acc = ModelCheckpoint(filepath = bestModelFilePath_val_acc, verbose = 1, monitor = 'val_acc', save_best_only = True)
124 | checkpointer_val_loss = ModelCheckpoint(filepath = bestModelFilePath_val_loss, verbose = 1, monitor = 'val_loss', save_best_only = True)
125 | checkpointer_val_map = ModelCheckpoint(filepath = bestModelFilePath_val_map, verbose = 1, monitor = 'val_map', mode = 'max', save_best_only = True)
126 |
127 | # training
128 | fitting_result = model.fit(X_train, y_train, nb_epoch = nb_epochs, batch_size = batchSize, callbacks = [earlyStopping, mapcallback, checkpointer_val_acc, checkpointer_val_loss, checkpointer_val_map], shuffle = 'batch', validation_data = (X_validation, y_validation))
129 |
130 | # calculate the elapsed time
131 | elapsed = time.time()-startTime;
132 | print("Execution time: {0} s".format(elapsed))
133 |
134 | # convert the output (probabilistics) to classes
135 | def proba_to_class(a):
136 | classCount = len(a[0])
137 | to_return = np.empty((0,classCount))
138 | for row in a:
139 | maxind = np.argmax(row)
140 | to_return = np.vstack((to_return, [1 if i == maxind else 0 for i in range(classCount)]))
141 | return to_return
142 |
143 | # calculate metrics on test data with the last model
144 | from sklearn.metrics import average_precision_score, accuracy_score
145 | y_result = model.predict(X_test)
146 | map = average_precision_score( y_test.data[y_test.start: y_test.end], y_result, average='micro')
147 | accuracy = accuracy_score(y_test.data[y_test.start: y_test.end], proba_to_class(y_result))
148 | print("AveragePrecision: {}".format(map))
149 | print("Accuracy: {}".format(accuracy))
150 |
151 | # reload the best model with smallest validation loss and calculate metrics on test data
152 | print("----- Loading best model from: {} -------".format(bestModelFilePath_val_loss))
153 | model.load_weights(bestModelFilePath_val_loss)
154 | y_result_bm = model.predict(X_test)
155 | map_bm_val_loss = average_precision_score( y_test.data[y_test.start: y_test.end], y_result_bm, average='macro')
156 | accuracy_bm_val_loss = accuracy_score(y_test.data[y_test.start: y_test.end], proba_to_class(y_result_bm))
157 | print("AveragePrecision: {}".format(map_bm_val_loss))
158 | print("Accuracy: {}".format(accuracy_bm_val_loss))
159 |
160 | # reload the best model with highest validation accuracy and calculate metrics on test data
161 | print("----- Loading best model from: {} -------".format(bestModelFilePath_val_acc))
162 | model.load_weights(bestModelFilePath_val_acc)
163 | y_result_bm = model.predict(X_test)
164 | map_bm_val_acc = average_precision_score( y_test.data[y_test.start: y_test.end], y_result_bm, average='macro')
165 | accuracy_bm_val_acc = accuracy_score(y_test.data[y_test.start: y_test.end], proba_to_class(y_result_bm))
166 | print("AveragePrecision: {}".format(map_bm_val_acc))
167 | print("Accuracy: {}".format(accuracy_bm_val_acc))
168 |
169 | # save the results summery into an excel file
170 | import log
171 | log.logToXLS(logfileName, model, fitting_result, {'execution(s)':elapsed, 'map':map, 'accuracy':accuracy, 'map_bm_val_loss':map_bm_val_loss, 'accuracy_bm_val_loss':accuracy_bm_val_loss,'map_bm_val_acc':map_bm_val_acc, 'accuracy_bm_val_acc':accuracy_bm_val_acc, 'modelPyFile': modelPath})
172 |
--------------------------------------------------------------------------------
/preprocess/xmltodict.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | "Makes working with XML feel like you are working with JSON"
3 | """ Source: https://github.com/martinblech/xmltodict"""
4 |
5 | try:
6 | import defusedexpat as expat
7 | except ImportError:
8 | from xml.parsers import expat
9 | from xml.sax.saxutils import XMLGenerator
10 | from xml.sax.xmlreader import AttributesImpl
11 | try: # pragma no cover
12 | from cStringIO import StringIO
13 | except ImportError: # pragma no cover
14 | try:
15 | from StringIO import StringIO
16 | except ImportError:
17 | from io import StringIO
18 | try: # pragma no cover
19 | from collections import OrderedDict
20 | except ImportError: # pragma no cover
21 | try:
22 | from ordereddict import OrderedDict
23 | except ImportError:
24 | OrderedDict = dict
25 |
26 | try: # pragma no cover
27 | _basestring = basestring
28 | except NameError: # pragma no cover
29 | _basestring = str
30 | try: # pragma no cover
31 | _unicode = unicode
32 | except NameError: # pragma no cover
33 | _unicode = str
34 |
35 | __author__ = 'Martin Blech'
36 | __version__ = '0.10.1'
37 | __license__ = 'MIT'
38 |
39 |
40 | class ParsingInterrupted(Exception):
41 | pass
42 |
43 |
44 | class _DictSAXHandler(object):
45 | def __init__(self,
46 | item_depth=0,
47 | item_callback=lambda *args: True,
48 | xml_attribs=True,
49 | attr_prefix='@',
50 | cdata_key='#text',
51 | force_cdata=False,
52 | cdata_separator='',
53 | postprocessor=None,
54 | dict_constructor=OrderedDict,
55 | strip_whitespace=True,
56 | namespace_separator=':',
57 | namespaces=None,
58 | force_list=None):
59 | self.path = []
60 | self.stack = []
61 | self.data = []
62 | self.item = None
63 | self.item_depth = item_depth
64 | self.xml_attribs = xml_attribs
65 | self.item_callback = item_callback
66 | self.attr_prefix = attr_prefix
67 | self.cdata_key = cdata_key
68 | self.force_cdata = force_cdata
69 | self.cdata_separator = cdata_separator
70 | self.postprocessor = postprocessor
71 | self.dict_constructor = dict_constructor
72 | self.strip_whitespace = strip_whitespace
73 | self.namespace_separator = namespace_separator
74 | self.namespaces = namespaces
75 | self.force_list = force_list
76 |
77 | def _build_name(self, full_name):
78 | if not self.namespaces:
79 | return full_name
80 | i = full_name.rfind(self.namespace_separator)
81 | if i == -1:
82 | return full_name
83 | namespace, name = full_name[:i], full_name[i+1:]
84 | short_namespace = self.namespaces.get(namespace, namespace)
85 | if not short_namespace:
86 | return name
87 | else:
88 | return self.namespace_separator.join((short_namespace, name))
89 |
90 | def _attrs_to_dict(self, attrs):
91 | if isinstance(attrs, dict):
92 | return attrs
93 | return self.dict_constructor(zip(attrs[0::2], attrs[1::2]))
94 |
95 | def startElement(self, full_name, attrs):
96 | name = self._build_name(full_name)
97 | attrs = self._attrs_to_dict(attrs)
98 | self.path.append((name, attrs or None))
99 | if len(self.path) > self.item_depth:
100 | self.stack.append((self.item, self.data))
101 | if self.xml_attribs:
102 | attr_entries = []
103 | for key, value in attrs.items():
104 | key = self.attr_prefix+self._build_name(key)
105 | if self.postprocessor:
106 | entry = self.postprocessor(self.path, key, value)
107 | else:
108 | entry = (key, value)
109 | if entry:
110 | attr_entries.append(entry)
111 | attrs = self.dict_constructor(attr_entries)
112 | else:
113 | attrs = None
114 | self.item = attrs or None
115 | self.data = []
116 |
117 | def endElement(self, full_name):
118 | name = self._build_name(full_name)
119 | if len(self.path) == self.item_depth:
120 | item = self.item
121 | if item is None:
122 | item = (None if not self.data
123 | else self.cdata_separator.join(self.data))
124 |
125 | should_continue = self.item_callback(self.path, item)
126 | if not should_continue:
127 | raise ParsingInterrupted()
128 | if len(self.stack):
129 | data = (None if not self.data
130 | else self.cdata_separator.join(self.data))
131 | item = self.item
132 | self.item, self.data = self.stack.pop()
133 | if self.strip_whitespace and data:
134 | data = data.strip() or None
135 | if data and self.force_cdata and item is None:
136 | item = self.dict_constructor()
137 | if item is not None:
138 | if data:
139 | self.push_data(item, self.cdata_key, data)
140 | self.item = self.push_data(self.item, name, item)
141 | else:
142 | self.item = self.push_data(self.item, name, data)
143 | else:
144 | self.item = None
145 | self.data = []
146 | self.path.pop()
147 |
148 | def characters(self, data):
149 | if not self.data:
150 | self.data = [data]
151 | else:
152 | self.data.append(data)
153 |
154 | def push_data(self, item, key, data):
155 | if self.postprocessor is not None:
156 | result = self.postprocessor(self.path, key, data)
157 | if result is None:
158 | return item
159 | key, data = result
160 | if item is None:
161 | item = self.dict_constructor()
162 | try:
163 | value = item[key]
164 | if isinstance(value, list):
165 | value.append(data)
166 | else:
167 | item[key] = [value, data]
168 | except KeyError:
169 | if self._should_force_list(key, data):
170 | item[key] = [data]
171 | else:
172 | item[key] = data
173 | return item
174 |
175 | def _should_force_list(self, key, value):
176 | if not self.force_list:
177 | return False
178 | try:
179 | return key in self.force_list
180 | except TypeError:
181 | return self.force_list(self.path[:-1], key, value)
182 |
183 |
184 | def parse(xml_input, encoding=None, expat=expat, process_namespaces=False,
185 | namespace_separator=':', **kwargs):
186 | """Parse the given XML input and convert it into a dictionary.
187 |
188 | `xml_input` can either be a `string` or a file-like object.
189 |
190 | If `xml_attribs` is `True`, element attributes are put in the dictionary
191 | among regular child elements, using `@` as a prefix to avoid collisions. If
192 | set to `False`, they are just ignored.
193 |
194 | Simple example::
195 |
196 | >>> import xmltodict
197 | >>> doc = xmltodict.parse(\"\"\"
198 | ...
199 | ... 1
200 | ... 2
201 | ...
202 | ... \"\"\")
203 | >>> doc['a']['@prop']
204 | u'x'
205 | >>> doc['a']['b']
206 | [u'1', u'2']
207 |
208 | If `item_depth` is `0`, the function returns a dictionary for the root
209 | element (default behavior). Otherwise, it calls `item_callback` every time
210 | an item at the specified depth is found and returns `None` in the end
211 | (streaming mode).
212 |
213 | The callback function receives two parameters: the `path` from the document
214 | root to the item (name-attribs pairs), and the `item` (dict). If the
215 | callback's return value is false-ish, parsing will be stopped with the
216 | :class:`ParsingInterrupted` exception.
217 |
218 | Streaming example::
219 |
220 | >>> def handle(path, item):
221 | ... print 'path:%s item:%s' % (path, item)
222 | ... return True
223 | ...
224 | >>> xmltodict.parse(\"\"\"
225 | ...
226 | ... 1
227 | ... 2
228 | ... \"\"\", item_depth=2, item_callback=handle)
229 | path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1
230 | path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2
231 |
232 | The optional argument `postprocessor` is a function that takes `path`,
233 | `key` and `value` as positional arguments and returns a new `(key, value)`
234 | pair where both `key` and `value` may have changed. Usage example::
235 |
236 | >>> def postprocessor(path, key, value):
237 | ... try:
238 | ... return key + ':int', int(value)
239 | ... except (ValueError, TypeError):
240 | ... return key, value
241 | >>> xmltodict.parse('12x',
242 | ... postprocessor=postprocessor)
243 | OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))])
244 |
245 | You can pass an alternate version of `expat` (such as `defusedexpat`) by
246 | using the `expat` parameter. E.g:
247 |
248 | >>> import defusedexpat
249 | >>> xmltodict.parse('hello', expat=defusedexpat.pyexpat)
250 | OrderedDict([(u'a', u'hello')])
251 |
252 | You can use the force_list argument to force lists to be created even
253 | when there is only a single child of a given level of hierarchy. The
254 | force_list argument is a tuple of keys. If the key for a given level
255 | of hierarchy is in the force_list argument, that level of hierarchy
256 | will have a list as a child (even if there is only one sub-element).
257 | The index_keys operation takes precendence over this. This is applied
258 | after any user-supplied postprocessor has already run.
259 |
260 | For example, given this input:
261 |
262 |
263 | host1
264 | Linux
265 |
266 |
267 | em0
268 | 10.0.0.1
269 |
270 |
271 |
272 |
273 |
274 | If called with force_list=('interface',), it will produce
275 | this dictionary:
276 | {'servers':
277 | {'server':
278 | {'name': 'host1',
279 | 'os': 'Linux'},
280 | 'interfaces':
281 | {'interface':
282 | [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }
283 |
284 | `force_list` can also be a callable that receives `path`, `key` and
285 | `value`. This is helpful in cases where the logic that decides whether
286 | a list should be forced is more complex.
287 | """
288 | handler = _DictSAXHandler(namespace_separator=namespace_separator,
289 | **kwargs)
290 | if isinstance(xml_input, _unicode):
291 | if not encoding:
292 | encoding = 'utf-8'
293 | xml_input = xml_input.encode(encoding)
294 | if not process_namespaces:
295 | namespace_separator = None
296 | parser = expat.ParserCreate(
297 | encoding,
298 | namespace_separator
299 | )
300 | try:
301 | parser.ordered_attributes = True
302 | except AttributeError:
303 | # Jython's expat does not support ordered_attributes
304 | pass
305 | parser.StartElementHandler = handler.startElement
306 | parser.EndElementHandler = handler.endElement
307 | parser.CharacterDataHandler = handler.characters
308 | parser.buffer_text = True
309 | try:
310 | parser.ParseFile(xml_input)
311 | except (TypeError, AttributeError):
312 | parser.Parse(xml_input, True)
313 | return handler.item
314 |
315 |
316 | def _emit(key, value, content_handler,
317 | attr_prefix='@',
318 | cdata_key='#text',
319 | depth=0,
320 | preprocessor=None,
321 | pretty=False,
322 | newl='\n',
323 | indent='\t',
324 | full_document=True):
325 | if preprocessor is not None:
326 | result = preprocessor(key, value)
327 | if result is None:
328 | return
329 | key, value = result
330 | if (not hasattr(value, '__iter__')
331 | or isinstance(value, _basestring)
332 | or isinstance(value, dict)):
333 | value = [value]
334 | for index, v in enumerate(value):
335 | if full_document and depth == 0 and index > 0:
336 | raise ValueError('document with multiple roots')
337 | if v is None:
338 | v = OrderedDict()
339 | elif not isinstance(v, dict):
340 | v = _unicode(v)
341 | if isinstance(v, _basestring):
342 | v = OrderedDict(((cdata_key, v),))
343 | cdata = None
344 | attrs = OrderedDict()
345 | children = []
346 | for ik, iv in v.items():
347 | if ik == cdata_key:
348 | cdata = iv
349 | continue
350 | if ik.startswith(attr_prefix):
351 | if not isinstance(iv, _unicode):
352 | iv = _unicode(iv)
353 | attrs[ik[len(attr_prefix):]] = iv
354 | continue
355 | children.append((ik, iv))
356 | if pretty:
357 | content_handler.ignorableWhitespace(depth * indent)
358 | content_handler.startElement(key, AttributesImpl(attrs))
359 | if pretty and children:
360 | content_handler.ignorableWhitespace(newl)
361 | for child_key, child_value in children:
362 | _emit(child_key, child_value, content_handler,
363 | attr_prefix, cdata_key, depth+1, preprocessor,
364 | pretty, newl, indent)
365 | if cdata is not None:
366 | content_handler.characters(cdata)
367 | if pretty and children:
368 | content_handler.ignorableWhitespace(depth * indent)
369 | content_handler.endElement(key)
370 | if pretty and depth:
371 | content_handler.ignorableWhitespace(newl)
372 |
373 |
374 | def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
375 | **kwargs):
376 | """Emit an XML document for the given `input_dict` (reverse of `parse`).
377 |
378 | The resulting XML document is returned as a string, but if `output` (a
379 | file-like object) is specified, it is written there instead.
380 |
381 | Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
382 | as XML node attributes, whereas keys equal to `cdata_key`
383 | (default=`'#text'`) are treated as character data.
384 |
385 | The `pretty` parameter (default=`False`) enables pretty-printing. In this
386 | mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
387 | can be customized with the `newl` and `indent` parameters.
388 |
389 | """
390 | if full_document and len(input_dict) != 1:
391 | raise ValueError('Document must have exactly one root.')
392 | must_return = False
393 | if output is None:
394 | output = StringIO()
395 | must_return = True
396 | content_handler = XMLGenerator(output, encoding)
397 | if full_document:
398 | content_handler.startDocument()
399 | for key, value in input_dict.items():
400 | _emit(key, value, content_handler, full_document=full_document,
401 | **kwargs)
402 | if full_document:
403 | content_handler.endDocument()
404 | if must_return:
405 | value = output.getvalue()
406 | try: # pragma no cover
407 | value = value.decode(encoding)
408 | except AttributeError: # pragma no cover
409 | pass
410 | return value
411 |
412 | if __name__ == '__main__': # pragma: no cover
413 | import sys
414 | import marshal
415 | try:
416 | stdin = sys.stdin.buffer
417 | stdout = sys.stdout.buffer
418 | except AttributeError:
419 | stdin = sys.stdin
420 | stdout = sys.stdout
421 |
422 | (item_depth,) = sys.argv[1:]
423 | item_depth = int(item_depth)
424 |
425 |
426 | def handle_item(path, item):
427 | marshal.dump((path, item), stdout)
428 | return True
429 |
430 | try:
431 | root = parse(stdin,
432 | item_depth=item_depth,
433 | item_callback=handle_item,
434 | dict_constructor=dict)
435 | if item_depth == 0:
436 | handle_item([], root)
437 | except KeyboardInterrupt:
438 | pass
439 |
--------------------------------------------------------------------------------
/preprocess/loadData.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Birdsong classificatione in noisy environment with convolutional neural nets in Keras
4 | # Copyright (C) 2017 Balint Czeba, Balint Pal Toth (toth.b@tmit.bme.hu)
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see . (c) Balint Czeba, Balint Pal Toth
18 | #
19 | # Please cite the following paper if this code was useful for your research:
20 | #
21 | # Tóth Bálint Pál, Czeba Bálint,
22 | # "Convolutional Neural Networks for Large-Scale Bird Song Classification in Noisy Environment",
23 | # In: Working Notes of Conference and Labs of the Evaluation Forum, Évora, Portugália, 2016, p. 8
24 |
25 | from scipy import io
26 | from scipy.io import wavfile
27 | import numpy as np
28 | import os
29 | import matplotlib
30 | import matplotlib.pyplot as plt
31 | from matplotlib import mlab
32 | import xmltodict
33 | import pandas as pd
34 | import h5py
35 | import pickle
36 | import gc
37 | np.random.seed(0)
38 | matplotlib.use('Agg')
39 | plt.ioff()
40 |
41 | # traiing data related paths
42 | PATH_TRAIN_IN_16KWAVS = '../birdclef_data/TrainingSet/wav_16khz' # the location where the 16kHz resampled wavs are located
43 | PATH_TRAIN_IN_XMLFILES = '../birdclef_data/TrainingSet/xml/' # the path where the XML meta-data files are located
44 | PATH_TRAIN_OUT_XMLPICKLEFILE = '../birdclef_data/TrainingSet/xml_data.pickle' # the location and filename where the XML meta-data will be saved
45 | PATH_TRAIN_OUT_HDF5 = '../birdclef_data/' # the path where preprocessed data will be saved in HDF5 format
46 |
47 | # same as above just with test data, the wav related data will be generating in train/predict.py
48 | PATH_TEST_IN_XMLFILES = '../birdclef_data/test/xml2015'
49 | PATH_TEST_OUT_XMLPICKLEFILE = '../birdclef_data/test/xml_data.pickle'
50 |
51 | # this parameter is used for preprocessing
52 | # the number comes from the following equation: np.floor(sampling_frequency/(FFT_length-FFT_overlap))*num_of_seconds
53 | # we use 16kHz sampling rate for the wavs, 512 FFT window length with 256 overlap and we investigate 5 seconds
54 | spectrogramWindowLength = int(5*np.floor(16000/(512-256)));
55 |
56 | # function to load the wave files from dirPath
57 | def loadWavs(dirPath):
58 | data = list()
59 | for path, subdirs, files in os.walk(dirpath):
60 | for name in files:
61 | if (name.endswith('.wav')):
62 | print os.path.join(path, name)
63 | tempFileName = name.split('.')[0]
64 | tempXmlFile = open(os.path.join(xmldirpath, tempFileName + '.xml'), 'rb')
65 | metadata = tempXmlFile.readlines()
66 | tempXmlFile.close()
67 | data.append([io.wavfile.read(os.path.join(path, name))[1], xmltodict.parse(''.join(metadata))['Audio']])
68 | return data;
69 |
70 | # function to load corresponding XML files into a Pandas dataframe
71 | def readXMLs(xmldirpath):
72 | df = pd.DataFrame()
73 | for path, subdirs, files in os.walk(xmldirpath):
74 | for name in files:
75 | print os.path.join(path, name)
76 | if (name.endswith('.xml')):
77 | print os.path.join(path, name)
78 | tempXmlFile = open(os.path.join(path, name), 'rb')
79 | metadata = tempXmlFile.readlines()
80 | tempXmlFile.close()
81 | df = df.append(pd.DataFrame(xmltodict.parse(''.join(metadata))['Audio'], index=[0])).reset_index(drop=True)
82 | return df
83 |
84 | # function to merge meta-data of the XML file
85 | def mergeOFGS(row):
86 | return "{} {} {} {}".format(row["Order"], row["Family"], row["Genus"], row["Species"])
87 |
88 | # if 'x' array contains 1, this expands it inthe given directions
89 | # used for the mask applied to the spectogram
90 | def expandOnes(x, directions = [[-1,0], [1,0], [0,-1], [0,1]]):
91 | expand = np.zeros(x.shape)
92 | for i in range(x.shape[0]):
93 | for j in range(x.shape[1]):
94 | if (x[i,j] == 1):
95 | for direction in directions:
96 | cx = i + direction[0]
97 | cy = j + direction[1]
98 | if (0 <= cx < x.shape[0] and 0 <= cy < x.shape[1]):
99 | expand[cx,cy]=1;
100 | return x+expand;
101 |
102 | # function to filter the spectogram based on the energy of the signal
103 | #
104 | # parameters:
105 | # data audio data
106 | # expandByOne if it is True, than the mask of the spectogram will be expanded in every direction
107 | # dropZeroColumnsPercent determines the ratio of 0 values along the frequency axis when a timeslice is dropped
108 | #
109 | # return values:
110 | # spectogram
111 | # filtered spectogram
112 |
113 | def audioToFilteredSpectrogram(data, expandByOne = True, dropZeroColumnsPercent = 0.95):
114 | # calculate the spectogram
115 | tempSpec = np.log10(mlab.specgram(data, NFFT=512, noverlap=256, Fs=16000)[0])
116 |
117 | # drop higher frequencies
118 | tempSpec = tempSpec[0:200,:]
119 | tempSpecFiltered = np.copy(tempSpec)
120 |
121 | # we analize the spectogram by 20x30 sized cells
122 | # to achieve better accuray the size of this cell should be finetuned
123 | rowBorders = np.ceil(np.linspace(0,tempSpec.shape[0], 20))
124 | columnBorders = np.hstack((np.ceil(np.arange(0,tempSpec.shape[1], 30)), tempSpec.shape[1]))
125 | rowBorders = [ int(x) for x in rowBorders ]
126 | columnBorders = [ int(x) for x in columnBorders ]
127 | keepCells = np.ones((len(rowBorders)-1, len(columnBorders)-1))
128 |
129 | # we create a mask for the spectogram: we scan the spectogram with the 20x30 sized
130 | # cell and create 0 mask based on the mean and std of the spectogram calculated for the cells and rows
131 | for i in range(len(rowBorders)-1):
132 | row_mean = np.mean(tempSpec[rowBorders[i]:rowBorders[i+1],:])
133 | row_std = np.std(tempSpec[rowBorders[i]:rowBorders[i+1],:])
134 |
135 | for j in range(len(columnBorders)-1):
136 | cell_mean = np.mean(tempSpec[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]])
137 | cell_max_top10_mean = np.mean(np.sort(tempSpec[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]], axis=None)[-10:])
138 |
139 | if (cell_mean < 0 or ((cell_max_top10_mean) < (row_mean + row_std)*1.5)):
140 | keepCells[i,j]=0
141 |
142 | # expand by ones (see above)
143 | if expandByOne:
144 | keepCells = expandOnes(keepCells)
145 |
146 | # apply the mask to the spectogram
147 | for i in range(keepCells.shape[0]):
148 | for j in range(keepCells.shape[1]):
149 | if not keepCells[i,j]:
150 | tempSpecFiltered[rowBorders[i]:rowBorders[i+1],columnBorders[j]:columnBorders[j+1]] = 0
151 |
152 | # drop zero columns
153 | # the amount of zero values along axis 0 (frequency) is calculated for every column (timeslice)
154 | # and it is dropped, if the number of zero values is higher than the dropZeroColumnsPercent
155 | # eg. dropZeroColumnsPercent=0.95, than a column (timeslice) is dropped, if more than 95% of the values (frequencies) is 0
156 | tempSpecFilteredBackup = np.copy(tempSpecFiltered)
157 | tempSpecFiltered = np.delete(tempSpecFiltered, np.nonzero((tempSpecFiltered==0).sum(axis=0) > tempSpecFiltered.shape[0]*dropZeroColumnsPercent), axis=1)
158 |
159 | # if every row was 0 than use the backed up spectogram
160 | if tempSpecFiltered.shape[1] == 0:
161 | tempSpecFiltered = tempSpecFilteredBackup
162 |
163 | return tempSpec, tempSpecFiltered;
164 |
165 | # function to return most common classes in the dataset
166 | def getMostCommon(df, N=10):
167 | from collections import Counter
168 | c = Counter(df["ClassId"])
169 | mostCommon = c.most_common(N)
170 | df_mostCommon = pd.DataFrame()
171 | for item in mostCommon:
172 | df_mostCommon = df_mostCommon.append(df[df["ClassId"] == item[0]], ignore_index=True)
173 | df_mostCommon.reset_index(drop=True)
174 | return df_mostCommon;
175 |
176 | # function to return data inbetween minQuality and maxQuality
177 | def filterByQuality(df, minQuality=0, maxQuality=5):
178 | df_filtered = pd.DataFrame()
179 | for quality in range(minQuality, maxQuality+1):
180 | df_filtered = df_filtered.append(df[df["Quality"] == str(quality)], ignore_index=True)
181 | df_filtered.reset_index(drop=True, inplace=True)
182 | return df_filtered;
183 |
184 | # function to remove samples where background species exist
185 | def removeSamplesWithBackgroundSpecies(df):
186 | return df[df.BackgroundSpecies.isnull()]
187 |
188 | # create onehot encoding for order, family, genus, specie
189 | def getOneHotOFGS(df):
190 | from sklearn.preprocessing import LabelBinarizer
191 | lb = LabelBinarizer()
192 | lb.fit(df["OFGS"])
193 | return ( lb, lb.transform(df["OFGS"]) )
194 |
195 | # create onehot encoding for classid
196 | def getOneHotClassId(df):
197 | from sklearn.preprocessing import LabelBinarizer
198 | lb = LabelBinarizer()
199 | lb.fit(df["ClassId"])
200 | return ( lb, lb.transform(df["ClassId"]) )
201 |
202 | # bulk processing of wav files in path
203 | #
204 | # parameters:
205 | # path the source path
206 | # filenames the filenames in the path
207 | # dontFilter does not filter the spectogram if it is set to True
208 | #
209 | # return value:
210 | # specotogram data of multiple files
211 |
212 | def wavsToSpectrogramByList(path, filenames, dontFilter=False):
213 | print("wavsToSpectrogramByList...")
214 | data=list()
215 | for filename in filenames:
216 | print('\r Processing {}'.format(os.path.join(path, filename))),
217 | (tempSpecUnfiltered,tempSpecFiltered) = audioToFilteredSpectrogram(io.wavfile.read(os.path.join(path, filename))[1], expandByOne=True)
218 | if (not dontFilter):
219 | data.append(tempSpecFiltered)
220 | else:
221 | data.append(tempSpecUnfiltered)
222 | print("\nwavsToSpectrogramByList finished")
223 | return data;
224 |
225 | # function to create training data from the list generated by wavsToSpectogramByList function
226 | #
227 | # parameters:
228 | # slist the spectogram list generated by wavsToSpectogramByList function
229 | # labels contain the class labels of the corresponding spectograms
230 | # N (1*44100)/(1024-512)=86
231 | # filenames filenames to return
232 | # classIds class IDs to return
233 | #
234 | # return values
235 | # X the constructed input
236 | # y the constructed output
237 | # fn filenames
238 | # cIds class IDs
239 | #
240 |
241 | def spectrogramListToT4(slist, labels=None, N=spectrogramWindowLength, filenames=None, classIds=None):
242 | print("SpectrogramListToT4...")
243 |
244 | rows = len(slist[0])
245 | X = np.empty((0,1,rows,N))
246 | y = []
247 | fn = []
248 | cIds = []
249 |
250 | # process all spectograms
251 | for i in range(len(slist)):
252 | print('\r Processing no. %d / %d' % (i, len(slist)))
253 | ranges = np.hstack((np.arange(0, len(slist[i][0]), N), len(slist[i][0])))
254 |
255 | for j in range(len(ranges)-1):
256 | # variable contains
257 | tempSpec = np.empty((1,rows,N))
258 |
259 | if (len(slist[i][0]) < N): # if data is shorter than N than fill up with zeros
260 | tempSpec[0] = np.hstack((slist[i],np.zeros((rows, N-len(slist[i][0])))))
261 | elif (ranges[j+1]-ranges[j] < N): # last element
262 | tempSpec[0] = slist[i][:,-N:]
263 | else: # other part of the spectrum
264 | tempSpec[0] = slist[i][:,ranges[j]:ranges[j+1]]
265 |
266 | X = np.vstack((X,[tempSpec]))
267 |
268 | if labels is not None:
269 | y.append(labels[i])
270 | if filenames is not None:
271 | fn.append(filenames[i])
272 | if classIds is not None:
273 | cIds.append(classIds[i])
274 |
275 | print("SpectrogramListToT4 finished")
276 | return X, y, fn, cIds
277 |
278 | # calculates the standard scaler coefficients of the input data for 0 mean and 1 variance
279 | #
280 | # parameters
281 | # numberOfFiles the number of files to process (we assume that the mean and variance will be similar in case
282 | # of a subset of the training data and we don't have to process the whole database
283 | # wavdirpath the path that contains the wavs (sampled at 16kHz)
284 | # xmlpicklepath the path and filename that contains the XML file for training (xml_data.pickle)
285 | #
286 | # return values
287 | # scaler
288 | # spectogramData
289 | #
290 |
291 | def generateScaler(numberOfFiles=100, wavdirpath=PATH_TRAIN_IN_16KWAVS, xmlpicklepath=PATH_TRAIN_OUT_XMLPICKLEFILE, todirrootpath=PATH_TRAIN_OUT_HDF5):
292 | if not os.path.exists(todirrootpath):
293 | os.makedirs(todirrootpath)
294 |
295 | import pickle
296 | df = pd.read_pickle(xmlpicklepath) # contains the metadata
297 | print("Metadata loaded")
298 |
299 | # Shuffle rows
300 | df = df.iloc[np.random.permutation(len(df))]
301 | df.reset_index(drop=True, inplace=True)
302 | print("Metadata shuffled")
303 |
304 | # Calculate spectograms
305 | spectrogramData = wavsToSpectrogramByList(wavdirpath, df.FileName[:numberOfFiles], dontFilter=False)
306 | print("Spectrograms done.")
307 |
308 | print('Building scaler...')
309 | from sklearn.preprocessing import StandardScaler
310 | scaler = StandardScaler()
311 | # calculate the scaler variables spectogram by spectogram
312 | for sData in spectrogramData:
313 | scaler.partial_fit(sData.reshape(-1,1))
314 |
315 | # filename where we save the scaler
316 | saveTo = os.path.join(todirrootpath,"standardScaler_{}.pickle".format(numberOfFiles))
317 | from sklearn.externals import joblib
318 | import pickle
319 | pickle.dump(scaler, open(saveTo, 'wb'))
320 | print('Scaler saved to: {}'.format(saveTo))
321 |
322 | return scaler, spectrogramData
323 |
324 | # function that constructs training data
325 | #
326 | # parameters:
327 | # N number of most classes to take into account
328 | # wavdirpath path of the wave files (16kHz)
329 | # xmlpicklepath the path and filename that contains the XML file for training (xml_data.pickle)
330 | # todirrootpath path were to save the training data
331 | #
332 | # return values:
333 | # X,y,fn for debuging purposes
334 | #
335 |
336 | def processNMostCommon(N=3, wavdirpath=PATH_TRAIN_IN_16KWAVS, xmlpicklepath=PATH_TRAIN_OUT_XMLPICKLEFILE, todirrootpath=PATH_TRAIN_OUT_HDF5):
337 | global spectrogramWindowLength
338 |
339 | if not os.path.exists(todirrootpath):
340 | os.makedirs(todirrootpath)
341 |
342 | spectrogramHeight = 200
343 |
344 | f = h5py.File(os.path.join(todirrootpath,"data_top{}_nozero.hdf5".format(N)), "w")
345 | dsetX = f.create_dataset('X', (0,1,spectrogramHeight,spectrogramWindowLength), maxshape=(None, 1,spectrogramHeight,spectrogramWindowLength))
346 | dsety = f.create_dataset('y', (0,N), maxshape=(None,N))
347 | dsetMediaId = f.create_dataset('MediaId', (0,1), maxshape=(None,1))
348 | dsetClassId = f.create_dataset('ClassId', (0,1), maxshape=(None,1), dtype=h5py.special_dtype(vlen=unicode))
349 |
350 | import pickle
351 | df = pd.read_pickle(xmlpicklepath) # read the metadata
352 |
353 | # if we would like to keep recordings with a given quality than we can do it here by uncommenting the next line
354 | #df = filterByQuality(df, 0, 3)
355 |
356 | df["OFGS"] = df.apply(mergeOFGS, axis=1) # merge Order, Family, Genus, Species
357 | df_mc = getMostCommon(df, N) # get N most common classes from the dataset
358 | df = None # let GC free up some memory
359 | print("Metadata loaded")
360 |
361 | # Shuffle rows
362 | df_mc = df_mc.iloc[np.random.permutation(len(df_mc))]
363 | df_mc.reset_index(drop=True, inplace=True)
364 | (lb,binaryLabels) = getOneHotClassId(df_mc) # generate one-hot labels
365 | pickle.dump(lb, open(os.path.join(todirrootpath,"labelBinarizer_top{}.pickle".format(N)), 'wb'))
366 |
367 | # process the selected files of top N classes and save the data into HDF5
368 | fileRanges = np.hstack((np.arange(0, len(df_mc), 30), len(df_mc)))
369 | for i in range(len(fileRanges)-1):
370 | tempSG = wavsToSpectrogramByList(wavdirpath, df_mc.FileName[fileRanges[i]: fileRanges[i+1]], dontFilter=False)
371 | X, y, fn, cIds = spectrogramListToT4(tempSG, \
372 | binaryLabels[fileRanges[i]: fileRanges[i+1]], \
373 | filenames = df_mc.MediaId[fileRanges[i]: fileRanges[i+1]].values, N=spectrogramWindowLength, \
374 | classIds = df_mc.ClassId[fileRanges[i]: fileRanges[i+1]].values) #convert to t4
375 | pre_len = dsetX.shape[0]
376 | add_len = X.shape[0]
377 | dsetX.resize(pre_len+add_len, axis=0)
378 | dsety.resize(pre_len+add_len, axis=0)
379 | dsetMediaId.resize(pre_len + add_len, axis=0)
380 | dsetClassId.resize(pre_len + add_len, axis=0)
381 | dsetX[pre_len:pre_len+add_len,:,:,:] = X
382 | dsety[pre_len:pre_len+add_len,:] = y
383 | dsetMediaId[pre_len:pre_len+add_len,:] = np.transpose([[int(i) for i in fn]])
384 | dsetClassId[pre_len:pre_len+add_len,:] = np.transpose([[s.encode('utf8') for s in cIds]])
385 | f.flush()
386 |
387 | f.close
388 | return (X,y,fn) # return last batch for debug purposes
389 |
390 | print("== Generating training data ==")
391 | print("Reading XML files and generating pickle file")
392 | df_xml = readXMLs(PATH_TRAIN_IN_XMLFILES) # read XML files with meta-data
393 | df_xml.to_pickle(PATH_TRAIN_OUT_XMLPICKLEFILE) # save the loaded meta-data into a pickle file with all the informatio
394 | print("Process wav files and save them into HDF5")
395 | (X, y, fn) = processNMostCommon(999, wavdirpath=PATH_TRAIN_IN_16KWAVS, xmlpicklepath=PATH_TRAIN_OUT_XMLPICKLEFILE, todirrootpath=PATH_TRAIN_OUT_HDF5) # processes the most common 999 species (so the whole dataset)
396 | # print("Generating scaler")
397 | # scaler, data = generateScaler(5000, wavdirpath=PATH_TRAIN_IN_16KWAVS, xmlpicklepath=PATH_TRAIN_OUT_XMLPICKLEFILE, todirrootpath=PATH_TRAIN_OUT_HDF5) # calculates and saves the standard scaler based on 5000 wav files
398 |
399 | print("== Generating test data ==")
400 | print("Reading XML files and generating pickle file")
401 | df_xml = readXMLs(PATH_TEST_IN_XMLFILES) # read XML files with meta-data
402 | df_xml.to_pickle(PATH_TEST_OUT_XMLPICKLEFILE) # save the loaded meta-data into a pickle file with all the informatio
403 |
404 |
405 | '''
406 | # The following code is for plotting some data for inspection
407 | for data_item in data:
408 | print("Processing {}".format(data_item[1]['FileName']))
409 | tempSpec, tempSpecFiltered = audioToFilteredSpectrogram(data_item[0])
410 | plt.ioff()
411 | fig = plt.figure(figsize=(19,10))
412 | plt.hold(False)
413 | ax1=plt.subplot(211)
414 | plt.tight_layout()
415 | plt.pcolormesh(tempSpec, cmap=plt.cm.binary)
416 | plt.subplot(212, sharex=ax1, sharey=ax1)
417 | plt.pcolormesh(tempSpecFiltered, cmap=plt.cm.binary)
418 | fig.savefig('../figures/filter_expand1/' + data_item[1]['FileName'][:-4] + '.png', transparent = True)
419 | plt.close(fig)
420 | '''
421 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 |
622 |
--------------------------------------------------------------------------------