-
Notifications
You must be signed in to change notification settings - Fork 171
/
cc_mixter.py
286 lines (229 loc) · 9.63 KB
/
cc_mixter.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
"""
Content Provider: ccMixter
ETL Process: Use the API to identify all CC licensed media.
Output: TSV file containing the media and the
respective meta-data.
Notes: Documentation: https://ccmixter.org/query-api
ccMixter sends bad JSON and extremely huge headers, both
of which need workarounds that are handled by this DAG.
"""
import json
import logging
import re
from typing import Literal
from common import constants
from common.licenses import get_license_info
from common.loader import provider_details as prov
from common.requester import DelayedRequester
from providers.provider_api_scripts.provider_data_ingester import ProviderDataIngester
logger = logging.getLogger(__name__)
JSON_OCTALS = re.compile(r":\s*0+(?P<num>\d+\.?\d*)\s*(?P<sep>[,}])")
class CcMixterDelayedRequester(DelayedRequester):
"""
WORKAROUND!
ccMixter sends bad JSON, including numbers with a leading 0 (observed some
such cases with "bpm" field). This makes the JSON invalid and raises decode
errors.
This class extends ``DelayedRequester`` to supply a custom JSON decoding
step where we perform a text substitution first and then parse the JSON.
"""
def _get_json(self, response):
raw_json = response.text
cleaned_json = JSON_OCTALS.sub(r":\g<num>\g<sep>", raw_json)
if cleaned_json == raw_json:
logger.debug("JSON was clean, no substitutions were made.")
else:
logger.warning("JSON had bad octals, substitutions were made.")
try:
# WORKAROUND!
#
# ccMixter sends JSON that can contain control characters which
# break JSON parsing, unless we use non-strict mode that can handle
# such malformed data as well.
response_json = json.loads(cleaned_json, strict=False)
except json.JSONDecodeError as e:
logger.warning(f"Could not get response_json.\n{e}")
response_json = None
return response_json
def patch_http_client():
"""
WORKAROUND!
ccMixter sends a very long ``X-Json`` header with the response, which causes
the ``http.client`` library to raise a ``LineTooLong`` error.
We work around it by patching the ``_read_headers`` function to ignore the
line length limit.
.. seealso::
StackOverflow
`Answer with this approach <https://stackoverflow.com/a/63158213/2601645>`_
``_read_headers()``
`Original implementation <https://github.com/python/cpython/blob/8b6ee5b/Lib/http/client.py#L206>`_
"""
import http.client
def _read_headers(fp):
logger.debug("Patched _read_headers() called.")
headers = []
while True:
line = fp.readline()
headers.append(line)
if len(headers) > http.client._MAXHEADERS:
raise http.client.HTTPException(
f"Got more than {http.client._MAXHEADERS} headers."
)
if line in (b"\r\n", b"\n", b""):
break
return headers
http.client._read_headers = _read_headers
class CcMixterDataIngester(ProviderDataIngester):
providers = {
"audio": prov.CC_MIXTER_DEFAULT_PROVIDER,
}
endpoint = "https://ccmixter.org/api/query/"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Set-up workarounds!
patch_http_client()
self.delayed_requester = CcMixterDelayedRequester(
delay=self.delay, headers=self.headers
)
def get_next_query_params(self, prev_query_params: dict | None, **kwargs) -> dict:
if not prev_query_params:
# This means this is the first request, so we start with offset 0.
return {
"format": "json",
"limit": self.batch_limit,
"offset": 0,
}
else:
# This is a subsequent request, so we bump the offset by a value
# equal to the batch limit.
return {
**prev_query_params,
"offset": prev_query_params["offset"] + self.batch_limit,
}
def get_batch_data(self, response_json):
return response_json
def get_should_continue(self, response_json):
# We can know we are at the last page if the number of records returned
# is less than the batch limit. This is not an issue even if the
# penultimate page has a batch limit number of results because ccMixter
# allows paginating after the last page too, returning ``[]``, which is
# less than the batch limit.
return len(response_json) >= self.batch_limit
def get_media_type(self, record: dict) -> Literal["audio"]:
return constants.AUDIO
@staticmethod
def _get_duration(ps: str | None) -> int | None:
"""
Convert a duration string to the number of milliseconds. This function
can handle between 1 and 3 segments in the time string.
:param ps: the human-friendly duration string
:return: the number of milliseconds
"""
if not ps:
return None
segments = map(int, [0, 0] + ps.split(":"))
*_, hours, minutes, seconds = segments
return (hours * 3600 + minutes * 60 + seconds) * 1000
@staticmethod
def _get_sample_rate(sr: str | None) -> int | None:
"""
Convert the sample rate from a human-friendly string to the integer
number of samples per second.
:param sr: the human-friendly sample rate
:return: the number of samples per second
"""
return int(float(sr.rstrip("k")) * 1000) if sr else None
def _get_audio_files(
self, files: list[dict]
) -> tuple[dict, list[dict]] | tuple[None, None]:
"""
Filter the audio files from the file list and identify the main one.
The list of files can include archives like ZIP files, which we drop.
The smallest audio file is assumed to be the main one, which is usually
MP3 in the case of ccMixter.
This is because the smallest audio file takes the least time to start
streaming, wastes the least data if not useful and MP3 is the most
widely supported format.
:param files: the list of files supplied by ccMixter
:return: the main file and a list of alternative files
"""
files = [
{
"url": file["download_url"],
"filesize": file["file_rawsize"],
"filetype": file["file_format_info"]["default-ext"],
"sample_rate": self._get_sample_rate(
file["file_format_info"].get("sr")
),
"duration": self._get_duration(file["file_format_info"].get("ps")),
}
for file in files
if file["file_format_info"]["media-type"] == "audio"
]
if not files:
return None, None
main_file, *alt_files = sorted(files, key=lambda file: file["filesize"])
return main_file, alt_files
def get_record_data(self, data: dict) -> dict | list[dict] | None:
if not (foreign_identifier := data.get("upload_id")):
logger.warning("Rejected record with no foreign identifier.")
return None
if not (foreign_landing_url := data.get("file_page_url")):
logger.warning(
f"Rejected record {foreign_identifier} with no foreign landing URL."
)
return None
# Use the `get_license_info` utility to get license information from a URL.
license_url = data.get("license_url")
license_info = get_license_info(license_url)
if not license_info:
logger.warning(
f"Rejected record {foreign_identifier} with no license info."
)
return None
if not (files := data.get("files")):
return None
main_file, alt_files = self._get_audio_files(files)
if not main_file:
logger.warning(
f"Rejected record {foreign_identifier} with no main audio file."
)
return None
# Optional fields
creator = data.get("user_real_name")
creator_url = data.get("artist_page_url")
title = data.get("upload_name")
meta_data = {
"description": data.get("upload_description_plain"),
"description_html": data.get("upload_description_html"),
"upload_num_scores": data.get("upload_num_scores", 0),
}
# ccMixter tags are comma-separated, and there is a leading and trailing
# comma, so we need to filter out empty strings.
raw_tags = list(filter(None, data.get("upload_tags").split(",")))
return {
"foreign_identifier": foreign_identifier,
"foreign_landing_url": foreign_landing_url,
"license_info": license_info,
# Optional fields
"creator": creator,
"creator_url": creator_url,
"title": title,
"meta_data": meta_data,
"raw_tags": raw_tags,
"alt_files": alt_files,
# ``main_file`` contains the following fields:
# - ``url``
# - ``filesize``
# - ``filetype``
# - ``sample_rate``
# - ``duration``
**main_file,
}
def main():
# Allows running ingestion from the CLI without Airflow running for debugging
# purposes.
ingester = CcMixterDataIngester()
ingester.ingest_records()
if __name__ == "__main__":
main()