-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
search_by_distance.js
2003 lines (1948 loc) · 107 KB
/
search_by_distance.js
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
'use strict';
//10/02/23
/*
Search by Distance
-----------------------------------
Creates a playlist with similar tracks to the currently selected one according
to genre, style, key, etc. Every library track is given a score using its tags
and/or a graph distance with their genre/style.
When their score is over 'scoreFilter', then they are included in the final pool.
After all tracks have been evaluated and the final pool is complete, some of
them are chosen to populate the playlist. You can choose whether this final
selection is done according to score, randomly chosen, etc. All settings are
configurable on the properties panel (or set in the files when called using
buttons, etc.)
There are 3 methods to calc similarity: WEIGHT, GRAPH and DYNGENRE.
Any weight equal to zero or tag not set will be skipped for calcs. Therefore it's
recommended to only use those really relevant, for speed improvements. There are 3
exceptions to this rule:
- dyngenreWeight > 0 & method = DYNGENRE:
genre and style tags will always be retrieved, even if their weight is set
to 0. They will not be considered for scoring... but are needed to calculate
dynGenre virtual tags.
- method = GRAPH:
genre and style tags will always be retrieved, even if their weight is set
to 0. They will not be considered for scoring... but are needed to calculate
the distance in the graph between different tracks.
- bInKeyMixingPlaylist = true:
key tags will always be retrieved, even if keyWeight is set to 0. This is
done to create the special playlist even if keys are totally ignored for
similarity scoring.
*/
include('..\\..\\helpers-external\\ngraph\\a-star.js');
include('..\\..\\helpers-external\\ngraph\\a-greedy-star.js');
include('..\\..\\helpers-external\\ngraph\\NBA.js');
include('ngraph_helpers_xxx.js');
var bLoadTags = true; // This tells the helper to load tags descriptors extra files
include('..\\..\\helpers\\helpers_xxx.js');
include('..\\..\\helpers\\helpers_xxx_crc.js');
include('..\\..\\helpers\\helpers_xxx_prototypes.js');
include('..\\..\\helpers\\helpers_xxx_properties.js');
include('..\\..\\helpers\\helpers_xxx_tags.js');
if (isFoobarV2) {include('..\\..\\helpers\\helpers_xxx_tags_cache.js');}
include('..\\..\\helpers\\helpers_xxx_math.js');
include('..\\..\\helpers\\helpers_xxx_statistics.js');
include('..\\..\\helpers\\camelot_wheel_xxx.js');
include('..\\..\\helpers\\dyngenre_map_xxx.js');
include('..\\music_graph\\music_graph_xxx.js');
include('..\\music_graph\\music_graph_test_xxx.js');
include('..\\filter_and_query\\remove_duplicates.js');
include('..\\sort\\scatter_by_tags.js');
include('..\\..\\helpers\\callbacks_xxx.js');
include('search_by_distance_extra.js');
checkCompatible('1.6.1', 'smp');
/*
Properties
*/
const SearchByDistance_properties = {
tags : ['Tags used for scoring', JSON.stringify({
genre: {weight: 15, tf: [globTags.genre], baseScore: 0, scoringDistribution: 'LINEAR', type: ['string', 'multiple', 'graph']},
style: {weight: 15, tf: [globTags.style], baseScore: 0, scoringDistribution: 'LINEAR', type: ['string', 'multiple', 'graph']},
dynGenre: {weight: 40, tf: [], baseScore: 0, scoringDistribution: 'LINEAR', type: ['number', 'virtual', 'absRange'], range: 1},
mood: {weight: 10, tf: [globTags.mood], baseScore: 0, scoringDistribution: 'LINEAR', type: ['string', 'multiple', 'combinations'], combs: 6}, // Used for query filtering, combinations of K moods for queries. Greater values will pre-filter better the library...
key: {weight: 5, tf: [globTags.key], baseScore: 0, scoringDistribution: 'LINEAR', type: ['string', 'single', 'keyMix', 'keyRange'], range: 1},
bpm: {weight: 5, tf: [globTags.bpm], baseScore: 0, scoringDistribution: 'LINEAR', type: ['number', 'single', 'percentRange'], range: 25},
date: {weight: 10, tf: [globTags.date], baseScore: 0, scoringDistribution: 'LINEAR', type: ['number', 'single', 'absRange'], range: 15},
composer: {weight: 0, tf: ['COMPOSER'], baseScore: 0, scoringDistribution: 'LINEAR', type: ['string', 'multiple']}
})],
scoreFilter : ['Exclude any track with similarity lower than (in %)', 70, {range: [[0,100]], func: isInt}, 70],
minScoreFilter : ['Minimum in case there are not enough tracks (in %)', 65, {range: [[0,100]], func: isInt}, 65],
graphDistance : ['Exclude any track with graph distance greater than (only GRAPH method):', 'music_graph_descriptors.intra_supergenre',
{func: (x) => {return (isString(x) && music_graph_descriptors.hasOwnProperty(x.split('.').pop())) || isInt(x) || x === Infinity;}}, 'music_graph_descriptors.intra_supergenre'],
method : ['Method to use (\'GRAPH\', \'DYNGENRE\' or \'WEIGHT\')', 'GRAPH', {func: checkMethod}, 'GRAPH'],
bNegativeWeighting : ['Assign negative score when tags fall outside their range', true],
bFilterWithGraph : ['Filter values not present on the graph', true],
forcedQuery : ['Forced query to pre-filter database (added to any other internal query)', globQuery.filter],
bSameArtistFilter : ['Exclude tracks by same artist', false],
bUseAntiInfluencesFilter: ['Exclude anti-influences by query', false],
bConditionAntiInfluences: ['Conditional anti-influences filter', false],
bUseInfluencesFilter : ['Allow only influences by query', false],
bSimilArtistsFilter : ['Allow only similar artists', false],
genreStyleFilterTag : ['Filter these values globally for genre/style', JSON.stringify(['Children\'s Music','?'])],
poolFilteringTag : ['Filter pool by tag', JSON.stringify([globTags.artist])],
poolFilteringN : ['Allows only N + 1 tracks on the pool (-1 = disabled)', -1, {greaterEq: -1, func: isInt}, -1],
bRandomPick : ['Take randomly from pool? (not sorted by weighting)', true],
probPick : ['Probability of tracks being choosen for final mix (makes playlist a bit random!)', 100, {range: [[1,100]], func: isInt}, 100],
playlistLength : ['Max Playlist Mix length', 50],
bSortRandom : ['Sort final playlist randomly', false],
bProgressiveListOrder : ['Sort final playlist by score', false],
bScatterInstrumentals : ['Intercalate instrumental tracks', false],
bInKeyMixingPlaylist : ['DJ-like playlist creation, following harmonic mixing rules', false],
bHarmonicMixDoublePass : ['Harmonic mixing double pass to match more tracks', true],
bProgressiveListCreation: ['Recursive playlist creation, uses output as new references', false],
progressiveListCreationN: ['Steps when using recursive playlist creation (>1 and <=100)', 4, {range: [[2,100]], func: isInt}, 4],
playlistName : ['Playlist name (TF allowed)', 'Search...', {func: isString}, 'Search...'],
bAscii : ['Asciify string values internally?', true],
checkDuplicatesByTag : ['Remove duplicates by', JSON.stringify(globTags.remDupl)],
bAdvTitle : ['Duplicates advanced RegExp title matching?', true],
bSmartShuffle : ['Smart Shuffle by Artist', true],
smartShuffleTag : ['Smart Shuffle tag', JSON.stringify([globTags.artist])]
};
// Checks
Object.keys(SearchByDistance_properties).forEach((key) => { // Checks
const k = key.toLowerCase();
if (k.endsWith('weight')) {
SearchByDistance_properties[key].push({greaterEq: 0, func: Number.isSafeInteger}, SearchByDistance_properties[key][1]);
} else if (k.endsWith('length')) {
SearchByDistance_properties[key].push({greaterEq: 0, func: Number.isSafeInteger}, SearchByDistance_properties[key][1]);
} else if (k.endsWith('query')) {
SearchByDistance_properties[key].push({func: (query) => {return checkQuery(query, true);}}, SearchByDistance_properties[key][1]);
} else if (k.endsWith('tag') || k.endsWith('tags')) {
SearchByDistance_properties[key].push({func: isJSON}, SearchByDistance_properties[key][1]);
} else if (regExBool.test(key)) {
SearchByDistance_properties[key].push({func: isBoolean}, SearchByDistance_properties[key][1]);
}
});
const SearchByDistance_panelProperties = {
bCacheOnStartup : ['Calculates link cache on script startup (instead of on demand)', true],
bGraphDebug : ['Warnings about links/nodes set wrong', false],
bSearchDebug : ['Enables debugging console logs', false],
bProfile : ['Enables profiling console logs', false],
bShowQuery : ['Enables query console logs', false],
bBasicLogging : ['Enables basic console logs', true],
bShowFinalSelection : ['Enables selection\'s final scoring console logs', true],
firstPopup : ['Search by distance: Fired once', false],
descriptorCRC : ['Graph Descriptors CRC', -1], // Calculated later on first time
bAllMusicDescriptors : ['Load All Music descriptors?', false],
bLastfmDescriptors : ['Load Last.fm descriptors?', false],
bStartLogging : ['Startup logging', false],
bTagsCache : ['Read tags from cache instead of files?', false]
};
// Checks
Object.keys(SearchByDistance_panelProperties).forEach( (key) => { // Checks
if (regExBool.test(key)) {
SearchByDistance_panelProperties[key].push({func: isBoolean}, SearchByDistance_panelProperties[key][1]);
}
});
var sbd_prefix = 'sbd_';
if (typeof buttonsBar === 'undefined' && typeof bNotProperties === 'undefined') { // Merge all properties when not loaded along buttons
// With const var creating new properties is needed, instead of reassigning using A = {...A,...B}
Object.entries(SearchByDistance_panelProperties).forEach(([key, value]) => {SearchByDistance_properties[key] = value;});
setProperties(SearchByDistance_properties, sbd_prefix);
} else { // With buttons, set these properties only once per panel
setProperties(SearchByDistance_panelProperties, sbd_prefix);
}
/*
Initialize maps/graphs at start. Global variables
*/
const sbd = {
allMusicGraph: musicGraph(),
influenceMethod: 'adjacentNodes', // direct, zeroNodes, adjacentNodes, fullPath
genreMap: [],
styleMap: [],
genreStyleMap: [],
isCalculatingCache: false,
panelProperties: (typeof buttonsBar === 'undefined' && typeof bNotProperties === 'undefined') ? getPropertiesPairs(SearchByDistance_properties, sbd_prefix) : getPropertiesPairs(SearchByDistance_panelProperties, sbd_prefix),
};
[sbd.genreMap , sbd.styleMap, sbd.genreStyleMap] = dyngenreMap();
// Info Popup
if (!sbd.panelProperties.firstPopup[1]) {
// sbd.panelProperties.firstPopup[1] = true; // Do it on script unloading the first time it successfully closed, so it can be reused somewhere if needed
overwriteProperties(sbd.panelProperties); // Updates panel
const readmeKeys = [{name: 'search_by_distance', title: 'Search by Distance'}, {name: 'tags_structure', title: 'Tagging requisites'}]; // Must read files on first execution
readmeKeys.forEach((objRead) => {
const readmePath = folders.xxx + 'helpers\\readme\\' + objRead.name + '.txt';
const readme = _open(readmePath, utf8);
if (readme.length) {fb.ShowPopupMessage(readme, objRead.title);}
});
// Make the user check their tags before use...
if (typeof buttonsBar === 'undefined' && typeof bNotProperties === 'undefined') {
doOnce('findStyleGenresMissingGraphCheck', debounce(findStyleGenresMissingGraphCheck, 500))(sbd.panelProperties);
}
// SMP Bug: https://github.com/TheQwertiest/foo_spider_monkey_panel/issues/205
// Force setting it to true at 30 secs after startup
setTimeout(() => {
if (!sbd.panelProperties.firstPopup[1]) {
sbd.panelProperties.firstPopup[1] = true;
overwriteProperties(sbd.panelProperties);
}
}, 60000);
}
/*
Load additional descriptors: All Music, Last.fm, ...
*/
[
{name: 'All Music', file: 'helpers\\music_graph_descriptors_xxx_allmusic.js', prop: 'bAllMusicDescriptors'},
{name: 'Last.fm', file: 'helpers\\music_graph_descriptors_xxx_lastfm.js', prop: 'bLastfmDescriptors'}
].forEach((descr) => {
if (sbd.panelProperties[descr.prop][1]) {
if (_isFile(folders.xxx + descr.file)) {
if (sbd.panelProperties.bStartLogging[1]) {console.log(descr.name + '\'s music_graph_descriptors - File loaded: ' + folders.xxx + descr.file);}
include('..\\' + descr.file);
}
}
});
/*
Load additional descriptors: All Music, Last.fm, ...
*/
if (sbd.panelProperties.bTagsCache[1]) {
if (typeof tagsCache === 'undefined') {
include('..\\helpers\\helpers_xxx_tags_cache.js');
}
doOnce('Load tags cache', debounce(() => {
tagsCache.load();
}, 5000))();
}
/*
Reuse cache on the same session, from other panels and from json file
*/
// Only use file cache related to current descriptors, otherwise delete it
// if (sbd.panelProperties.bProfile[1]) {var profiler = new FbProfiler('descriptorCRC');}
const descriptorCRC = crc32(JSON.stringify(music_graph_descriptors) + musicGraph.toString() + calcGraphDistance.toString() + calcMeanDistance.toString() + sbd.influenceMethod + 'v1.1.0');
const bMissmatchCRC = sbd.panelProperties.descriptorCRC[1] !== descriptorCRC;
if (bMissmatchCRC) {
if (sbd.panelProperties.descriptorCRC[1] !== -1) { // There may be multiple panels, don't nuke it on first init on a new panel
console.log('Search by Distance: CRC mistmatch. Deleting old json cache.');
_deleteFile(folders.data + 'searchByDistance_cacheLink.json');
_deleteFile(folders.data + 'searchByDistance_cacheLinkSet.json');
}
sbd.panelProperties.descriptorCRC[1] = descriptorCRC;
overwriteProperties(sbd.panelProperties); // Updates panel
}
// if (sbd.panelProperties.bProfile[1]) {profiler.Print();}
// Start cache
var cacheLinkSet;
if (_isFile(folders.data + 'searchByDistance_cacheLink.json')) {
const data = loadCache(folders.data + 'searchByDistance_cacheLink.json');
if (data.size) {cacheLink = data; if (sbd.panelProperties.bStartLogging[1]) {console.log('Search by Distance: Used Cache - cacheLink from file.');}}
}
if (_isFile(folders.data + 'searchByDistance_cacheLinkSet.json')) {
const data = loadCache(folders.data + 'searchByDistance_cacheLinkSet.json');
if (data.size) {cacheLinkSet = data; if (sbd.panelProperties.bStartLogging[1]) {console.log('Search by Distance: Used Cache - cacheLinkSet from file.');}}
}
// Delays cache update after startup (must be called by the button file if it's not done here)
if (typeof buttonsBar === 'undefined' && typeof bNotProperties === 'undefined') {debounce(updateCache, 3000)({properties: sbd.panelProperties});}
// Ask others instances to share cache on startup
if (typeof cacheLink === 'undefined') {
setTimeout(() => {window.NotifyOthers('Search by Distance: requires cacheLink map', true);}, 1000);
}
if (typeof cacheLinkSet === 'undefined') {
setTimeout(() => {window.NotifyOthers('Search by Distance: requires cacheLinkSet map', true);}, 1000);
}
async function updateCache({newCacheLink, newCacheLinkSet, bForce = false, properties = null} = {}) {
if (typeof cacheLink === 'undefined' && !newCacheLink) { // only required if on_notify_data did not fire before
const profiler = sbd.panelProperties.bProfile[1] ? new FbProfiler('updateCache') : null;
if (sbd.panelProperties.bCacheOnStartup[1] || bForce) {
if (sbd.isCalculatingCache) {return;}
sbd.isCalculatingCache = true;
if (typeof buttonsBar !== 'undefined') {
buttonsBar.listKeys.flat(Infinity).filter((key) => {return key.match(/^(?:Search by Distance.*)|(?:Playlist Tools$)/i);})
.forEach((key) => {
buttonsBar.buttons[key].switchAnimation('Link cache', true, () => !sbd.isCalculatingCache);
});
}
const tags = properties && properties.hasOwnProperty('tags') ? JSON.parse(properties.tags[1]) : null;
const genreStyleTags = tags
? Object.values(tags).filter((t) => t.type.includes('graph') && !t.type.includes('virtual')).map((t) => t.tf).flat(Infinity)
.map((tag) => {return tag.indexOf('$') === -1 ? _t(tag): tag;}).join('|')
: _t(globTags.genre) + '|' + _t(globTags.style);
console.log('Search by Distance: tags used for cache - ' + genreStyleTags);
const tfo = fb.TitleFormat(genreStyleTags);
const styleGenres = await new Promise((resolve) => {
const libItems = fb.GetLibraryItems().Convert();
const num = libItems.length;
let tagValues = [];
const promises = [];
let step = 0;
let prevProgress = -1;
// All styles/genres from library without duplicates
for (let i = 0; step < num; i ++) {
promises.push(new Promise((resolve) => {
step += 300;
const items = new FbMetadbHandleList(libItems.slice(i, step));
setTimeout((step) => {
tagValues.push(...new Set(tfo.EvalWithMetadbs(items).join('|').split(/\| *|, */g)));
const progress = Math.floor(step / num * 4) * 25;
if (progress > prevProgress) {prevProgress = progress; console.log('Calculating tags ' + (progress <= 100 ? progress : 100) + '%.');}
resolve('done');
}, iDelayLibrary * 6 * i, step);
}));
}
Promise.all(promises).then(() => {
if (properties && properties.hasOwnProperty('bAscii') && properties.bAscii[1]) {
setTimeout(() => {resolve(new Set([...new Set(tagValues)].map((tag) => {return _asciify(tag);})));}, 500);
} else {
setTimeout(() => {resolve(new Set(tagValues));}, 500);
}
});
});
cacheLink = await calcCacheLinkSGV2(sbd.allMusicGraph, styleGenres, void(0), sbd.influenceMethod);
sbd.isCalculatingCache = false;
} else {
cacheLink = new Map();
}
saveCache(cacheLink, folders.data + 'searchByDistance_cacheLink.json');
if (sbd.panelProperties.bProfile[1]) {profiler.Print();}
console.log('Search by Distance: New Cache - cacheLink');
window.NotifyOthers('Search by Distance: cacheLink map', cacheLink);
} else if (newCacheLink) {
cacheLink = newCacheLink;
}
if (typeof cacheLinkSet === 'undefined' && !newCacheLinkSet) { // only required if on_notify_data did not fire before
cacheLinkSet = new Map();
console.log('Search by Distance: New Cache - cacheLinkSet');
window.NotifyOthers('Search by Distance: cacheLinkSet map', cacheLinkSet);
} else if (newCacheLinkSet) {
cacheLinkSet = newCacheLinkSet;
}
// Multiple Graph testing and logging of results using the existing cache
if (sbd.panelProperties.bSearchDebug[1]) {
doOnce('Test 1',testGraph)(sbd.allMusicGraph);
doOnce('Test 2',testGraphV2)(sbd.allMusicGraph);
}
}
addEventListener('on_notify_data', (name, info) => {
if (name === 'bio_imgChange' || name === 'biographyTags' || name === 'bio_chkTrackRev') {return;}
if (!name.startsWith('Search by Distance')) {return;}
switch (name) {
case 'Search by Distance: requires cacheLink map': { // When asked to share cache, delay 1 sec. to allow script loading
if (typeof cacheLink !== 'undefined' && cacheLink.size) {
debounce(() => {if (typeof cacheLink !== 'undefined') {window.NotifyOthers('Search by Distance: cacheLink map', cacheLink);}}, 1000)();
console.log('Search by Distance: Requested Cache - cacheLink.');
}
break;
}
case 'Search by Distance: requires cacheLinkSet map': { // When asked to share cache, delay 1 sec. to allow script loading
if (typeof cacheLinkSet !== 'undefined' && cacheLinkSet.size) {
debounce(() => {if (typeof cacheLinkSet !== 'undefined') {window.NotifyOthers('Search by Distance: cacheLinkSet map', cacheLinkSet);}}, 1000)();
console.log('Search by Distance: Requested Cache - cacheLinkSet.');
}
break;
}
case 'Search by Distance: cacheLink map': {
if (info) {
console.log('Search by Distance: Used Cache - cacheLink from other panel.');
let data = JSON.parse(JSON.stringify([...info])); // Deep copy
data.forEach((pair) => {if (pair[1].distance === null) {pair[1].distance = Infinity;}}); // stringify converts Infinity to null, this reverts the change
updateCache({newCacheLink: new Map(data)});
}
break;
}
case 'Search by Distance: cacheLinkSet map': {
if (info) {
console.log('Search by Distance: Used Cache - cacheLinkSet from other panel.');
let data = JSON.parse(JSON.stringify([...info])); // Deep copy
data.forEach((pair) => {if (pair[1] === null) {pair[1] = Infinity;}}); // stringify converts Infinity to null, this reverts the change
updateCache({newCacheLinkSet: new Map(data)});
}
break;
}
case 'Search by Distance: requires cacheLink map': {
break;
}
}
});
addEventListener('on_script_unload', () => {
if (sbd.panelProperties.bStartLogging[1]) {console.log('Search by Distance: Saving Cache.');}
if (cacheLink) {saveCache(cacheLink, folders.data + 'searchByDistance_cacheLink.json');}
if (cacheLinkSet) {saveCache(cacheLinkSet, folders.data + 'searchByDistance_cacheLinkSet.json');}
// SMP Bug: https://github.com/TheQwertiest/foo_spider_monkey_panel/issues/205
// if (!sbd.panelProperties.firstPopup[1]) {
// sbd.panelProperties.firstPopup[1] = true;
// overwriteProperties(sbd.panelProperties); // Updates panel
// }
// console.flush();
});
/*
Warnings about links/nodes set wrong
*/
if (sbd.panelProperties.bGraphDebug[1]) {
const profiler = sbd.panelProperties.bProfile[1] ? new FbProfiler('graphDebug') : null;
graphDebug(sbd.allMusicGraph);
if (sbd.panelProperties.bProfile[1]) {profiler.Print();}
}
/*
Variables allowed at recipe files and automatic documentation update
*/
const recipeAllowedKeys = new Set(['name', 'properties', 'theme', 'recipe', 'tags', 'bNegativeWeighting', 'bFilterWithGraph', 'forcedQuery', 'bSameArtistFilter', 'bConditionAntiInfluences', 'bUseAntiInfluencesFilter', 'bUseInfluencesFilter', 'bSimilArtistsFilter', 'method', 'scoreFilter', 'minScoreFilter', 'graphDistance', 'poolFilteringTag', 'poolFilteringN', 'bPoolFiltering', 'bRandomPick', 'probPick', 'playlistLength', 'bSortRandom', 'bProgressiveListOrder', 'bScatterInstrumentals', 'bSmartShuffle', 'bInKeyMixingPlaylist', 'bProgressiveListCreation', 'progressiveListCreationN', 'playlistName', 'bProfile', 'bShowQuery', 'bShowFinalSelection', 'bBasicLogging', 'bSearchDebug', 'bCreatePlaylist', 'bAscii', 'bAdvTitle']);
const recipePropertiesAllowedKeys = new Set(['smartShuffleTag']);
const themePath = folders.xxx + 'presets\\Search by\\themes\\';
const recipePath = folders.xxx + 'presets\\Search by\\recipes\\';
if (!_isFile(folders.xxx + 'presets\\Search by\\recipes\\allowedKeys.txt') || bMissmatchCRC) {
const data = [...recipeAllowedKeys].map((key) => {
const propDescr = SearchByDistance_properties[key] || SearchByDistance_panelProperties[key];
let descr = propDescr ? propDescr[0] : '';
if (!descr.length) {
if (key.toLowerCase().indexOf('properties') !== -1) {
descr = {'Object properties to pass other arguments':
Object.fromEntries([...recipePropertiesAllowedKeys].map((key) => {return [key, (SearchByDistance_properties[key] || SearchByDistance_panelProperties[key])[0]];}))
};
}
if (key === 'name') {descr = 'Preset name (instead of filename)';}
if (key === 'theme') {descr = 'Load additional theme by file name or path';}
if (key === 'recipe') {descr = 'Load additional recipe(s) by file name or path. Nesting and multiple values (array) allowed';}
if (key === 'bPoolFiltering') {descr = 'Global enable/disable switch. Equivalent to setting poolFilteringN to >0 or -1';}
if (key === 'bCreatePlaylist') {descr = 'Output results to a playlist or only for internal use';}
}
return [key, descr];
});
if (sbd.panelProperties.bStartLogging[1]) {console.log('Updating recipes documentation at: ' + folders.xxx + 'presets\\Search by\\recipes\\allowedKeys.txt');}
_save(folders.xxx + 'presets\\Search by\\recipes\\allowedKeys.txt', JSON.stringify(Object.fromEntries(data), null, '\t'));
}
function testRecipe({path = null, json = null, baseTags = null} = {}) {
const result = {valid: true , report: []};
let recipe;
if (!path && !json) {result.valid = false; result.report.push('No recipe provided.'); return result;}
if (!baseTags) {result.valid = false; result.report.push('No tags provided.'); return result;}
else if (path) {
if (_isFile(path)) {
recipe = _jsonParseFileCheck(path, 'Recipe json', 'Search by Distance', utf8);
} else {result.valid = false; result.report.push('Recipe file not found.'); return result;}
} else {recipe = clone(json);}
if (Object.keys(recipe).length === 0) {result.valid = false; result.report.push('Recipe is empty.'); return result;}
// Process nested recipes
if (recipe.hasOwnProperty('recipe')) {
const toAdd = processRecipe(recipe.recipe);
delete toAdd.recipe;
Object.keys(toAdd).forEach((key) => {
if (!recipe.hasOwnProperty(key)) {
recipe[key] = toAdd[key];
} else if (key === 'tags') {
for (let key in toAdd.tags) {
if (!recipe.tags.hasOwnProperty(key)) {
recipe.tags[key] = toAdd.tags[key];
} else {
for (let subKey in toAdd.tags[key]) {
if (!recipe.tags[key].hasOwnProperty(subKey)) {
recipe.tags[key][subKey] = toAdd.tags[key][subKey];
}
}
}
}
}
});
}
const tags = recipe.hasOwnProperty('tags') ? recipe.tags : null;
// Process placeholders for tags
if (tags) {
if (recipe.tags.hasOwnProperty('*')) {
for (let key in tags) {
for (let prop in tags['*']) {
if (!tags[key].hasOwnProperty(prop)) {tags[key][prop] = tags['*'][prop];}
}
}
}
}
// Test
for (let key in recipe) {
if (!recipeAllowedKeys.has(key)) {
result.valid = false;
result.report.push('Recipe contains non valid key: ' + key);
}
}
const validVarTypes = ['string', 'number'];
const validValTypes = ['multiple', 'single'];
const checkKeys = ['weight', 'tf', 'baseScore', 'scoringDistribution'];
const validTagKeys = ['range', 'type', 'combs', ...checkKeys];
for (let key in tags) {
if (key === '*') {continue;}
const tag = baseTags.hasOwnProperty(key) ? {...clone(baseTags[key]), ...tags[key]} : tags[key];
// Type
if (!tag.hasOwnProperty('type') || tag.type.length === 0) {
result.valid = false;
result.report.push('Tag missing type declaration: ' + key);
} else {
if (!validVarTypes.some((t) => tag.type.includes(t))) {
result.valid = false;
result.report.push('Tag missing variable type ' + _p(validVarTypes.join(', ')) + ': ' + key);
}
if (!validValTypes.some((t) => tag.type.includes(t))) {
result.valid = false;
result.report.push('Tag missing multi-value type ' + _p(validValTypes.join(', ')) + ': ' + key);
}
// Range
const rangeRegx = /-*range/i;
if (tag.hasOwnProperty('range') && !tag.type.some((t) => rangeRegx.test(t))) {
result.valid = false;
result.report.push('Tag missing range type: ' + key);
} else if (tag.type.some((t) => rangeRegx.test(t)) && !tag.hasOwnProperty('range')) {
result.valid = false;
result.report.push('Tag missing range property: ' + key);
}
}
// General keys
for (let check of checkKeys) {
if (!tag.hasOwnProperty(check)) {
result.valid = false;
result.report.push('Tag missing property ' + _p(check) + ': ' + key);
}
}
for (let check in tag) {
if (!validTagKeys.includes(check)) {
result.valid = false;
result.report.push('Tag contains non valid property ' + _p(check) + ': ' + key);
}
}
}
if (!result.valid) {result.report.splice(0, 0, 'Recipe non valid: ' + recipe.name + (path ? '\n' + path : '') + '\n');}
return result;
}
// 1900 ms 24K tracks GRAPH all default on i7 920 from 2008
// 3144 ms 46K tracks DYNGENRE all default on i7 920 from 2008
async function searchByDistance({
// --->Default args (aka properties from the panel and input)
properties = getPropertiesPairs(SearchByDistance_properties, sbd_prefix),
panelProperties = (typeof buttonsBar === 'undefined') ? properties : getPropertiesPairs(SearchByDistance_panelProperties, sbd_prefix),
sel = fb.GetFocusItem(), // Reference track, first item of act. pls. if can't get focus item
theme = {}, // May be a file path or object with Arr of tags {name, tags: [{genre, style, mood, key, date, bpm, composer, customStr, customNum}]}
recipe = {}, // May be a file path or object with Arr of arguments {genreWeight, styleWeight, ...}
// --->Args modifiers
bAscii = properties.hasOwnProperty('bAscii') ? properties.bAscii[1] : true, // Sanitize all tag values with ASCII equivalent chars
bTagsCache = panelProperties.hasOwnProperty('bTagsCache') ? panelProperties.bTagsCache[1] : false, // Read from cache
bAdvTitle = properties.hasOwnProperty('bAdvTitle') ? properties.bAdvTitle[1] : true, // RegExp duplicate matching,
checkDuplicatesByTag = properties.hasOwnProperty('checkDuplicatesByTag') ? JSON.parse(properties.checkDuplicatesByTag[1]) : globTags.remDupl,
// --->Weights
tags = properties.hasOwnProperty('tags') ? JSON.parse(properties.tags[1]) : null,
bNegativeWeighting = properties.hasOwnProperty('bNegativeWeighting') ? properties.bNegativeWeighting[1] : true, // Assigns negative score for num. tags when they fall outside range
bFilterWithGraph = properties.hasOwnProperty('bFilterWithGraph') ? properties.bFilterWithGraph[1] : false, // Filter graph search with valid values (slow)
// --->Pre-Scoring Filters
// Query to filter library
forcedQuery = properties.hasOwnProperty('forcedQuery') ? properties.forcedQuery[1] : '',
// Exclude same artist
bSameArtistFilter = properties.hasOwnProperty('bSameArtistFilter') ? properties.bSameArtistFilter[1] : false,
// Similar artists
bSimilArtistsFilter = properties.hasOwnProperty('bSimilArtistsFilter') ? properties.bSimilArtistsFilter[1] : false,
// Filter anti-influences by query, before any scoring/distance calc.
bConditionAntiInfluences= properties.hasOwnProperty('bConditionAntiInfluences') ? properties.bConditionAntiInfluences[1] : false, // Only for specific style/genres (for ex. Jazz)
bUseAntiInfluencesFilter= !bConditionAntiInfluences && properties.hasOwnProperty('bUseAntiInfluencesFilter') ? properties.bUseAntiInfluencesFilter[1] : false,
// Allows only influences by query, before any scoring/distance calc.
bUseInfluencesFilter = properties.hasOwnProperty('bUseInfluencesFilter') ? properties.bUseInfluencesFilter[1] : false,
// --->Scoring Method
method = properties.hasOwnProperty('method') ? properties.method[1] : 'GRAPH',
// --->Scoring filters
scoreFilter = properties.hasOwnProperty('scoreFilter') ? Number(properties.scoreFilter[1]) : 75,
minScoreFilter = properties.hasOwnProperty('minScoreFilter') ? Number(properties.minScoreFilter[1]) : scoreFilter - 10,
graphDistance = properties.hasOwnProperty('graphDistance') ? (isString(properties.graphDistance[1]) ? properties.graphDistance[1] : Number(properties.graphDistance[1])) : Infinity,
// --->Post-Scoring Filters
// Allows only N +1 tracks per tag set... like only 2 tracks per artist, etc.
poolFilteringTag = properties.hasOwnProperty('poolFilteringTag') ? JSON.parse(properties.poolFilteringTag[1]).filter(Boolean) : [],
poolFilteringN = properties.hasOwnProperty('poolFilteringN') ? Number(properties.poolFilteringN[1]) : -1,
bPoolFiltering = poolFilteringN >= 0 && poolFilteringN < Infinity ? true : false,
// --->Playlist selection
// How tracks are chosen from pool
bRandomPick = properties.hasOwnProperty('bRandomPick') ? properties.bRandomPick[1] : false, // Get randomly
probPick = properties.hasOwnProperty('probPick') ? Number(properties.probPick[1]) : 100, // Get by scoring order but with x probability of being chosen
playlistLength = properties.hasOwnProperty('playlistLength') ? Number(properties.playlistLength[1]) : 50, // Max playlist size
// --->Playlist sorting
// How playlist is sorted (independently of playlist selection)
bSortRandom = properties.hasOwnProperty('bSortRandom') ? properties.bSortRandom[1] : false, // Random sorting
bProgressiveListOrder = properties.hasOwnProperty('bProgressiveListOrder') ? properties.bProgressiveListOrder[1] : false, // Sorting following progressive changes on tags (score)
bScatterInstrumentals = properties.hasOwnProperty('bScatterInstrumentals') ? properties.bScatterInstrumentals[1] : false, // Intercalate instrumental tracks breaking clusters if possible
bSmartShuffle = properties.hasOwnProperty('bSmartShuffle') ? properties.bSmartShuffle[1] : false, // Spotify's smart shuffle by artist
// --->Special Playlists
// Use previous playlist selection, but override playlist sorting, since they use their own logic
bInKeyMixingPlaylist = properties.hasOwnProperty('bInKeyMixingPlaylist') ? properties.bInKeyMixingPlaylist[1] : false, // Key changes following harmonic mixing rules like a DJ
bHarmonicMixDoublePass = properties.hasOwnProperty('bHarmonicMixDoublePass') ? properties.bHarmonicMixDoublePass[1] : false, // Usually outputs more tracks in harmonic mixing
bProgressiveListCreation= properties.hasOwnProperty('bProgressiveListCreation') ? properties.bProgressiveListCreation[1] : false, // Uses output tracks as new references, and so on...
progressiveListCreationN= bProgressiveListCreation ? Number(properties.progressiveListCreationN[1]) : 1, // > 1 and < 100
// --->Console logging
// Uses panelProperties instead of properties, so it always points to the right properties... used along buttons or not.
// They are the same for all instances within the same panel
bProfile = panelProperties.hasOwnProperty('bProfile') ? panelProperties.bProfile[1] : false,
bShowQuery = panelProperties.hasOwnProperty('bShowQuery') ? panelProperties.bShowQuery[1] : true,
bShowFinalSelection = panelProperties.hasOwnProperty('bShowFinalSelection') ? panelProperties.bShowFinalSelection[1] : true,
bBasicLogging = panelProperties.hasOwnProperty('bBasicLogging') ? panelProperties.bBasicLogging[1] : false,
bSearchDebug = panelProperties.hasOwnProperty('bSearchDebug') ? panelProperties.bSearchDebug[1] : false,
// --->Output
playlistName = properties.hasOwnProperty('playlistName') ? properties.playlistName[1] : 'Search...',
bCreatePlaylist = true, // false: only outputs handle list. To be used along other scripts and/or recursive calls
// --->Misc
parent = null
} = {}) {
const descr = music_graph_descriptors;
const oldCacheLinkSize = cacheLink ? cacheLink.size : 0;
const oldCacheLinkSetSize = cacheLinkSet ? cacheLinkSet.size : 0;
// Tags check
if (!tags || Object.keys(tags).length === 0) {console.popup('No tags provided: ' + tags +'\nRestore defaults to fix it.', 'Search by distance'); return;}
// Recipe check
const bUseRecipe = !!(recipe && (typeof recipe === 'string' && recipe.length || Object.keys(recipe).length));
const recipeProperties = {};
if (bUseRecipe) {
let path;
if (isString(recipe)) { // File path
path = !_isFile(recipe) && _isFile(recipePath + recipe) ? recipePath + recipe : recipe;
recipe = _jsonParseFileCheck(path, 'Recipe json', 'Search by Distance', utf8);
if (!recipe) {console.popup('Recipe not found: ' + path, 'Search by distance'); return;}
}
// Check recipe but don't crash
const result = testRecipe({json: recipe, baseTags: tags});
if (!result.valid) {console.popup(result.report.join('\n\t- '), 'Recipe error');}
// Rewrite args or use destruct when passing args
// Sel is omitted since it's a function or a handle
// Note a theme may be set within a recipe too, overwriting any other theme set
// Changes null to infinity and not found theme filenames into full paths
let bOverwriteTheme = false;
if (recipe.hasOwnProperty('recipe')) { // Process nested recipes
let toAdd = processRecipe(recipe.recipe);
delete toAdd.recipe;
Object.keys(toAdd).forEach((key) => {
if (!recipe.hasOwnProperty(key)) {
recipe[key] = toAdd[key];
} else if (key === 'tags') {
for (let key in toAdd.tags) {
if (!recipe.tags.hasOwnProperty(key)) {
recipe.tags[key] = toAdd.tags[key];
} else {
for (let subKey in toAdd.tags[key]) {
if (!recipe.tags[key].hasOwnProperty(subKey)) {
recipe.tags[key][subKey] = toAdd.tags[key][subKey];
}
}
}
}
}
});
}
if (bSearchDebug) {console.log(recipe);}
Object.keys(recipe).forEach((key) => { // Process current recipe
const value = recipe[key] !== null ? recipe[key] : Infinity;
if (recipeAllowedKeys.has(key)) {
if (key === 'name') {
return;
} else if (key === 'recipe') {
return; // Skip, already processed
} else if (key === 'properties') { // Overrule current ones (but don't touch original object!)
const newProperties = recipe[key];
if (newProperties) {
Object.keys(newProperties).forEach((rKey) => {
if (!properties.hasOwnProperty(rKey)) {console.log('Recipe has a property key not recognized: ' + rKey); return;}
recipeProperties[rKey] = newProperties[rKey];
});
}
} else if (key === 'tags') { // Overrule current ones (but don't touch original object!)
recipeProperties.tags = recipe.tags;
} else {
if (isStringWeak(value)) {
eval(key + ' = \'' + value + '\'');
} else if (isArrayStrings(value)) {
const newVal = '\'' + value.join('\',\'') + '\'';
eval(key + ' = [' + newVal + ']');
} else if (typeof value === 'object') {
const newVal = JSON.stringify(value);
eval(key + ' = ' + newVal );
} else {
eval(key + ' = ' + value);
}
if (key === 'theme') {bOverwriteTheme = true;}
if (bSearchDebug) {console.log(key, value, eval(key));}
}
} else {console.log('Recipe has a variable not recognized: ' + key);}
});
// Process placeholders for tags
if (recipe.hasOwnProperty('tags') && recipe.tags.hasOwnProperty('*')) {
for (let key in recipe.tags) { // Recipe's tags missing some property
for (let prop in recipe.tags['*']) {
if (!recipe.tags[key].hasOwnProperty(prop)) {recipe.tags[key][prop] = recipe.tags['*'][prop];}
}
}
for (let key in tags) { // Base tags not on recipe
if (!recipe.tags.hasOwnProperty(key)) {recipe.tags[key] = recipe.tags['*'];}
}
}
if (bBasicLogging) {
const name = recipe.hasOwnProperty('name') ? recipe.name : (path ? utils.SplitFilePath(path)[1] : '-no name-');
console.log('Using recipe as config: ' + name + (path ? ' (' + path + ')' : ''));
if (bOverwriteTheme) {console.log('Recipe forces its own theme.');}
}
}
const bUseRecipeTags = !!(bUseRecipe && recipeProperties.hasOwnProperty('tags'));
// Parse args
graphDistance = parseGraphDistance(graphDistance, descr, bBasicLogging);
if (graphDistance === null) {return;}
// Theme check
const bUseTheme = !!(theme && (typeof recipe === 'string' && theme.length || Object.keys(theme).length));
if (bUseTheme) {
let path;
if (isString(theme)) { // File path: try to use plain path or themes folder + filename
path = !_isFile(theme) && _isFile(themePath + theme) ? themePath + theme : theme;
theme = _jsonParseFileCheck(path, 'Theme json', 'Search by Distance', utf8);
if (!theme) {return;}
}
// Array of objects
const tagsToCheck = Object.keys(tags).filter((k) => !tags[k].type.includes('virtual'));
// Theme tags must contain at least all the user tags
const tagCheck = theme.hasOwnProperty('tags') ? theme.tags.findIndex((tagArr) => {return !new Set(Object.keys(tagArr)).isSuperset(new Set(tagsToCheck));}) : 0;
const bCheck = theme.hasOwnProperty('name') && tagCheck === -1;
if (!bCheck) {
console.log('Theme selected for mix is missing some keys: ' + (theme.hasOwnProperty('name') ? [...new Set(tagsToCheck).difference(new Set(Object.keys(theme.tags[tagCheck])))] : 'name'));
return;
}
if (bBasicLogging) {
console.log('Using theme as reference: ' + theme.name + (path ? ' (' + path + ')' : ''));
console.log(theme);
}
}
// Sel check
if (!bUseTheme) {
if (!sel) {
console.log('No track\\theme selected for mix.');
return;
}
if (bBasicLogging) {
console.log('Using selection as reference: ' + fb.TitleFormat('[%TRACK% - ]%TITLE%').EvalWithMetadb(sel) + ' (' + sel.RawPath + ')');
}
}
// Method check
if (!checkMethod(method)) {console.popup('Method not recognized: ' + method +'\nOnly allowed GRAPH, DYNGENRE or WEIGHT.', 'Search by distance'); return;}
// Start calcs
const test = bProfile ? new FbProfiler('Search by Distance') : null;
// Copy recipe tags
if (bUseRecipeTags) {
for (let key in recipeProperties.tags) {
if (!tags.hasOwnProperty(key) && key !== '*') {
tags[key] = recipeProperties.tags[key];
}
}
}
// May be more than one tag so we use split(). Use filter() to remove '' values. For ex:
// styleTag: 'tagName,, ,tagName2' => ['tagName','Tagname2']
// We check if weights are zero first
const calcTags = {genreStyle: {weight: 0, tf: [], baseScore: 0, type: ['virtual']}};
for (let key in tags) {
const tag = tags[key];
// Set base values
const calcTag = {weight: tag.weight || 0, tf: [], scoringDistribution: tag.scoringDistribution || 'LINEAR', baseScore: tag.baseScore || 0, type: [...tag.type], range: tag.range || 0, combs: tag.combs || 0};
// Overwrite with properties
if (bUseRecipeTags && recipeProperties.tags.hasOwnProperty(key)) {
Object.keys(recipeProperties.tags[key]).filter((k) => k !== 'tf').forEach((k) => {
calcTag[k] = recipeProperties.tags[key][k];
});
}
// Get proper TF
const type = tag.type;
if (tag.weight !== 0 || (type.includes('graph') && (method === 'DYNGENRE' || method === 'GRAPH')) || (type.includes('keyMix') && bInKeyMixingPlaylist)) {
calcTag.tf = (bUseRecipeTags && recipeProperties.tags.hasOwnProperty(key) ? (recipeProperties.tags[key].tf || tag.tf) : tag.tf).filter(Boolean);
if (type.includes('graph')) {calcTags.genreStyle.tf.push(...calcTag.tf);}
}
calcTags[key] = calcTag;
// Safety Check. Warn users if they try wrong settings
if (type.includes('single') && calcTag.tf.length > 1) {
console.popup('Check \'tags\' value (' + calcTag.tf + '), for tag ' + key + '. Must be only one tag name!.');
return;
}
}
if (bSearchDebug) {console.log(JSON.stringify(calcTags, void(0), '\t'));}
const smartShuffleTag = JSON.parse(recipeProperties.smartShuffleTag || properties.smartShuffleTag[1]).filter(Boolean);
const genreStyleTag = [...new Set(calcTags.genreStyle.tf)].map((tag) => {return (tag.indexOf('$') === -1 ? _t(tag) : tag);});
const genreStyleTagQuery = genreStyleTag.map((tag) => {return (tag.indexOf('$') === -1 ? tag : _q(tag));});
// Check input
playlistLength = (playlistLength >= 0) ? playlistLength : 0;
probPick = (probPick <= 100 && probPick > 0) ? probPick : 100;
scoreFilter = (scoreFilter <= 100 && scoreFilter >= 0) ? scoreFilter : 100;
minScoreFilter = (minScoreFilter <= scoreFilter && minScoreFilter >= 0) ? minScoreFilter : scoreFilter;
bPoolFiltering = bPoolFiltering && (poolFilteringN >= 0 && poolFilteringN < Infinity) ? true : false;
if (bPoolFiltering && (!poolFilteringTag || !poolFilteringTag.length || !isArrayStrings(poolFilteringTag))) {
console.popup('Warning: Tags for pool filtering are not set or have an invalid value:\n' + poolFilteringTag, 'Search by distance');
return;
}
if (bSmartShuffle && !smartShuffleTag || !smartShuffleTag.length) {
console.popup('Warning: Smart Shuffle Tag is not set or has an invalid value:\n' + smartShuffleTag, 'Search by distance');
return;
}
if (bProgressiveListCreation && !checkDuplicatesByTag || !checkDuplicatesByTag.length) {
console.popup('Warning: Recursive playlist creation is enabled, but no tags for duplicates removal are provided.', 'Search by distance');
return;
}
// Can not use those methods without genre/style tags at all
if (genreStyleTag.length === 0 && (method === 'GRAPH' || method === 'DYNGENRE')) {
if (bBasicLogging) {
console.log('Check \'genre\' and \'style\' tags. Both can not be empty when using GRAPH or DYNGENRE methods.');
}
return;
}
// Zero weights if there are no tag names to look for
for (let key in calcTags) {
const tag = calcTags[key];
if (tag.type.includes('virtual')) {continue;}
if (tag.tf.length === 0) {
tag.weight = 0;
if (tag.type.includes('keyMix')) {bInKeyMixingPlaylist = false;}
}
}
if (method === 'DYNGENRE') { // Warn users if they try wrong settings
if (calcTags.dynGenre.weight === 0) {
if (bBasicLogging) {console.log('Check \'dynGenre\' weight value (' + calcTags.dynGenre.weight + '). Must be greater than zero if you want to use DYNGENRE method!.');}
return;
} else {method = 'WEIGHT';} // For calcs they are the same!
} else {calcTags.dynGenre.weight = 0;}
const totalWeight = Object.keys(calcTags).reduce((total, key) => {return total + calcTags[key].weight}, 0); //100%
const countWeights = Object.keys(calcTags).reduce((total, key) => {return (total + (calcTags[key].weight !== 0 ? 1 : 0));}, 0);
if (!playlistLength) {
if (bBasicLogging) {console.log('Check \'Playlist Mix length\' value (' + playlistLength + '). Must be greater than zero.');}
return;
}
if (!totalWeight && method === 'WEIGHT') {
if (bBasicLogging) {
if (calcTags.dynGenre.weight !== 0) {console.log('Check weight values, all are set to zero and \'dynGenre\' weight is not used for WEIGHT method.');}
else {console.log('Check weight values, all are set to zero.');}
}
return;
}
try {fb.GetQueryItems(new FbMetadbHandleList(), forcedQuery);} // Sanity check
catch (e) {fb.ShowPopupMessage('Query not valid, check forced query:\n' + forcedQuery); return;}
// Query
let query = [];
let queryl = 0;
// These should be music characteristics not genre/styles. Like 'electric blues' o 'acoustic', which could apply to any blues style... those things are not connected by graph, but considered only for weight scoring instead.
const graphExclusions = descr.map_distance_exclusions; // Set
// Tag filtering: applied globally. Matched values omitted on both calcs, graph and scoring..
// Add '' value to set so we also apply a ~boolean filter when evaluating. Since we are using the filter on string tags, it's good enough.
// It's faster than applying array.filter(Boolean).filter(genreStyleFilterTag)
const genreStyleFilter = new Set(JSON.parse(properties['genreStyleFilterTag'][1]).concat(''));
const bTagFilter = !genreStyleFilter.isEqual(new Set([''])) ? true : false; // Only use filter when required
// Get the tag value. Skip those with weight 0 and get num of values per tag right (they may be arrays, single values, etc.)
// We use flat since it's only 1 track: genre[0][i] === genre.flat()[i]
// Also filter using boolean to remove '' values within an array, so [''] becomes [] with 0 length.
// Using only boolean filter it's 3x faster than filtering by set
const selHandleList = bUseTheme ? null : new FbMetadbHandleList(sel);
for (let key in calcTags) {
const tag = calcTags[key];
tag.reference = [];
if (tag.type.includes('virtual')) {continue;}
if (tag.weight !== 0 || (tag.tf.length && (tag.type.includes('graph') && (tags.dynGenre.weight !== 0 || method === 'GRAPH')) || (tag.type.includes('keyMix') && bInKeyMixingPlaylist))) {
tag.reference = (bUseTheme ? theme.tags[0][key] : getTagsValuesV3(selHandleList, tag.tf, true).flat()).filter(bTagFilter ? (tag) => !genreStyleFilter.has(tag) : Boolean);
}
if (tag.type.includes('single')) {
if (tag.type.includes('string')) {
tag.reference = tag.reference[0] || '';
} else if (tag.type.includes('number')) {
tag.reference = Number(tag.reference[0]) || null;
}
}
if (tag.type.includes('string')) {
if (tag.type.includes('multiple')) {
if (tag.reference.length && bAscii) {tag.reference.forEach((val, i) => {tag.reference[i] = _asciify(val);});}
tag.referenceSet = new Set(tag.reference);
tag.referenceNumber = tag.referenceSet.size;
} else {
if (tag.reference.length && bAscii) {tag.reference = _asciify(tag.reference);}
}
}
}
// Sets for later comparison
if (method === 'GRAPH' || calcTags.dynGenre.weight !== 0) {
calcTags.genreStyle.referenceSet = new Set(calcTags.genre.reference.concat(calcTags.style.reference)).difference(graphExclusions); // Remove exclusions
calcTags.genreStyle.referenceNumber = calcTags.genreStyle.referenceSet.size;
}
let originalWeightValue = 0;
// Queries and ranges
const sortedByCombs = Object.keys(calcTags)
.sort((a, b) => (calcTags[a].type.includes('combinations') ? 1 : 0) - (calcTags[b].type.includes('combinations') ? 1 : 0));
for (let key of sortedByCombs) {
const tag = calcTags[key];
const type = tag.type;
if (tag.weight === 0 || tag.tf.length === 0) {continue;}
if (type.includes('virtual')) {continue;}
if ((type.includes('multiple') && tag.referenceNumber !== 0) || (type.includes('single') && (type.includes('string') && tag.tf.length || tag.reference !== null))) {
originalWeightValue += tag.weight;
if (tag.weight / totalWeight >= totalWeight / countWeights / 100) {
queryl = query.length;
const tagNameTF = type.includes('multiple') // May be a tag or a function...
? tag.tf.map((t) => {return ((t.indexOf('$') === -1) ? t : _q(t));})
: ((tag.tf[0].indexOf('$') === -1) ? tag.tf[0] : _q(tag.tf[0]));
if (type.includes('keyRange')) {
const camelotKey = camelotWheel.getKeyNotationObjectCamelot(tag.reference);
if (camelotKey) {
let keyComb = [];
const keysInRange = camelotWheel.createRange(camelotKey, tag.range, {name: ['flat', 'sharp', 'open', 'camelot'], bFlat: false});
keysInRange.forEach((keyArr) => {
let subKeyComb = [];
keyArr.forEach((keyVal) => {
subKeyComb.push(tagNameTF + ' IS ' + keyVal);
});
keyComb.push(query_join(subKeyComb, 'OR'));
});
// And combinate queries
if (keyComb.length !== 0) {query[queryl] = query_join(keyComb, 'OR');}
} else {query[queryl] = tagNameTF + ' IS ' + tag.reference;} // For non-standard notations just use simple matching
} else if (type.includes('percentRange')) {
const rangeUpper = round(tag.reference * (100 + tag.range) / 100, 0);
const rangeLower = round(tag.reference * (100 - tag.range) / 100, 0);
if (rangeUpper !== rangeLower) {query[queryl] = tagNameTF + ' GREATER ' + rangeLower + ' AND ' + tagNameTF + ' LESS ' + rangeUpper;}
else {query[queryl] += tagNameTF + ' EQUAL ' + tag.reference;}
} else if (type.includes('absRange')) {
const rangeUpper = tag.reference + tag.range;
const rangeLower = tag.reference - tag.range;
if (rangeUpper !== rangeLower) {query[queryl] = tagNameTF + ' GREATER ' + rangeLower + ' AND ' + tagNameTF + ' LESS ' + rangeUpper;}
else {query[queryl] += tagNameTF + ' EQUAL ' + tag.reference;}
} else if (type.includes('combinations')) {
const k = tag.referenceNumber >= tag.combs ? tag.combs : tag.referenceNumber; //on combinations of k
const tagComb = k_combinations(tag.reference, k);
const match = tagNameTF.some((tag) => {return tag.indexOf('$') !== -1}) ? 'HAS' : 'IS'; // Allow partial matches when using funcs
// Group as small as possible for query purposes
const tagCombSet = tagComb.map((a) => new Set(a));
let groups = [];
tagCombSet.forEach((s, i) => {
let bDone = false;
groups.forEach((sg, j) => {
const intersection = sg.base.intersection(s);
if (sg.base.size === s.size && intersection.size === sg.base.size - 1 || sg.base.size === s.size - 1 && intersection.size === sg.base.size) {
if (sg.base.size === s.size) {
sg.or.add(...sg.base.difference(intersection));
sg.base = intersection;
}
sg.or.add(...s.difference(intersection));
bDone = true;
}
});
if (!bDone) {groups.push({base: s, or: new Set()});}
});
groups = groups.map((o) => {return {base: [...o.base], or: [...o.or]};});
groups = groups.map((o) => {
return (o.or.length
? query_join(query_combinations(o.base, tagNameTF, 'AND').concat(query_combinations(o.or, tagNameTF, 'OR')), 'AND')
: void(0)
);
}).filter(Boolean);
query[queryl] = query_join(groups, 'OR');
// const match = tagNameTF.some((tag) => {return tag.indexOf('$') !== -1}) ? 'HAS' : 'IS'; // Allow partial matches when using funcs
// if (tagNameTF.length > 1) {query[queryl] = query_join(query_combinations(tagComb, tagNameTF, 'OR', 'AND', void(0), match), 'OR');}
// else {query[queryl] = query_combinations(tagComb, tagNameTF, 'OR', 'AND');}
} else {
const match = tagNameTF.some((tag) => {return tag.indexOf('$') !== -1}) ? 'HAS' : 'IS'; // Allow partial matches when using funcs
if (tagNameTF.length > 1) {query[queryl] = query_join(query_combinations(tag.reference, tagNameTF, 'OR', void(0), match), 'OR');}
else {query[queryl] = query_combinations(tag.reference, tagNameTF, 'OR');}
}
}
} else if (tag.weight !== 0 && bBasicLogging) {console.log('Weight was not zero but selected track had no ' + key + ' tags');}
}
// Dyngenre virtual tag is calculated with previous values
if (calcTags.genreStyle.referenceSize !== 0 && calcTags.dynGenre.weight !== 0) {
for (const genreStyle in calcTags.genreStyle.referenceSet) {
const dynGenre = sbd.genreStyleMap.get(genreStyle);
if (dynGenre) {calcTags.dynGenre.reference.push(...dynGenre);}
}
calcTags.dynGenre.referenceNumber = calcTags.dynGenre.reference.length;
if (calcTags.dynGenre.referenceNumber !== 0) {
originalWeightValue += calcTags.dynGenre.weight;
}
} else if (calcTags.dynGenre.weight !== 0 && bBasicLogging) {console.log('\'dynGenre\' weight was not zero but selected track had no style nor genre tags');}
// Total score
const originalScore = (originalWeightValue * 100) / totalWeight; // if it has tags missing then original Distance != totalWeight
if (bProfile) {test.Print('Task #1: Reference track / theme', false);}
// Create final query
// Pre filtering by query greatly speeds up the next part (weight and graph distance calcs), but it requires variable queries according to the weights.
// i.e. if genreWeight is set too high, then only same genre tracks would pass the later score/distance filter...
// But having the same values for other tags could make the track pass to the final pool too, specially for Graph method.
// So a variable pre-filter would be needed, calculated according to the input weight values and -estimated- later filters scoring.
// Also an input track missing some tags could break the pre-filter logic if not adjusted.
queryl = query.length;
if (queryl === 0) {
if (!originalScore) {
console.log('No query available for selected track. Probably missing tags!');
return;
} else {query[queryl] = '';} // Pre-Filter may not be relevant according to weights...
}
const querylength = query.length;
if (method === 'WEIGHT' && calcTags.dynGenre.weight === 0) { // Weight method. Pre-filtering is really simple...
if (querylength === 1 && !query[0].length) {query[querylength] = '';}
else {query[querylength] = query_join(query, 'OR');} //join previous query's
} else if (method === 'WEIGHT' && calcTags.dynGenre.weight !== 0) { //Dyngenre method.
if (querylength === 1 && !query[0].length) {query[querylength] = '';}
else {query[querylength] = query_join(query, 'OR');} //join previous query's
} else { // Graph Method
let influencesQuery = [];
if (bUseAntiInfluencesFilter || bConditionAntiInfluences) { // Removes anti-influences using queries
let influences = [];