-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangel.py
More file actions
2029 lines (1961 loc) · 62.1 KB
/
angel.py
File metadata and controls
2029 lines (1961 loc) · 62.1 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import builtins
import collections
import datetime
import functools
import glob
import ijson
import itertools
import math
import multiprocessing
import numpy
import operator
import os
import pickle
import regex
import scipy.stats
import sklearn.svm
import subprocess
import sys
import traceback
import typing
import unicodedata
def return_source(
source_prefix=None,
source_filter=None,
source_sorter=None,
source_merger=None,
source_number=None,
source_pickle=None,
source_search=None,
source_indexs=None,
source_reduce=None,
tracks_filter=None,
tracks_window=None,
tracks_weight=None,
tracks_fscore=None,
tracks_recall=None,
tracks_common=None,
tracks_artist=None,
tracks_mapper=None,
tracks_number=None,
tracks_reduce=None,
tracks_merger=None,
thread_number=None
):
if isinstance(source_prefix, str):
source_prefix = [source_prefix]
if source_pickle is None:
source_pickle = True
if source_search is None:
source_search = True
if source_indexs is not None:
if source_indexs == True:
source_indexs = {}
assert isinstance(source_indexs, dict)
if tracks_filter and \
not callable(tracks_filter):
if not isinstance(tracks_filter, set):
tracks_filter = set(tracks_filter)
tracks_filter = \
expand_artist(tracks_filter)
tracks_filter -= ignore_tracks()
if tracks_fscore is None:
tracks_fscore = True
if tracks_filter:
if tracks_window is None:
tracks_window = math.inf
if tracks_artist is None:
tracks_artist = True
if tracks_reduce is None:
tracks_reduce = True
source = None
if source_indexs is not None and \
tracks_filter and \
not callable(tracks_filter):
artist_filter = \
set(itertools.chain(*map(
track_artist, tracks_filter)))
prefix = \
set(map(lambda _:
os.path.split(_)[0],
source_prefix))
_indexs = source_indexs.setdefault('', {})
source = collections.Counter()
for artist in artist_filter:
indexs = source_indexs.get(artist)
if indexs is None:
indexs = \
source_indexs.setdefault(
artist, set())
globed = \
itertools.chain(*(
glob.iglob(
os.path.join(
'indexs',
artist,
_prefix,
'*.pickle'))
for _prefix in prefix))
_ = os.path.join(
'indexs', artist, '')
for entity in globed:
_entity, suffix = \
os.path.splitext(entity)
_entity = \
_entity.removeprefix(_)
with open(entity, 'rb') as f:
ids = pickle.load(f)
indexs.update(ids)
_indexs.update(
zip(ids,
itertools.repeat(
_entity)))
source.update(iter(indexs))
source = \
collections.Counter({
(file :=
os.path.join(
_indexs[id],
str(id)+'.json')):
counts
if not tracks_fscore else
fscore(
counts/os.path.getsize(
file.removesuffix(
'.json') +
'.pickle')*10,
counts/len(artist_filter),
weight=1.25)
for id, counts in
source.most_common()})
if source_search and \
source_pickle and \
tracks_filter and \
not callable(tracks_filter):
if source:
_source_number = 20000
source = \
collections.Counter(dict(
source.most_common(
_source_number)))
source = \
collections.Counter({
_[0].removesuffix(
'.pickle') + '.json':
round(_[1], 3)
for _ in locate_pickle(
source or source_prefix,
tracks_filter,
tracks_weight,
tracks_artist).items()
if tracks_common is None or
_[1] >= tracks_common})
if tracks_fscore:
_source = \
locate_pickle(
source, return_cmdarg=True)
_tracks = \
locate_pickle(
[], tracks_filter,
return_cmdarg=True)
bundle = \
int(len(source) * 0.7 / (
len(' '.join(_source)) / (
os.sysconf('SC_ARG_MAX')
- len(' '.join(_tracks))
))) + 1
counts = \
sum(map(
locate_pickle,
itertools.batched(
source, bundle
)), collections.Counter())
def _fscore(_source, common):
_source = \
_source.removesuffix(
'.json') + '.pickle'
precis = common / \
(counts[_source] or math.inf)
recall = common / \
len(tracks_filter)
return fscore(
precis, recall, tracks_recall)
source = \
collections.Counter({
_[0]: _fscore(*_)
for _ in source.items()
if tracks_fscore is True or
_fscore(*_) >= tracks_fscore})
if source is None:
source = \
collections.Counter(
locate_source(
prefix=source_prefix))
else:
if source_sorter is None:
source = \
collections.Counter(
dict(source.most_common()))
source_sorter = False
if source_sorter is None:
source_sorter = os.path.getmtime
if source_sorter:
source = \
collections.Counter(dict(
sorted(
source.items(), key=lambda _:
(source_sorter(_[0]), _[1]))))
if source_merger is None:
source_merger = unique_source
if source_merger:
source = source_merger(source)
if source_filter or source_number:
source_islice = \
itertools.islice(
filter(
lambda _:
source_filter is None or (
source_filter(_[0])
if callable(
source_filter
) else
_[0] in source_filter
), source.items()
), source_number)
source_queued = \
collections.Counter(
dict(source_islice))
else:
source_queued = source
def worker(_):
_source, _params, _reduce = _
try:
tracks = \
import_source(_source, *_params)
except Exception:
print(_source)
raise
if tracks:
if not _reduce:
return _source, tracks
else:
return _reduce([(_source, tracks)])
else:
return None
params = \
zip(source_queued,
itertools.repeat((
tracks_filter,
tracks_window,
tracks_number,
tracks_mapper,
source_pickle)),
itertools.repeat(tracks_reduce))
if not thread_number:
thread_number = 1
if thread_number == 1:
result = map(worker, params)
else:
thread = \
multiprocessing.pool.ThreadPool(
thread_number)
result = \
thread.imap_unordered(worker, params)
try:
result = filter(None, result)
if not tracks_reduce:
result = dict(result)
if tracks_reduce is True:
return source_queued
if callable(tracks_reduce):
addend = next(result, None)
if addend is None:
result = list(result)
return None
if isinstance(
addend, typing.Iterator):
addend = list(addend)
result = map(list, result)
if tracks_merger is None:
if isinstance(
addend, collections.Counter):
def merger(c1, c2):
for k in c2:
if k not in c1:
c1[k] = c2[k]
else:
c1[k] += c2[k]
return c1
elif isinstance(addend, dict):
def merger(d1, d2):
d1.update(d2)
return d1
else:
merger = operator.iadd
else:
merger = tracks_merger
result = \
functools.reduce(
merger, result, addend)
if callable(source_reduce):
result = source_reduce(result.items())
if thread_number > 1:
worker.close()
worker.join()
return result
except Exception, KeyboardInterrupt:
if thread_number > 1:
worker.terminate()
worker.join()
raise
def obtain_indexs(
source_prefix, tracks_artist=None):
artist_source = {}
def tracks_reduce(source_tracks):
for source, tracks in source_tracks:
id = source_id(source)
for track in tracks:
artist = track_artist(track)
for _artist in artist:
if tracks_artist and \
_artist not in \
tracks_artist:
continue
artist_source.setdefault(
_artist, set()).add(id)
return_source(
source_prefix=source_prefix,
tracks_reduce=tracks_reduce)
_prefix, entity = os.path.split(source_prefix)
for artist, source in artist_source.items():
entity_prefix = \
os.path.join(
'indexs', artist, _prefix)
os.makedirs(entity_prefix, exist_ok=True)
_entity = \
os.path.join(
entity_prefix, entity + '.pickle')
with open(_entity, 'wb') as f:
pickle.dump(source, f)
def period_source_filter(before=False, **kwargs):
period = datetime.datetime(**kwargs)
if not period: return None
def source_filter(_):
return before == (
os.path.getmtime(_)
< period.timestamp())
return source_filter
def agesex_source_filter(
source,
minage=None,
maxage=None,
gender=None
):
if minage or maxage:
date = datetime.datetime.now()
ages = {
_['id']: date.year -
datetime.datetime.strptime(
_['bdate'], '%d.%m.%Y').year
for _ in source
if 'bdate' in _ and
_['bdate'].split('.')[2:]}
if gender:
sexs = {
_['id']: _['sex']
for _ in source if 'sex' in _}
def source_filter(file):
id = source_id(file)
if minage and minage > \
ages.get(id, 0): return False
if maxage and maxage < \
ages.get(id, math.inf): return False
if gender and gender != \
sexs.get(id): return False
return True
return source_filter
def nearby_tracks_filter(
tracks_metric,
nearby_source,
*remote_source,
nearby_cutoff=0.95
):
source = [
return_tracks(_) for _ in
(nearby_source, *remote_source)]
def tracks_filter(track):
metric = tracks_metric(track)
if not metric: return False
def scores(tracks):
return map(
lambda _:
_[0] if type(_) is tuple else _,
filter(None, map(metric, tracks)))
_scores = [
statistics.mean(scores(tracks))
for tracks in source]
return _scores[0] / max(_scores) \
>= nearby_cutoff
return tracks_filter
def labels_tracks_filter(
tracks_metric,
tracks_labels,
target_labels={0}
):
tracks_counts = \
collections.Counter(
itertools.chain(*tracks_labels))
tracks_labels = {
track: label
for label, tracks in
enumerate(tracks_labels)
for track in tracks
if tracks_counts[track] <= 1}
metric = \
tracks_metric(tracks_labels, counts=False)
tracks = list(metric)
tracks_indexs = \
dict(map(reversed, enumerate(tracks)))
indexs = [
tracks_indexs[track]
for track in tracks_labels
if track in tracks_indexs]
kernel = metric[:, indexs].copy()
kernel /= numpy.max(kernel)
labels = [
tracks_labels[tracks[index]]
for index in indexs]
svmsvc = sklearn.svm.SVC(kernel='precomputed')
svmsvc.fit(kernel, labels)
def tracks_filter(track):
index = tracks_indexs.get(track)
if index is None: return False
kernel = metric[:, [index]].T.copy()
labels = svmsvc.predict(kernel)
return labels[0] in target_labels
return tracks_filter
def source_tracks_reduce():
def source_reduce(source_tracks):
source_counts = collections.Counter()
for source, tracks in source_tracks:
source_counts[source] = len(tracks)
return source_counts
return source_reduce
def counts_tracks_reduce(tracks_weight=None):
def counts_reduce(source_tracks):
tracks_counts = collections.Counter()
for source, tracks in source_tracks:
tracks_counts.update(iter(tracks))
if tracks_weight:
tracks_counts = \
collections.Counter({
track: count *
tracks_weight
.get(track, 0)
for track, count in
tracks_counts.items()})
return tracks_counts
return counts_reduce
def common_tracks_reduce(
tracks_filter,
tracks_weight=None,
tracks_fscore=None,
tracks_recall=None,
tracks_common=None,
tracks_number=None,
tracks_reduce=None,
artist_reduce=None,
artist_expand=None,
artist_weight=None,
artist_cutoff=None,
return_sorted=None,
return_source=None,
return_fscore=None,
return_common=None,
return_number=None,
return_tracks=None
):
assert not callable(tracks_filter)
_tracks_filter = set()
if not artist_expand or artist_weight:
_tracks_filter |= \
expand_artist(set(tracks_filter))
if artist_expand:
_tracks_filter |= {
artist for track in tracks_filter
for artist in track_artist(track)}
tracks_filter = _tracks_filter
if callable(tracks_reduce):
return_tracks = True
if not artist_expand:
if artist_reduce is None:
artist_reduce = True
else:
if not artist_weight:
artist_reduce = None
if return_sorted != False and \
not return_fscore and \
not return_common and \
not return_number:
return_sorted = True
if return_fscore != False:
return_fscore = True
if return_common != False:
return_common = True
if return_number != False:
return_number = True
def common_reduce(source_tracks):
result = []
class _dict(dict):
def __lt__(self, other):
return len(self) < len(other)
for source, tracks in source_tracks:
tracks_source = set()
if not artist_expand or \
artist_weight:
tracks_source |= \
tracks.keys() | \
expand_artist(
tracks.keys() -
tracks_filter,
collab=False)
common0 = \
len(tracks_source
& tracks_filter)
if artist_expand:
tracks_source |= {
artist for track in tracks
if not artist_weight or
track not in tracks_filter
for artist in
track_artist(track)}
common_tracks = \
tracks_source & tracks_filter
if not common_tracks: continue
if artist_reduce:
common_tracks = {
track_artist(track)[0]
for track in common_tracks}
common1 = len(common_tracks)
if not artist_expand or \
not artist_weight:
if not tracks_weight:
common = len(common_tracks)
else:
common = sum(map(
tracks_weight.__getitem__,
common_tracks))
else:
counts = collections.Counter()
for track in common_tracks:
artist = \
track_artist(track)[0]
counts[artist] += (
artist_weight
if ' - ' not in track else
tracks_weight[track]
if tracks_weight else 1)
counts[artist] = \
min(counts[artist],
artist_cutoff or 1)
common = sum(counts.values())
if tracks_fscore or return_fscore:
precis = common/len(tracks)
recall = common/len(tracks_filter)
_fscore = fscore(
precis, recall, tracks_recall)
if tracks_fscore:
if _fscore < tracks_fscore:
continue
if tracks_common:
if common < tracks_common:
continue
if tracks_number:
if len(tracks_source) \
< tracks_number: continue
scores = []
if return_fscore:
scores.append(_fscore)
if return_common:
if not artist_weight:
scores.append(common)
else:
scores.append((
common, common0, common1))
if return_number:
scores.append(len(tracks))
if return_tracks:
if return_sorted:
tracks = _dict(tracks)
scores.append(tracks)
if len(scores) > 1:
scores = (tuple(scores),)
result.append(
(source, *scores)
if scores else source)
if isinstance(return_source, int):
if return_sorted:
if return_fscore or \
return_common or \
return_number:
result = \
collections.Counter(
dict(result)
).most_common(
return_source)
result = result[:return_source]
if not callable(tracks_reduce):
if return_fscore or \
return_common or \
return_number:
result = \
collections.Counter(
dict(result))
else:
result = (
(source, scores[-1]
if type(scores) is tuple
else scores
) for source, scores in result)
result = tracks_reduce(result)
return result
return common_reduce
def impact_tracks_reduce(tracks_filter):
if not isinstance(tracks_filter, set):
tracks_filter = set(tracks_filter)
def impact_reduce(source_tracks):
tracks_impact = collections.Counter()
for source, tracks in source_tracks:
tracks_common = \
tracks.keys() & tracks_filter
tracks_weight = \
collections.Counter(
dict.fromkeys(
tracks_common,
1 / len(tracks_common)))
for track in tracks:
if track not in tracks_filter:
if track not in tracks_impact:
tracks_impact[track] = \
collections.Counter()
tracks_impact[track] += \
tracks_weight
return tracks_impact
return impact_reduce
def proxim_tracks_reduce(
tracks_filter,
tracks_window=1,
tracks_weight=None,
tracks_artist=None,
tracks_proxim=None
):
if not isinstance(tracks_filter, set):
tracks_filter = set(tracks_filter)
if not tracks_weight:
tracks_weight = \
dict.fromkeys(tracks_filter, 1)
if tracks_artist:
tracks_artist = {
track: track_artist(track)[0]
for track in tracks_filter}
artist_counts = \
collections.Counter(
tracks_artist.values())
def proxim_reduce(source_tracks):
tracks_counts = collections.Counter()
for source, tracks in source_tracks:
common_tracks = \
tracks.keys() & tracks_filter
if not common_tracks: continue
indexs = {}
for track in common_tracks:
weight = \
tracks_weight.get(track, 1) \
/ len(tracks[track])
if tracks_artist:
weight /= \
artist_counts[
tracks_artist[track]]
for index in tracks[track]:
for shift in range(
-tracks_window,
tracks_window + 1):
if tracks_proxim:
proxim = 1 - (
abs(shift or 1)-1
) / tracks_window
else:
proxim = 1
indexs[index + shift] = \
max(proxim * weight,
indexs.setdefault(
index + shift,
0))
for track in tracks:
weight = 0
for _index in tracks[track]:
_weight = indexs.get(_index)
if _weight:
weight = \
max(_weight, weight)
if weight:
tracks_counts[track] += weight
for track, count in tracks_counts.items():
tracks_counts[track] = round(count, 3)
return tracks_counts
return proxim_reduce
def filter_tracks(
tracks,
string,
action=str.__contains__,
negate=False
):
def filter_entity(entity):
if isinstance(entity, tuple):
entity = entity[0]
if isinstance(string, str):
return not negate == \
action(entity, string)
else:
return negate == (
not next(
filter(
lambda _:
action(entity, _),
string), False))
if isinstance(tracks, dict):
return type(tracks)(
dict(
filter_tracks(
list(tracks.items()),
string,
action,
negate)))
else:
return type(tracks)(
filter(filter_entity, tracks))
def fscore(precis, recall, weight=1, digits=3):
if precis == 0 or recall == 0: return 0
if weight == 0:
weight_precis, weight_recall = 1, 0
elif weight == math.inf:
weight_precis, weight_recall = 0, 1
else:
weight_precis, weight_recall = \
1 / (weight or 0.5) ** 2, 1
result = \
(weight_precis + weight_recall) \
/ (weight_precis / precis +
weight_recall / recall)
return round(result, digits)
def idf(counts, slicer=None, weight=None):
if weight is None:
maxima = counts.most_common(1)[0][1]
def weight(count):
if count == 0: return 0
return 1 + math.log(
maxima / count, 10)
if weight is False:
def weight(count): return 1
return type(counts)({
track: weight(count)
for track, count in (
counts.items()
if slicer is None else
counts.most_common()[slicer])})
def ndcg(ranked, seeded, digits=3):
ndcg, idcg, hits = 0, 0, 0
for index, id in enumerate(ranked):
if isinstance(id, tuple): id = id[0]
if id in seeded:
ndcg += 1 / math.log(index+2, 2)
hits += 1
idcg += 1 / math.log(index+2, 2)
return (
round(ndcg / idcg, digits),
round(hits / len(ranked), digits))
def user2item(
source_prefix=None,
source_filter=None,
source_number=None,
source_debias=None,
tracks_filter=None,
tracks_window=None,
tracks_weight=None,
tracks_fscore=None,
tracks_recall=None,
tracks_common=None,
tracks_artist=None,
tracks_proxim=None,
tracks_debias=None,
tracks_mapper=None,
thread_number=None
):
if source_number:
if not tracks_fscore and \
not tracks_common:
tracks_fscore = True
if tracks_filter:
if tracks_window is None:
tracks_window = math.inf
args = dict(
source_prefix=source_prefix,
source_filter=source_filter,
source_number=source_number,
tracks_filter=tracks_filter,
tracks_weight=tracks_weight,
tracks_fscore=tracks_fscore,
tracks_recall=tracks_recall,
tracks_common=tracks_common,
tracks_artist=tracks_artist,
tracks_mapper=tracks_mapper,
thread_number=thread_number)
if source_debias or tracks_debias:
tracks_counts = \
return_source(
tracks_window=tracks_window
if tracks_debias else 0,
tracks_reduce=
counts_tracks_reduce(),
**args)
if source_debias:
args |= \
dict(tracks_weight=idf(tracks_counts))
if tracks_debias:
tracks_weight = {
track: 1 / count
for track, count in
tracks_counts.items()}
if tracks_proxim or tracks_debias:
tracks_reduce = \
proxim_tracks_reduce(
tracks_filter,
tracks_weight,
tracks_artist,
tracks_window,
tracks_proxim)
else:
tracks_reduce = counts_tracks_reduce()
return return_source(
tracks_window=tracks_window,
tracks_reduce=tracks_reduce,
**args)
def item2item(
caches_suffix,
cached_metric=None,
update_metric=None,
source_prefix=None,
source_filter=None,
source_number=None,
tracks_filter=None,
tracks_window=None,
tracks_weight=None,
tracks_fscore=None,
tracks_common=None,
tracks_mapper=None,
tracks_reduce=None,
tracks_number=None,
tracks_offset=None,
lookup_transp=None,
thread_number=None
):
def return_counts(update=False):
source_cached = \
'source_counts.{}.pickle' \
.format(caches_suffix)
if os.path.exists(source_cached):
with open(source_cached, 'rb') as f:
source_counts = pickle.load(f)
else:
source_counts = {}
tracks_cached = \
'tracks_counts.{}.pickle' \
.format(caches_suffix)
if os.path.exists(tracks_cached):
with open(tracks_cached, 'rb') as f:
tracks_counts = pickle.load(f)
else:
tracks_counts = {}
if not update:
assert source_counts, source_cached
assert tracks_counts, tracks_cached
if source_counts and tracks_counts:
return source_counts, tracks_counts
assert source_prefix, f'{source_prefix=}'
source_counts = {}
tracks_counts = collections.Counter()
def _tracks_reduce(source_tracks):
if tracks_reduce:
source_tracks = \
tracks_reduce(source_tracks)
for source, tracks in source_tracks:
source_counts[source] = len(tracks)
tracks_counts.update(iter(tracks))
return_source(
source_prefix=source_prefix,
source_filter=source_filter,
source_number=source_number,
tracks_filter=tracks_filter,
tracks_window=tracks_window,
tracks_weight=tracks_weight,
tracks_fscore=tracks_fscore,
tracks_common=tracks_common,
tracks_mapper=tracks_mapper,
tracks_reduce=_tracks_reduce,
thread_number=1)
if tracks_number:
tracks_counts = \
dict(
tracks_counts.most_common(
tracks_number))
with open(source_cached, 'wb') as f:
pickle.dump(source_counts, f)
with open(tracks_cached, 'wb') as f:
pickle.dump(tracks_counts, f)
return source_counts, tracks_counts
def return_indexs(update=False):
indexs_cached = \
'tracks_source.{}.pickle' \
.format(caches_suffix)
if not update or \
os.path.exists(indexs_cached):
with open(indexs_cached, 'rb') as f:
return pickle.load(f)
assert source_prefix, f'{source_prefix=}'
source_counts, tracks_counts = \
return_counts()
source_ranked = \
dict(
map(reversed,
enumerate(source_counts)))
tracks_source = {}
def _tracks_reduce(source_tracks):
def _tracks_reduce(source_tracks):
if tracks_reduce:
source_tracks = \
tracks_reduce(
source_tracks)
for source, tracks in source_tracks:
if source not in source_ranked:
continue
number = source_ranked[source]
for track in tracks:
if track in tracks_counts:
tracks_source. \
setdefault(
track, set()
).add(number)
return_source(
source_prefix=source_counts,
source_search=False,
tracks_filter=tracks_counts
if not tracks_mapper else (
lambda track:
tracks_mapper(track)
in tracks_counts),
tracks_mapper=tracks_mapper,
tracks_reduce=_tracks_reduce,
thread_number=1)
tracks_source = [
tracks_source.get(track, set())
for track in tracks_counts]
with open(indexs_cached, 'wb') as f:
pickle.dump(tracks_source, f)
return tracks_source
def obtain_metric(
index1,
source_weight,
source_counts,
tracks_counts,
tracks_source,
metric,
common,
normed=True,
invert=True,