/
data.py
621 lines (527 loc) · 21.9 KB
/
data.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
from hashlib import sha256
import logging
import copy
import time
import json
import os
import db
import db.exceptions
from flask import current_app
from sqlalchemy import text
import sqlalchemy.exc
from brainzutils import musicbrainz_db
_whitelist_file = os.path.join(os.path.dirname(__file__), "tagwhitelist.json")
_whitelist_tags = set(json.load(open(_whitelist_file)))
SANITY_CHECK_KEYS = [
['metadata', 'version', 'essentia'],
['metadata', 'version', 'essentia_git_sha'],
['metadata', 'version', 'extractor'],
['metadata', 'version', 'essentia_build_sha'],
['metadata', 'audio_properties', 'length'],
['metadata', 'audio_properties', 'bit_rate'],
['metadata', 'audio_properties', 'codec'],
['metadata', 'audio_properties', 'lossless'],
['metadata', 'tags', 'file_name'],
['metadata', 'tags', 'musicbrainz_recordingid'],
['lowlevel'],
['rhythm'],
['tonal'],
]
STATUS_HIDDEN = 'hidden'
STATUS_EVALUATION = 'evaluation'
STATUS_SHOW = 'show'
VERSION_TYPE_LOWLEVEL = 'lowlevel'
VERSION_TYPE_HIGHLEVEL = 'highlevel'
MODEL_STATUSES = [STATUS_HIDDEN, STATUS_EVALUATION, STATUS_SHOW]
# TODO: Util methods should not be in the database package
def _has_key(dictionary, key):
"""Checks if muti-level dictionary contains in item referenced by a
specified key.
Args:
dictionary: Multi-level dictionary that needs to be checked.
keys: List of keys that will be checked. For example, key
['metadata', 'tags'] represents dictionary['metadata']['tags'].
Returns:
True if dictionary contains item with a specified key, False if it
wasn't found.
"""
for part in key:
if part not in dictionary:
return False
dictionary = dictionary[part]
return True
def sanity_check_data(data):
"""Checks if data about the recording contains all required keys.
Args:
data: Dictionary that contains information about the recording.
Returns:
First key that is missing or None if everything is in place.
"""
for key in SANITY_CHECK_KEYS:
if not _has_key(data, key):
return key
return None
def clean_metadata(data):
"""Check that tags are in our whitelist. If not, throw them away."""
cleaned_tags = copy.deepcopy(data["metadata"]["tags"])
for tag in data["metadata"]["tags"].keys():
if tag.lower() not in _whitelist_tags:
del cleaned_tags[tag]
data["metadata"]["tags"] = cleaned_tags
return data
def submit_low_level_data(mbid, data, gid_type):
"""Function for submitting low-level data.
Args:
mbid: MusicBrainz ID of the recording that corresponds to the data
that is being submitted.
data: Low-level data about the recording.
gid_type: the ID type [musicbrainzid(mbid) or messybrainzid(msid)]
"""
mbid = str(mbid)
data = clean_metadata(data)
try:
# If the user submitted a trackid key, rewrite to recording_id
if 'musicbrainz_trackid' in data['metadata']['tags']:
val = data['metadata']['tags']['musicbrainz_trackid']
del data['metadata']['tags']['musicbrainz_trackid']
data['metadata']['tags']['musicbrainz_recordingid'] = val
if data['metadata']['audio_properties']['lossless']:
data['metadata']['audio_properties']['lossless'] = True
else:
data['metadata']['audio_properties']['lossless'] = False
except KeyError:
pass
missing_key = sanity_check_data(data)
if missing_key is not None:
raise db.exceptions.BadDataException(
"Key '%s' was not found in submitted data." %
' : '.join(missing_key)
)
# Ensure the MBID form the URL matches the recording_id from the POST data
if data['metadata']['tags']['musicbrainz_recordingid'][0].lower() != mbid.lower():
raise db.exceptions.BadDataException(
"The musicbrainz_trackid/musicbrainz_recordingid in "
"the submitted data does not match the MBID that is "
"part of this resource URL."
)
# The data looks good, lets see about saving it
write_low_level(mbid, data, gid_type)
def insert_version(connection, data, version_type):
# TODO: Memoise sha -> id
norm_data = json.dumps(data, sort_keys=True, separators=(',', ':'))
sha = sha256(norm_data).hexdigest()
query = text("""
SELECT id
FROM version
WHERE data_sha256=:data_sha256
AND type=:version_type""")
result = connection.execute(query, {"data_sha256": sha, "version_type": version_type})
row = result.fetchone()
if row:
return row[0]
result = connection.execute(
text("""INSERT INTO version (data, data_sha256, type)
VALUES (:data, :sha, :version_type)
RETURNING id"""),
{"data": norm_data, "sha": sha, "version_type": version_type}
)
row = result.fetchone()
return row[0]
def write_low_level(mbid, data, is_mbid):
def _get_by_data_sha256(connection, data_sha256):
query = text("""
SELECT id
FROM lowlevel_json
WHERE data_sha256 = :data_sha256
""")
result = connection.execute(query, {"data_sha256": data_sha256})
return result.fetchone()
def _insert_lowlevel(connection, mbid, build_sha1, is_lossless_submit, gid_type):
""" Insert metadata into the lowlevel table and return its id """
query = text("""
INSERT INTO lowlevel (gid, build_sha1, lossless, gid_type)
VALUES (:mbid, :build_sha1, :lossless, :gid_type)
RETURNING id
""")
result = connection.execute(query, {"mbid": mbid,
"build_sha1": build_sha1,
"lossless": is_lossless_submit,
"gid_type": gid_type})
return result.fetchone()[0]
def _insert_lowlevel_json(connection, ll_id, data_json, data_sha256, version_id):
""" Insert the contents of the data file, with references to
the version and metadata"""
query = text("""
INSERT INTO lowlevel_json (id, data, data_sha256, version)
VALUES (:id, :data, :data_sha256, :version)
""")
connection.execute(query, {"id": ll_id,
"data": data_json,
"data_sha256": data_sha256,
"version": version_id})
is_lossless_submit = data['metadata']['audio_properties']['lossless']
version = data['metadata']['version']
build_sha1 = version['essentia_build_sha']
data_json = json.dumps(data, sort_keys=True, separators=(',', ':'))
data_sha256 = sha256(data_json.encode("utf-8")).hexdigest()
with db.engine.begin() as connection:
# See if we already have this data
existing = _get_by_data_sha256(connection, data_sha256)
if existing:
logging.info("Already have %s" % data_sha256)
return
try:
ll_id = _insert_lowlevel(connection, mbid, build_sha1, is_lossless_submit, is_mbid)
version_id = insert_version(connection, version, VERSION_TYPE_LOWLEVEL)
_insert_lowlevel_json(connection, ll_id, data_json, data_sha256, version_id)
logging.info("Saved %s" % mbid)
except sqlalchemy.exc.DataError as e:
raise db.exceptions.BadDataException(
"data is badly formed")
def add_model(model_name, model_version, model_status=STATUS_HIDDEN):
if model_status not in MODEL_STATUSES:
raise Exception("model_status must be one of %s" % ",".join(MODEL_STATUSES))
with db.engine.begin() as connection:
query = text(
"""INSERT INTO model (model, model_version, status)
VALUES (:model_name, :model_version, :model_status)
RETURNING id"""
)
result = connection.execute(query,
{"model_name": model_name,
"model_version": model_version,
"model_status": model_status})
return result.fetchone()[0]
def set_model_status(model_name, model_version, model_status):
if model_status not in MODEL_STATUSES:
raise Exception("model_status must be one of %s" % ",".join(MODEL_STATUSES))
with db.engine.begin() as connection:
query = text(
"""UPDATE model
SET status = :model_status
WHERE model_name = :model_name
AND model_version = :model_version"""
)
connection.execute(query,
{"model_name": model_name,
"model_version": model_version,
"model_status": model_status})
def get_model(model_name, model_version):
with db.engine.begin() as connection:
query = text(
"""SELECT *
FROM model
WHERE model = :model_name
AND model_version = :model_version""")
result = connection.execute(query,
{"model_name": model_name,
"model_version": model_version})
return result.fetchone()
def _get_model_id(model_name, version):
with db.engine.begin() as connection:
query = text(
"""SELECT id
FROM model
WHERE model = :model_name
AND model_version = :model_version""")
result = connection.execute(query,
{"model_name": model_name,
"model_version": version})
row = result.fetchone()
if row:
return row[0]
else:
return None
def write_high_level_item(connection, model_name, model_version, ll_id, version_id, data):
item_norm_data = json.dumps(data, sort_keys=True, separators=(',', ':'))
item_sha = sha256(item_norm_data).hexdigest()
model_id = _get_model_id(model_name, model_version)
if model_id is None:
model_id = add_model(model_name, model_version)
item_q = text(
"""INSERT INTO highlevel_model (highlevel, data, data_sha256, model, version)
VALUES (:highlevel, :data, :data_sha256, :model, :version)""")
connection.execute(item_q,
{"highlevel": ll_id, "data": item_norm_data,
"data_sha256": item_sha, "model": model_id,
"version": version_id})
def write_high_level_meta(connection, ll_id, mbid, build_sha1, json_meta):
check_query = text(
"""SELECT id
FROM highlevel
WHERE id = :id""")
result = connection.execute(check_query, {"id": ll_id})
if result.rowcount:
# If this already exists, we don't need to add it
# (new model for existing highlevel)
return
hl_query = text(
"""INSERT INTO highlevel (id, mbid, build_sha1)
VALUES (:id, :mbid, :build_sha1)""")
connection.execute(hl_query, {"id": ll_id, "mbid": mbid, "build_sha1": build_sha1})
if json_meta:
meta_norm_data = json.dumps(json_meta, sort_keys=True, separators=(',', ':'))
sha = sha256(meta_norm_data).hexdigest()
hl_meta = text(
"""INSERT INTO highlevel_meta (id, data, data_sha256)
VALUES (:id, :data, :data_sha256)""")
connection.execute(hl_meta, {"id": ll_id, "data": meta_norm_data, "data_sha256": sha})
def write_high_level(mbid, ll_id, data, build_sha1):
"""Write highlevel data to the database.
This includes entries in the
highlevel
version
highlevel_model
tables. If the exact version already exists it will be reused.
If `data` is an empty dictionary, a highlevel table entry is still recorded
so that this submission is no longer processed by the highlevel runner
"""
with db.engine.begin() as connection:
json_meta = data.get("metadata", {})
json_high = data.get("highlevel", {})
write_high_level_meta(connection, ll_id, mbid, build_sha1, json_meta)
if json_meta and json_high:
hl_version = json_meta["version"]["highlevel"]
version_id = insert_version(connection, hl_version, VERSION_TYPE_HIGHLEVEL)
model_version = hl_version["models_essentia_git_sha"]
for model_name, data in json_high.items():
write_high_level_item(connection, model_name, model_version, ll_id, version_id, data)
def load_low_level(mbid, offset=0):
"""Load lowlevel data with the given mbid as a dictionary.
If no offset is given, return the first. If an offset is
given (from 0), return the relevent item.
Raises db.exceptions.NoDataFoundException if the mbid doesn't
exist or if the offset is too high."""
with db.engine.connect() as connection:
result = connection.execute(
"""SELECT llj.data
FROM lowlevel ll
JOIN lowlevel_json llj
ON ll.id = llj.id
WHERE ll.gid = %s
ORDER BY ll.submitted
OFFSET %s""",
(str(mbid), offset)
)
if not result.rowcount:
raise db.exceptions.NoDataFoundException
row = result.fetchone()
return row[0]
def load_high_level(mbid, offset=0):
"""Load high-level data for a given MBID."""
with db.engine.connect() as connection:
# Metadata
result = connection.execute(
"""SELECT hl.id
, hlm.data
FROM highlevel hl
LEFT JOIN highlevel_meta hlm
ON hl.id = hlm.id
JOIN lowlevel ll
ON ll.id = hl.id
WHERE ll.gid = %s
ORDER BY ll.submitted
OFFSET %s""",
(str(mbid), offset)
)
metarow = result.fetchone()
if metarow is None:
raise db.exceptions.NoDataFoundException
hlid = metarow[0]
metadata = metarow[1]
# If we have a `highlevel` row but not a `highlevel_meta` row it means that
# the hl calculation failed and we added a placeholder row. There is a
# database row, but the metadata is blank
if metadata is None:
raise db.exceptions.NoDataFoundException
# model data
query = text(
"""select m.model
, hlmo.data
, version.data as version
FROM highlevel_model hlmo
JOIN model m
ON m.id = hlmo.model
JOIN version
ON version.id = hlmo.version
WHERE hlmo.highlevel = :hlid
AND m.status = 'show'
""")
result = connection.execute(query, {"hlid": hlid})
highlevel = {}
for row in result.fetchall():
model = row[0]
data = row[1]
version = row[2]
data["version"] = version
highlevel[model] = data
return {"metadata": metadata, "highlevel": highlevel}
def count_lowlevel(mbid):
"""Count number of stored low-level submissions for a specified MBID."""
with db.engine.connect() as connection:
result = connection.execute(
"""SELECT COUNT(*)
FROM lowlevel
WHERE gid = %s""",
(str(mbid),)
)
return result.fetchone()[0]
def count_many_lowlevel(mbids):
"""Count number of stored low-level submissions for a specified set
of MBID."""
with db.engine.connect() as connection:
query = text(
"""SELECT gid
, COUNT(*)
FROM lowlevel
WHERE gid IN :mbids
GROUP BY gid;""")
return {str(mbid): {"count": int(count)} for mbid, count
in connection.execute(query, {"mbids": tuple(mbids)})}
def get_unprocessed_highlevel_documents_for_model(highlevel_model, within=None):
"""Fetch up to 100 low-level documents which have no associated
high level data for the given module_id.
if `within` is set, only return mbids that are in this list"""
within_query = ""
if within:
within_query = "AND ll.mbid IN :within"
with db.engine.connect() as connection:
query = text(
"""SELECT ll.gid::text
, llj.data::text
, ll.id
FROM lowlevel AS ll
JOIN lowlevel_json AS llj
ON llj.id = ll.id
LEFT JOIN (SELECT id, highlevel
FROM highlevel_model
WHERE model=:highlevel_model) AS hlm
ON ll.id = hlm.highlevel
WHERE hlm.id IS NULL
%s
LIMIT 100""" % within_query)
params = {"highlevel_model": highlevel_model}
if within:
params["within"] = tuple(within)
result = connection.execute(query, params)
docs = result.fetchall()
return docs
def get_unprocessed_highlevel_documents():
"""Fetch up to 100 low-level documents which have no associated high level data."""
with db.engine.connect() as connection:
query = text(
"""SELECT ll.gid::text
, llj.data::text
, ll.id
FROM lowlevel AS ll
JOIN lowlevel_json AS llj
ON llj.id = ll.id
LEFT JOIN highlevel AS hl
ON ll.id = hl.id
WHERE hl.mbid IS NULL
LIMIT 100""")
result = connection.execute(query)
docs = result.fetchall()
return docs
def get_summary_data(mbid, offset=0):
"""Fetches the low-level and high-level features from for the specified MBID.
Args:
offset: Offset can be specified if you need to get summary for a
different submission. They are ordered by creation time.
Returns:
Dictionary with low-level data ("lowlevel" key) for the specified MBID
and, if it has been calculated, high-level data ("highlevel" key).
"""
summary = {}
mbid = str(mbid)
lowlevel = load_low_level(mbid, offset)
if 'artist' not in lowlevel['metadata']['tags']:
lowlevel['metadata']['tags']['artist'] = ["[unknown]"]
if 'release' not in lowlevel['metadata']['tags']:
lowlevel['metadata']['tags']['release'] = ["[unknown]"]
if 'title' not in lowlevel['metadata']['tags']:
lowlevel['metadata']['tags']['title'] = ["[unknown]"]
lowlevel['metadata']['audio_properties']['length_formatted'] = \
time.strftime("%M:%S", time.gmtime(lowlevel['metadata']['audio_properties']['length']))
summary['lowlevel'] = lowlevel
try:
highlevel = load_high_level(mbid, offset)
summary['highlevel'] = highlevel
except db.exceptions.NoDataFoundException:
pass
return summary
def get_new_recordings_from_lowlevel():
with db.engine.begin() as connection:
rows_to_fetch = current_app.config['RECORDINGS_FETCHED_PER_BATCH']
query = text("""SELECT lowlevel.gid
FROM lowlevel
LEFT JOIN musicbrainz.recording
ON lowlevel.gid = musicbrainz.recording.gid
WHERE musicbrainz.recording.gid is NULL
ORDER BY lowlevel.id
LIMIT :rows_to_fetch
""")
gids = connection.execute(query, {"rows_to_fetch": rows_to_fetch})
gids = gids.fetchall()
gids_in_AB = [value[0] for value in gids]
return gids_in_AB
def get_mbids_from_gid_redirect_tables():
"""Fetch mbids from recording gid redirect table and calls function
get_original_entity to get the redirected result.
Returns:
Dictionary containing the redirected original entity ids with MBIDs as keys.
- mbid: Recording mbids of the entities
- id: Original redirected ids of the entities after mbid redirect
"""
with db.engine.begin() as connection:
query = text("""
SELECT gid
FROM musicbrainz.recording_gid_redirect
""")
result = connection.execute(query)
mbids = result.fetchall()
recording_mbids = []
for mbid in mbids:
recording_mbids.append(str(mbid[0]))
return recording_mbids
def get_current_schema_and_replication_sequence():
with musicbrainz_db.engine.begin() as connection:
query = text("""
SELECT current_schema_sequence, current_replication_sequence
FROM replication_control
""")
result = connection.execute(query)
schema_seq, mb_replication_seq = result.fetchone()
return schema_seq, mb_replication_seq
def get_replication_sequence_from_mb_schema():
with db.engine.begin() as connection:
query = text("""
SELECT current_replication_sequence
FROM musicbrainz.replication_control
""")
result = connection.execute(query)
sequence = result.fetchone()
return sequence[0]
def update_replication_sequence(replication_seq):
"""Store new replication sequence into replication_control table for future
updates and deletes from replication packets.
Args:
replication_seq: Current replication sequence to replace the old one.
"""
with db.engine.begin() as connection:
query = text("""
UPDATE musicbrainz.replication_control
SET current_replication_sequence = %s""" % (replication_seq)
)
connection.execute(query)
def write_replication_control(replication_seq):
"""Insert first replication sequence into replication_control table.
Args:
replication_seq: first replication sequence to start the download of packets from.
"""
with db.engine.begin() as connection:
query = text("""
INSERT INTO musicbrainz.replication_control (current_replication_sequence)
VALUES (:replication_seq)
""")
connection.execute(query, {'replication_seq': replication_seq})