-
Notifications
You must be signed in to change notification settings - Fork 1
/
ztm.py
6037 lines (4932 loc) · 262 KB
/
ztm.py
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 argparse
from collections import OrderedDict
import csv
import os
from os.path import exists, dirname
import re
import sqlite3
import sys
import time
import uuid
import pandas as pd
import numpy as np
from string_grouper import match_strings, match_most_similar, \
group_similar_strings, compute_pairwise_similarities, \
StringGrouper
''' function to clear screen '''
cls = lambda: os.system('clear')
def firstlettercaps(s):
''' returns first letter caps for each word but respects apostrophes '''
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
def us_state(s):
return s.upper() in ['AL',
'AK',
'AZ',
'AR',
'CA',
'CZ',
'CO',
'CT',
'DE',
'DC',
'FL',
'GA',
'GU',
'HI',
'ID',
'IL',
'IN',
'IA',
'KS',
'KY',
'LA',
# 'ME',
'MD',
'MA',
'MI',
'MN',
'MS',
'MO',
'MT',
'NE',
'NV',
'NH',
'NJ',
'NM',
'NY',
'NC',
'ND',
'OH',
'OK',
'OR',
'PA',
'PR',
'RI',
'SC',
'SD',
'TN',
'TX',
'UT',
'VT',
'VI',
'VA',
'WA',
'WV',
'WI',
'WY']
def title_case(value):
# turns a word into Title Case and takes care of numbering and apostrophes
titled = value.title()
titled = re.sub(r"([a-z])'([A-Z])", lowercase_match, titled) # Fix Don'T
titled = re.sub(r"\d([A-Z])", lowercase_match, titled) # Fix 1St and 2Nd
return titled
def lowercase_match(match):
"""Lowercase the whole regular expression match group."""
return match.group().lower()
def replace_demimiters(string, entity = ''):
# Define a regular expression pattern to match comma, forward slash, or semicolon
# if artist or albumartist do not include & in splitting logic
if entity in ('artist', 'albumartist'):
pattern = r'[,\;/]'
else:
pattern = r'[,\;/&]'
# Replace occurrences of the pattern with double backslash
replaced_string = re.sub(pattern, r'\\\\', string)
# Remove spaces immediately before and after the double backslash
replaced_string = re.sub(r'\s*\\\\\s*', r'\\\\', replaced_string)
return replaced_string
def first_alpha(string):
# returns the pos of the first alpha char in a string, else -1
match = re.search(r'[a-zA-Z]', string)
if match:
return match.start()
else:
return -1
def last_alpha(string):
# returns the pos of the last alpha char in a string, else -1
last_alpha = -1
for i, c in enumerate(string):
if c.isalpha():
last_alpha = i
return last_alpha
def capitalise_first_alpha(s):
# Capitalises first alpha char in s
for i, c in enumerate(s):
if c.isalpha():
tmp = s[:i] + c.upper() + s[i+1:]
if always_upper(tmp) or us_state(tmp):
tmp = tmp.upper()
return tmp
return s
# stuff intended to handle single words
def is_roman_numeral(word):
first_char = first_alpha(word)
if first_char > -1: # i.e. there is indeed at least one alpha char in string
last_char = last_alpha(word) + 1
word = word[first_char:last_char]
''' determines whether word passed is a roman numeral within the stricter meaning of the term and returns it properly formatted '''
return bool(re.match(r'^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$', word.upper()))
# def always_upper(word):
# '''determines whether word is in list of words that will always be uppercase'''
# return word.upper() in ('ABBA', 'BBC', 'BMG', 'EP', 'EU', 'FM', 'LP', 'MFSL', 'MOFI', 'MTV','NRG', 'NYC', 'UDSACD', 'UMG','USA', 'U.S.A.')
# def always_upper(word):
# '''determines whether word is in list of words that will always be uppercase after stripping out the last char where it's a bracket'''
# # consider using if not word[-1].isalpha() to catch all instances of a word e.g. USA1, USA- etc.
# if word[-1] in (')', ']', '}'):
# word = word[:len(word)-1]
# return word.upper() in ('ABBA', 'BBC', 'BMG', 'EP', 'EU', 'FM', 'LP', 'MFSL', 'MOFI', 'NRG', 'NYC', 'UDSACD', 'UMG','USA', 'U.S.A.')
def always_upper(word):
'''determines whether word is in list of words that will always be uppercase after stripping out non-alpha chars at the beginning and end of the string '''
first_char = first_alpha(word)
if first_char > -1: # i.e. there is indeed at least one alpha char in string
last_char = last_alpha(word) + 1
word = word[first_char:last_char]
return word.upper() in ('A&M', 'ABBA', 'AFZ', 'BBC', 'BBQ', 'BMG', 'CD', 'CD/DVD', 'DSD', 'DVD', 'DVD-A', 'EMI', 'EP', 'EU', 'FM', 'HBO', 'HMV', 'KCRW', 'LP', 'MFSL', 'MCA', 'MOFI', 'MTV', 'NL', 'NRG', 'NYC', 'SACD', 'SHM-CD', 'UDCD', 'UDSACD', 'UK', 'UMG', 'USA', 'U.S.A.', 'XYZ', 'ZZ')
def capitalise_first_word(sentence):
# capitalises the first word in a string passed to it
if not sentence: # empty sentence check
return ''
words = sentence.split()
first_word = sentence[0]
if first_word and re.match(r'(:|\?|!|\}|\—|\(|\)|"| )', first_word):
first_word = capitalise_word(first_word)
return ' '.join(words)
def capitalise_last_word(sentence):
# capitalises the last word in a string passed to it
if not sentence: # empty sentence check
return ''
words = sentence.split()
*_, lastword = words
if lastword and re.match(r'(:|\?|!|\}|\—|\(|\)|"| )', lastword):
lastword = capitalise_word(lastword)
return ' '.join(words)
def capitalise_word(word):
''' loose implementation of RYM's capitalisation standards '''
if word.lower() in ['a', 'an', 'and', 'at', 'but', 'by', 'cetera ', 'et', 'etc.', 'for', 'in', 'nor', 'of', 'on', 'or', 'the', 'to', 'v.', 'versus', 'vs.', 'yet']:
return word.lower()
# elif word.lower() in ['am', 'are', 'as', 'be', 'been', 'from', 'he', 'if', 'into', 'is', 'it', 'she', 'so', 'upon', 'was', 'we', 'were', 'with']:
# return word.capitalize()
elif word.lower() == 'khz':
return 'kHz'
elif word.lower() == 'khz]':
return 'kHz]'
elif word.lower() == '10cc':
return '10cc'
elif is_roman_numeral(word) or always_upper(word) or us_state(word):
return word.upper()
else:
# if it doesn't meet any of thse special conditions. capitalise it taking into account first aplha character as capitalisation candidate
# return capitalise_first_alpha(word)
return capitalise_first_alpha(word.capitalize())
# this handles the full string
def rymify(sentence):
''' Breaks a sentence down into words and capitalises each according to capitalise_word() '''
if not sentence: # empty sentence check
return ''
parts = re.split(r'(:|\?|!|\—|\(|\)|"| )', sentence)
for i in range(len(parts)):
if parts[i] and not re.match(r'(:|\?|!|\—|\(|\)|"|&| )', parts[i]):
parts[i] = capitalise_word(parts[i])
# Join parts while maintaining original spacing
capitalised_sentence = ''.join(parts)
# Capitalize first and last word
capitalised_sentence = capitalise_first_alpha(capitalise_last_word(capitalised_sentence))
return capitalised_sentence
def trim_whitespace(string):
''' get rid of multiple spaces between characters in strings '''
return " ".join(string.split())
def sanitize_dirname(dirname):
"""
Sanitize a file path by removing illegal characters.
''.strip() basically means that nothing is returned to replace the illegal char
"""
illegal_chars = '#%{}\\<>*?$":@+`|='
sanitized_dirname = ''.join(char if char not in illegal_chars else ''.strip() for char in dirname)
return sanitized_dirname
def sanitize_filename(filename):
"""
Sanitize a file path by removing illegal characters.
''.strip() basically means that nothing is returned to replace the illegal char
"""
illegal_chars = '#%{}\\<>*?/$":@+`|='
sanitized_filename = ''.join(char if char not in illegal_chars else ''.strip() for char in filename)
return sanitized_filename
def pad_text(text, pad_len = 2):
''' pad incoming text to padlen '''
padding_prefix = '0'
if len(text) < pad_len:
text = padding_prefix * ((pad_len - len(text)) // len(padding_prefix)) + text
return text
def table_exists(table_name):
''' test whether table exists in a database '''
dbcursor.execute(f"SELECT count(name) FROM sqlite_master WHERE type='table' AND name='{table_name}';")
#if the count is 1, then table exists
return dbcursor.fetchone()[0] == 1
def get_columns(table_name):
''' return the list of columns in a table '''
dbcursor.execute(f"SELECT name FROM PRAGMA_TABLE_INFO('{table_name}');")
return dbcursor.fetchall()
def tag_in_table(tag, table_name):
''' check if tag exists in table '''
dbcursor.execute(f"SELECT name FROM PRAGMA_TABLE_INFO('{table_name}');")
dbtags = dbcursor.fetchall()
''' generate a list of the first element of each tuple in the list of tuples that is dbtags '''
dblist = list(zip(*dbtags))[0]
''' build list of matching tagnames in dblist '''
return tag in dblist
def dedupe_and_sort(input_string, delimiter=r'\\'):
''' get a list items that contains a delimited string, dedupe and sort it and pass it back '''
distinct_items = set(x.strip() for x in input_string.split(delimiter))
return delimiter.join(sorted(distinct_items))
def eliminate_duplicates_ordered_dict(input_string):
''' utility function to elimiate duplicate words from a string whilst preserving the order of the string. If order wasn't important set() would be faster '''
word_list = input_string.split()
unique_words = list(OrderedDict.fromkeys(word_list))
return ' '.join(unique_words)
def delete_repeated_phrase2(s, phrase):
if phrase == None:
return s
j = s.find(phrase)
if j >= 0:
k = j + len(phrase)
s = s[:k] + s[k:].replace(phrase, "")
return s
def delete_repeated_phrase(sentence, phrase, lastonly = False):
''' deletes all but the first instance of phrase from sentence, unless lastonly == True. Pass True if you only want to remove the last instance of a phrase from sentence '''
# first count the number of instances of a phrase in the sentence, if no occurences, return the original sentence
if sentence.count(phrase) == 0:
return sentence
# get phrase length
phrase_len = len(phrase)
# reverse the string because we want to remove the phrase from end of sentence to start of sentence
reversed_sentence = sentence[::-1]
reversed_phrase = phrase[::-1]
if lastonly:
# slice string to remove the first occurence of the phrase
index = reversed_sentence.find(reversed_phrase)
reversed_sentence = reversed_sentence[0:index] + reversed_sentence[index + 1 + phrase_len:]
new_sentence = reversed_sentence[::-1]
return new_sentence
else:
# while there remains more than 1 instance of phrase in sentence
while reversed_sentence.count(reversed_phrase) > 1:
# slice string to remove the first occurence of the phrase
index = reversed_sentence.find(reversed_phrase)
reversed_sentence = reversed_sentence[0:index] + reversed_sentence[index + 1 + phrase_len:]
new_sentence = reversed_sentence[::-1]
return new_sentence
def get_spurious_items(source, target):
''' function to return all items in source that do not appear in target '''
return [item for item in source if item not in target]
def get_permitted_list(source: list, target: tuple):
''' function to return all items in source that appear in target '''
return sorted(set(source).intersection(target))
def vetted_list_intersection(source: list, target: tuple):
intersection = []
s = [x.lower() for x in source]
for t in target:
if t.lower() in s:
intersection.append(t)
return intersection
def delimited_string_to_list(input_string, delimiter=r'\\'):
''' convert delimited string to list and pass it back '''
return input_string.split(delimiter)
def list_to_delimited_string(input_list: list, delimiter=r'\\'):
''' convert a list of items to a delimited string '''
return delimiter.join(map(str, input_list))
def tally_mods():
''' start and stop counter that returns how many changes have been triggered at the point of call - will be >= 0 '''
dbcursor.execute('SELECT SUM(sqlmodded) FROM alib WHERE sqlmodded IS NOT NULL;')
matches = dbcursor.fetchone()
if matches[0] is None:
''' sqlite returns null from a sum operation if the field values are null, so test for it, because if the script is run iteratively that'll be the case where alib has been readied for export '''
return 0
return matches[0]
def changed_records():
''' returns how many records have been changed at the point of call - will be >= 0 '''
dbcursor.execute('SELECT count(sqlmodded) FROM alib;')
matches = dbcursor.fetchone()
return matches[0]
def library_size():
''' returns record count in alib '''
dbcursor.execute('SELECT count(*) FROM alib;')
matches = dbcursor.fetchone()
return matches[0]
def affected_dirpaths():
''' get list of all affected __dirpaths '''
dbcursor.execute('SELECT DISTINCT __dirpath FROM alib where sqlmodded IS NOT NULL;')
matches = dbcursor.fetchall()
return matches
def affected_dircount():
''' sum number of distinct __dirpaths with changed content '''
return(len(affected_dirpaths()))
def create_indexes():
''' set up indexes to be used throughout the script operations'''
print("Creating table indexes...")
if table_exists('alib'):
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_filepaths ON alib(__path);''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_artists ON alib (artist) WHERE artist IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_lartists ON alib (LOWER(artist)) WHERE artist IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_albartists ON alib (albumartist) WHERE albumartist IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_lalbartists ON alib (LOWER(albumartist)) WHERE albumartist IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_performers ON alib (performer) WHERE performer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_lperformers ON alib (LOWER(performer)) WHERE performer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_composers ON alib (composer) WHERE composer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_lcomposers ON alib (LOWER(composer)) WHERE composer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_writers ON alib (writer) WHERE writer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_lwriters ON alib (LOWER(writer)) WHERE writer IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_titles ON alib(title) WHERE title IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_ltitles ON alib(LOWER(title)) WHERE title IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_genres ON alib(genre) WHERE genre IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_alib_styles ON alib(style) WHERE style IS NOT NULL;''')
if table_exists('_REF_mb_entities'):
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix__REF_mb_entities_lmb_master on _REF_mb_entities(lentity) WHERE entity IS NOT NULL;''')
if table_exists('_REF_mb_entities'):
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_mb_namesakes_lmb_namesakes on mb_namesakes(lentity) WHERE entity IS NOT NULL;''')
if table_exists('_REF_contributor_matched_on_allmusic'):
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix__REF_contributor_matched_on_allmusic_contributor on _REF_contributor_matched_on_allmusic(contributor) WHERE contributor IS NOT NULL;''')
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix__REF_contributor_matched_on_allmusic_lcontributor on _REF_contributor_matched_on_allmusic(lcontributor) WHERE contributor IS NOT NULL;''')
if table_exists('_REF_mb_disambiguated'):
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix__REF_mb_disambiguated_ldisambiguated on _REF_mb_disambiguated(lentity) WHERE entity IS NOT NULL;''')
def establish_environment():
''' define tables and fields required for the script to do its work '''
good_tags = [
"__accessed",
"__app",
"__bitrate",
"__bitrate_num",
"__bitspersample",
"__channels",
"__created",
"__dirname",
"__dirpath",
"__ext",
"__file_access_date",
"__file_access_datetime",
"__file_access_datetime_raw",
"__file_create_date",
"__file_create_datetime",
"__file_create_datetime_raw",
"__file_mod_date",
"__file_mod_datetime",
"__file_mod_datetime_raw",
"__file_size",
"__file_size_bytes",
"__file_size_kb",
"__file_size_mb",
"__filename",
"__filename_no_ext",
"__filetype",
"__frequency",
"__frequency_num",
"__image_mimetype",
"__image_type",
"__layer",
"__length",
"__length_seconds",
"__md5sig",
"__mode",
"__modified",
"__num_images",
"__parent_dir",
"__path",
"__size",
"__tag",
"__tag_read",
"__vendorstring",
"__version",
"tagminder_uuid",
"acousticbrainz_mood",
"acoustid_fingerprint",
"acoustid_id",
"album",
"album_dr",
"albumartist",
"amg_album_id",
"amg_boxset_url",
"amg_url",
"amgtagged",
"analysis",
"arranger",
"artist",
"asin",
"barcode",
"bootleg",
"catalog",
"catalognumber",
"compilation",
"composer",
"conductor",
"country",
"discnumber",
"discogs_artist_url",
"discogs_release_url",
"discsubtitle",
"engineer",
"ensemble",
"fingerprint",
"genre",
"isrc",
"label",
"live",
"lyricist",
"lyrics",
"movement",
"mixer",
"mood",
"musicbrainz_albumartistid",
"musicbrainz_albumid",
"musicbrainz_artistid",
"musicbrainz_composerid",
"musicbrainz_engineerid",
"musicbrainz_discid",
"musicbrainz_producerid",
"musicbrainz_releasegroupid",
"musicbrainz_releasetrackid",
"musicbrainz_trackid",
"musicbrainz_workid",
"musicbrainz_arrangerid",
"musicbrainz_conductoridid",
"musicbrainz_lyricistid",
"musicbrainz_mixerid",
"musicbrainz_remixerid",
"musicbrainz_writerid",
"originaldate",
"originalreleasedate",
"originalyear",
"part",
"performancedate",
"performer",
"personnel",
"producer",
"rating",
"recordinglocation",
"recordingstartdate",
"reflac",
"releasetype",
"remixer",
"replaygain_album_gain",
"replaygain_album_peak",
"replaygain_track_gain",
"replaygain_track_peak",
"review",
"roonalbumtag",
"roonradioban",
"roontracktag",
"roonid",
"sqlmodded",
"style",
"subtitle",
"theme",
"title",
"track",
"upc",
"version",
"work",
"writer",
"year"]
print("Populating permitted tags table...")
dbcursor.execute('drop table if exists _TMP_permitted_tags;')
dbcursor.execute('create table _TMP_permitted_tags (tagname text);')
for tag in good_tags:
dbcursor.execute(f"INSERT INTO _TMP_permitted_tags ('tagname') VALUES ('{tag}')")
# create enduring indexes required to operate efficiently
create_indexes()
''' ensure trigger is in place to record incremental changes until such time as tracks are written back '''
dbcursor.execute("CREATE TRIGGER IF NOT EXISTS sqlmods AFTER UPDATE ON alib FOR EACH ROW WHEN old.sqlmodded IS NULL BEGIN UPDATE alib SET sqlmodded = iif(sqlmodded IS NULL, '1', (CAST (sqlmodded AS INTEGER) + 1) ) WHERE rowid = NEW.rowid; END;")
''' alib_rollback is a master copy of alib table untainted by any changes made by this script. if a rollback table already exists we are applying further changes or imports, so leave it intact '''
dbcursor.execute("CREATE TABLE IF NOT EXISTS alib_rollback AS SELECT * FROM alib order by __path;")
# check whether there's a musicbrainz entities table containing distinct names and mbid's. If it exists, leverage it. Note, this table is the entire musicbrainz master before removing namesakes.
# Namesakes need to be dealt with manually in userland, it's not something that can be automated as there's no way to reliably distinguish one namesake from another when considering only name
if table_exists('_REF_mb_entities'):
# # index it for speed
# dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_lmb_master on _REF_mb_entities(lower(entity)) WHERE entity IS NOT NULL;''')
# given a user may have preferences as to how an artist name is written, check whether any changes need to be made to _REF_mb_entities to align with user preference as captured in _REF_vetted_contributors table
# as an example, most of my tagging over the years leveraged allmusic.com artist names and those are reflected in _REF_vetted_contributors where I've had to make changes to sourced metadata in the past
if table_exists('_REF_vetted_contributors'):
dbcursor.execute('''UPDATE _REF_mb_entities
SET entity = _REF_vetted_contributors.replacement_val,
updated_from__REF_vetted_contributors = '1'
FROM _REF_vetted_contributors
WHERE (_REF_vetted_contributors.lreplacement_val == _REF_mb_entities.lentity AND
_REF_vetted_contributors.replacement_val != _REF_mb_entities.entity);
''')
# do the same for allmusic vetted names if _REF_contributor_matched_on_allmusic exists (it contains artist names vetted against allmusic.com, with the Allmusic text case shown)
if table_exists('_REF_contributor_matched_on_allmusic'):
dbcursor.execute('''UPDATE _REF_mb_entities
SET entity = '_REF_contributor_matched_on_allmusic.contributor',
updated_from__REF_vetted_contributors = '1'
FROM _REF_vetted_contributors
WHERE (_REF_vetted_contributors.lreplacement_val == _REF_mb_entities.lentity AND
_REF_vetted_contributors.replacement_val != _REF_mb_entities.entity);
''')
# create a table of namesakes for users to browse if they need to disambiguate
dbcursor.execute('''DROP TABLE IF EXISTS mb_namesakes;''')
dbcursor.execute('''CREATE TABLE IF NOT EXISTS mb_namesakes AS SELECT *
FROM (
WITH cte AS (
SELECT entity
FROM _REF_mb_entities
GROUP BY lower(entity)
HAVING count() > 1
ORDER BY lower(entity)
)
SELECT mbid,
entity,
lentity
FROM _REF_mb_entities
WHERE entity IN cte
);''')
# index it for speed
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_lmb_namesakes on mb_namesakes(lentity) WHERE entity IS NOT NULL;''')
# create a table of entity names that only appear once in mb_master for use within tagminder when adding mbid's to artist, albumartist, composer, engineer, producer, label and recordinglocation tags
dbcursor.execute('''DROP TABLE IF EXISTS _REF_mb_disambiguated;''')
dbcursor.execute('''CREATE TABLE IF NOT EXISTS _REF_mb_disambiguated AS SELECT *
FROM (
SELECT mbid,
entity,
lentity
FROM _REF_mb_entities
GROUP BY lower(entity)
HAVING count() == 1
ORDER BY lower(entity)
);''')
# index it for speed
dbcursor.execute('''CREATE INDEX IF NOT EXISTS ix_mb_ldisambiguated on _REF_mb_disambiguated(lentity) WHERE entity IS NOT NULL;''')
conn.commit()
return
# genre related functionality module addressing specifics related to genres
def vetted_genre_pool():
''' return a tuple of sanctioned genres - based on allmusic.com 4/11/2023 with some custom genres added '''
return ("Aboriginal Rock",
"Acadian",
"Acappella",
"Acid Folk",
"Acid House",
"Acid Jazz",
"Acid Rock",
"Acid Techno",
"Acoustic Blues",
"Acoustic Chicago Blues",
"Acoustic Louisiana Blues",
"Acoustic Memphis Blues",
"Acoustic New Orleans Blues",
"Acoustic Texas Blues",
"Adult Alternative",
"Adult Alternative Pop/Rock",
"Adult Contemporary",
"Adult Contemporary R&B",
"Afghanistan",
"Afoxe",
"African Folk",
"African Jazz",
"African Psychedelia",
"African Rap",
"African Traditions",
"Afrikaans",
"Afro-beat",
"Afro-Brazilian",
"Afro-Colombian",
"Afro-Cuban",
"Afro-Cuban Jazz",
"Afro-Peruvian",
"Afro-Pop",
"Afroswing",
"Al-Jil",
"Albanian",
"Album Rock",
"Algerian",
"Alpine",
"Alt-Country",
"Alterna Movimiento",
"Alternative CCM",
"Alternative Corridos",
"Alternative Country",
"Alternative Country-Rock",
"Alternative Dance",
"Alternative Folk",
"Alternative Latin",
"Alternative Metal",
"Alternative Pop/Rock",
"Alternative R&B",
"Alternative Rap",
"Alternative Singer/Songwriter",
"Alternative/Indie Rock",
"AM Pop",
"Ambient",
"Ambient Breakbeat",
"Ambient Dub",
"Ambient House",
"Ambient Pop",
"Ambient Techno",
"American Jewish Pop",
"American Popular Song",
"American Punk",
"American Trad Rock",
"American Underground",
"Americana",
"Anarchist Punk",
"Andalus Classical",
"Andean Folk",
"Angolan",
"Anime Music",
"Anti-Folk",
"Apala",
"Appalachian",
"Arabic",
"Arena Rock",
"Argentinian Folk",
"Armenian",
"Armenian Folk",
"Art Rock",
"Art-Rock/Experimental",
"Asian Folk",
"Asian Pop",
"Asian Psychedelia",
"Asian Rap",
"Asian Rock",
"Asian Traditions",
"Aussie Rock",
"Australasian",
"Australian",
"Austrian",
"AustroPop",
"Avant-Garde",
"Avant-Garde Jazz",
"Avant-Garde Metal",
"Avant-Garde Music",
"Avant-Prog",
"Axe",
"Azerbaijani",
"Azorean",
"Bachata",
"Bahamian",
"Baile Funk",
"Bakersfield Sound",
"Balinese",
"Balkan",
"Ballet",
"Ballroom Dance",
"Baltic",
"Bambara",
"Band Music",
"Banda",
"Bangladeshi",
"Bar Band",
"Barbershop Quartet",
"Baroque Pop",
"Baseline",
"Basque",
"Bass Music",
"Bava",
"Bavarian",
"Bay Area Rap",
"Beach",
"Beat Poetry",
"Bedroom Pop",
"Beguine",
"Beguine Moderne",
"Beguine Vide",
"Belair",
"Belarusian",
"Belgian",
"Belly Dancing",
"Benga",
"Bengali",
"Berber",
"Bhangra",
"Big Band",
"Big Band/Swing",
"Big Beat",
"Bikutsi",
"Bird Calls",
"Black Gospel",
"Black Metal",
"Blackgaze",
"Blaxploitation",
"Blue Humor",
"Blue-Eyed Soul",
"Bluebeat",
"Bluegrass",
"Bluegrass-Gospel",
"Blues",
"Blues Gospel",
"Blues Revival",
"Blues-Rock",
"Bolero",
"Bolivian",
"Bollywood",
"Bomba",
"Bongo Flava",
"Boogaloo",
"Boogie Rock",
"Boogie-Woogie",
"Bop",
"Bop Vocals",
"Bornean",
"Bosnian",
"Bossa Nova",
"Brazilian Folk",
"Brazilian Jazz",
"Brazilian Pop",
"Brazilian Traditions",
"Breakcore",
"Breton",
"Brill Building Pop",
"British",
"British Blues",
"British Dance Bands",
"British Folk",
"British Folk-Rock",
"British Invasion",
"British Metal",
"British Psychedelia",
"British Punk",
"British Rap",
"British Trad Rock",
"Britpop",
"Bro-Country",
"Broken Beat",
"Brown-Eyed Soul",
"Bubblegum",
"Buddhist",
"Bulgarian",
"Bulgarian Folk",
"Burundi",
"C-86",
"C-Pop",
"Cabaret",
"Cadence",
"Cajun",
"Calypso",
"Cambodian",
"Cameroonian",
"Canadian",
"Canterbury Scene",
"Cantopop",
"Cape Verdean",
"Caribbean Traditions",
"Carnatic",
"Carnival",
"Carols",
"Cartoon Music",
"Cast Recordings",
"CCM",
"Celebrity",
"Celtic",
"Celtic Folk",
"Celtic Fusion",
"Celtic Gospel",
"Celtic New Age",
"Celtic Pop",
"Celtic Rock",
"Celtic/British Isles",
"Central African",
"Central American Traditions",
"Central European Traditions",
"Central/West Asian Traditions",
"Ceremonial",
"Cha-Cha",
"Chamber Jazz",
"Chamber Music",
"Chamber Pop",
"Changui",
"Chants",
"Chanukah",
"Charanga",
"Chassidic",
"Chicago Blues",
"Chicago House",
"Chicago Jazz",
"Chicago Soul",
"Children's",
"Children's Folk",
"Children's Pop",
"Children's Rock",
"Children's Songwriters",
"Chilean",
"Chillwave",
"Chimurenga",
"Chinese Classical",
"Chinese Rap",
"Chinese Rock",
"Chinese Traditions",
"Chiptunes",
"Choral",
"Choro",
"Chouval Bwa",
"Christian Comedy",
"Christian Metal",
"Christian Punk",
"Christian Rap",
"Christian Rock",
"Christmas",
"City Pop",
"Classic Blues Vocals",
"Classic Female Blues",
"Classical",
"Classical Crossover",
"Classical Pop",
"Close Harmony",
"Cloud Rap",
"Club/Dance",
"Clubjazz",
"Cocktail",
"Cold Wave",
"College Rock",
"Colombian",
"Comedy",
"Comedy Rap",
"Comedy Rock",
"Comedy/Spoken",
"Compas",
"Composer Songbook",
"Computer Music",
"Conceptual Art",
"Concerto",
"Congolese",
"Conjunto",
"Contemporary Bluegrass",