1 contributor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import argparse
import subprocess
import numpy
import os
import sys
import time
import multiprocessing
def initialize():
defaults = {
'sample_time' : 500,
'span' : 150,
'step' : 1,
'min_overlap' : 20,
'threshold' : 80,
'processor' : os.cpu_count(),
'separator' : ';'
}
def check_nproc(arg):
try:
n = int(arg)
except ValueError:
raise argparse.ArgumentTypeError("il faut un nombre entier")
if n < 1 or n > os.cpu_count():
raise argparse.ArgumentTypeError("{} n'est pas compris entre 1 et {:d}".format(n, os.cpu_count()))
return n
def check_threshold(arg):
try:
n = float(arg)
except ValueError:
raise argparse.ArgumentTypeError("il faut un nombre")
if n < 0 or n > 100:
raise argparse.ArgumentTypeError("{} n'est pas compris entre 0 et 100 inclus".format(n))
return n
def parse_input_files(input_file, source_files):
if isinstance(input_file, list):
for f in input_file:
parse_input_files(f, source_files)
else:
if os.path.isfile(input_file):
source_files[input_file] = 1
elif os.path.isdir(input_file):
for root, dirs, files in os.walk(input_file):
for f in files:
parse_input_files(os.path.join(root, f), source_files)
parser = argparse.ArgumentParser(__file__)
parser.add_argument("-i ", "--source-file",
action = 'append',
nargs = '+',
help = "répertoire ou fichier"
)
parser.add_argument("-t ", "--threshold",
type = check_threshold,
default = defaults['threshold'],
help = "seuil en pourcentage sous lequel il est considéré qu'il n'y a pas de corrélation (défaut: %(default)d)"
)
parser.add_argument("-p ", "--processor",
type = check_nproc,
default = defaults['processor'],
help = "le nombre de processus parallèles lancés (défaut: %(default)d)"
)
parser.add_argument("--sample-time",
type = int,
default = defaults['sample_time'],
help = "seconds to sample audio file for fpcalc (défaut: %(default)d)"
)
parser.add_argument("--span",
type = int,
default = defaults['span'],
help = "finesse en points pour scanner la corrélation (défaut: %(default)d)"
)
parser.add_argument("--step",
type = int,
default = defaults['step'],
help = "valeur du pas en points de corrélation (défaut: %(default)d)"
)
parser.add_argument("--min-overlap",
type = int,
default = defaults['min_overlap'],
help = "nombre minimal de points de correspondance (défaut %(default)d)"
)
parser.add_argument("--separator",
type = str,
default = defaults['separator'],
help = "séparateur des champs de résultat (défaut '%(default)s')"
)
args = parser.parse_args()
source_files = {}
for f in args.source_file:
parse_input_files(f, source_files)
return list(source_files.keys()), args
def prime(i, primes):
for prime in primes:
if not (i == prime or i % prime):
return False
primes.add(i)
return i
def nPrimes(n):
primes = set([2])
i, p = 2, 0
while True:
if prime(i, primes):
p += 1
if p == n:
return primes
i += 1
def getPrimes(n, ids):
a = 0
b = 0
for i in ids:
if n % i == 0:
a = i
b = int(n / i)
break
return a, b
def calculate_fingerprints(filename):
fpcalc_out = subprocess.getoutput('fpcalc -raw -length {} "{}"'.format(args.sample_time, filename))
fingerprint_index = fpcalc_out.find('FINGERPRINT=') + 12
return fpcalc_out[fingerprint_index:]
def correlation(listx, listy):
if len(listx) == 0 or len(listy) == 0:
raise Exception('Empty lists cannot be correlated.')
if len(listx) > len(listy):
listx = listx[:len(listy)]
elif len(listx) < len(listy):
listy = listy[:len(listx)]
covariance = 0
for i in range(len(listx)):
covariance += 32 - bin(listx[i] ^ listy[i]).count("1")
covariance = covariance / float(len(listx))
return covariance/32
def cross_correlation(listx, listy, offset):
if offset > 0:
listx = listx[offset:]
listy = listy[:len(listx)]
elif offset < 0:
offset = -offset
listy = listy[offset:]
listx = listx[:len(listy)]
if min(len(listx), len(listy)) < args.min_overlap:
return
return correlation(listx, listy)
def compare(listx, listy, span, step):
if span > min(len(list(listx)), len(list(listy))):
raise Exception('span >= sample size: %i >= %i\n'
% (span, min(len(list(listx)), len(list(listy))))
+ 'Reduce span, reduce crop or increase sample_time.')
corr_xy = []
for offset in numpy.arange(-span, span + 1, step):
corr_xy.append(cross_correlation(listx, listy, offset))
return corr_xy
def get_max_corr(corr, source, target):
max_corr_index = corr.index(max(corr))
max_corr_offset = -args.span + max_corr_index * args.step
if corr[max_corr_index] * 100 >= args.threshold:
return corr[max_corr_index], max_corr_offset
def correlate(source, target):
corr = compare(source, target, args.span, args.step)
return get_max_corr(corr, source, target)
def get_tests_nbr(n):
return n * n - n * ( n + 1 ) / 2
def get_ETA(start, total, done):
now = time.time()
return time.ctime(now + (now - start) / done * (total - done))
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def mp_calculate_fingerprints(key):
try:
ziques[key] = {
'fingerprint': list(map(int, calculate_fingerprints(ziques[key]['path']).split(','))),
'path': ziques[key]['path']
}
except:
erreurs.append(ziques[key]['path'])
del ziques[key]
pass
def mp_correlate(key):
try:
c, o = correlate(
ziques[comparaison[key]['a']]['fingerprint'],
ziques[comparaison[key]['b']]['fingerprint'])
comparaison[key] = {
'a': comparaison[key]['a'],
'b': comparaison[key]['b'],
'correlation': c,
'offset': o
}
except:
del comparaison[key]
pass
if __name__ == "__main__":
global args
source_files, args= initialize()
if len(source_files) < 2:
print("au moins deux fichiers sont nécessaires")
sys.exit()
ids = list(nPrimes(len(source_files)))
total_ids = len(ids)
manager = multiprocessing.Manager()
ziques = manager.dict()
comparaison = manager.dict()
erreurs = manager.list()
pool = multiprocessing.Pool(args.processor)
for f in range(len(source_files)):
ziques[ids[f]] = { 'path': source_files[f] }
del source_files
nb_erreurs = len(erreurs)
start = time.time()
for i, _ in enumerate(pool.imap_unordered(mp_calculate_fingerprints, ziques.keys()), 1):
nb_erreurs = len(erreurs)
print('calcul des empreintes{:s}: {:.1f}% (ETA {:s})'.format(
("", " (" + str(nb_erreurs) + " erreur{})".format(("", "s")[nb_erreurs > 1]))[nb_erreurs > 0],
i / total_ids * 100,
get_ETA(start, total_ids, i)),
end='\r')
sys.stdout.write("\033[K")
print('calcul des empreintes terminé ({:d} fichiers traités{:s})'.format(
len(ziques),
("", " et " + str(nb_erreurs) + " erreur{}".format(("", "s")[nb_erreurs > 1]))[nb_erreurs > 0]))
if len(erreurs):
print("Fichier{} en erreur:".format(("", "s")[len(erreurs) > 1]))
for k in erreurs:
print(k)
print()
erreurs[:] = []
nb_erreurs = len(erreurs)
nb_tests = get_tests_nbr(len(ziques))
done = 0
start = time.time()
for a in ziques.keys():
for b in ziques.keys():
id_correl = a * b
if a == b or id_correl in comparaison:
continue
comparaison[id_correl] = {
'a': a,
'b': b
}
done += 1
print("construction liste: {:.1f}% (ETA {:s})".format(
done / nb_tests * 100,
get_ETA(start, nb_tests, done)),
end='\r')
sys.stdout.write("\033[K")
tests_nbr = len(comparaison)
start = time.time()
for i, _ in enumerate(pool.imap_unordered(mp_correlate, comparaison.keys()), 1):
found = len(comparaison) + i - tests_nbr
print('{:s} corrélation{pluriel:s} trouvée{pluriel:s}: {:.1f}% (ETA {:s}){:s}'.format(
("aucune", str(found))[found > 0],
i / tests_nbr * 100,
get_ETA(start, tests_nbr, i),
' ',
pluriel = ("", "s")[found > 1]),
end='\r')
sys.stdout.write("\033[K")
print('comparaison terminée:\n{0:d} comparaison{pluriel1} effectuée{pluriel1}\n{1} corrélation{pluriel2} trouvée{pluriel2} (seuil {2}%)'.format(
tests_nbr,
len(comparaison),
args.threshold,
pluriel1=("", "s")[tests_nbr > 1],
pluriel2=("", "s")[len(comparaison) > 1],
))
for k in comparaison.keys():
print("{:s}{sep}{:s}{sep}{:.2f}%{sep}{:d}".format(
ziques[comparaison[k]['a']]['path'],
ziques[comparaison[k]['b']]['path'],
comparaison[k]['correlation'] * 100,
comparaison[k]['offset'],
sep = args.separator
))