-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
293 lines (257 loc) · 11.1 KB
/
api.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
from datetime import datetime, timedelta
from flask import jsonify
from flask_restful import Resource
from models import db, Play, Track, Album, Artist
def arg_date_to_datetime(from_date, to_date):
f = datetime.strptime(from_date, '%Y-%m-%d') if from_date else datetime(2017, 8, 1)
t = datetime.strptime(to_date, '%Y-%m-%d') if to_date else datetime.now()
t = t + timedelta(days=1) # To receive the whole day
return f, t
class Plays(Resource):
def get(self, user_name):
latest_plays = Play.query.\
filter_by(user_name=user_name).\
order_by(Play.played_at_cet.desc()).\
limit(20).\
all()
result = []
for play in latest_plays:
result.append(play.to_dict())
response = jsonify({
'meta': {
'user_name': user_name,
},
'latest_plays': result,
})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
class ResourceMixin(object):
def _apply_meta_data(self, unit, user_name, from_date, to_date, resource):
return {
'meta': {
'from_date': from_date,
'to_date': to_date,
'user_name': user_name,
'unit': unit,
'resource': resource,
},
}
class Counts(Resource, ResourceMixin):
N = 100
def _arg_date_to_datetime(self, from_date, to_date):
f = datetime.strptime(from_date, '%Y-%m-%d') if from_date else datetime(2017, 8, 1)
t = datetime.strptime(to_date, '%Y-%m-%d') if to_date else datetime.now()
t = t + timedelta(days=1) # To receive the whole day
return f, t
def _get_count_per_track(self, user_name, from_date, to_date):
plays_per_track = []
counts = db.session.\
query(db.func.count(Play.track_id).label('cnt'), Play.track_id).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
group_by(Play.track_id).\
order_by(db.desc('cnt')).\
limit(self.N).\
all()
for count, track_id in counts:
track = Track.query.get(track_id)
plays_per_track.append({'count': count, 'track': track.to_dict()})
return {'data': plays_per_track}
def _get_count_per_artist(self, user_name, from_date, to_date):
plays_per_artist = []
counts = db.session.\
query(db.func.count(Artist.artist_id).label('cnt'), Artist.artist_id).\
select_from(Play).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
join(Play.track).\
join(Track.artists).\
group_by(Artist.artist_id).\
order_by(db.desc('cnt')).\
limit(self.N).\
all()
for count, artist_id in counts:
artist = Artist.query.get(artist_id)
plays_per_artist.append({'count': count, 'artist': artist.to_dict()})
return {'data': plays_per_artist}
def _get_count_per_album(self, user_name, from_date, to_date):
plays_per_album = []
counts = db.session.\
query(db.func.count(Album.album_id).label('cnt'), Album.album_id).\
select_from(Play).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
join(Play.track).\
join(Track.album).\
group_by(Album.album_id).\
order_by(db.desc('cnt')).\
limit(self.N).\
all()
for count, album_id in counts:
album = Album.query.get(album_id)
plays_per_album.append({'count': count, 'album': album.to_dict()})
return {'data': plays_per_album}
def _get_count_per_day(self, user_name, from_date, to_date):
plays_per_day = dict()
counts = db.session.\
query(db.func.count(Play.day_of_week).label('cnt'), Play.day_of_week).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
group_by(Play.day_of_week).\
order_by(db.asc(Play.day_of_week)).\
limit(self.N).\
all()
for count, day in counts:
plays_per_day[day] = count
return {'data': plays_per_day}
def _get_count_per_hour(self, user_name, from_date, to_date):
plays_per_hour = dict()
counts = db.session.\
query(db.func.count(Play.hour).label('cnt'), Play.hour).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
group_by(Play.hour).\
order_by(db.asc(Play.hour)).\
limit(self.N).\
all()
for count, hour in counts:
plays_per_hour[hour] = count
return {'data': plays_per_hour}
def _get_count_per_month(self, user_name, from_date, to_date):
plays_per_month = dict()
counts = db.session.\
query(db.func.count(Play.month).label('cnt'), Play.month).\
filter_by(user_name=user_name).\
filter(Play.played_at_cet >= from_date).\
filter(Play.played_at_cet <= to_date).\
group_by(Play.month).\
order_by(db.asc(Play.month)).\
limit(self.N).\
all()
for count, month in counts:
plays_per_month[month] = count
return {'data': plays_per_month}
def _get_data_by_unit(self, unit, user_name, from_date, to_date):
UNIT_MAPPING = {
'artist': self._get_count_per_artist,
'track': self._get_count_per_track,
'album': self._get_count_per_album,
'hour': self._get_count_per_hour,
'day': self._get_count_per_day,
'month': self._get_count_per_month,
}
if unit in UNIT_MAPPING:
return UNIT_MAPPING[unit](user_name, from_date, to_date)
return {}
def get(self, unit, user_name, from_date=None, to_date=None):
from_date, to_date = arg_date_to_datetime(from_date, to_date)
data = self._get_data_by_unit(unit, user_name, from_date, to_date)
data.update(self._apply_meta_data(unit, user_name, from_date, to_date, resource='count'))
response = jsonify(data)
response.headers.add('Access-Control-Allow-Origin', '*')
return response
class AudioFeature(Resource, ResourceMixin):
def _get_audio_feature_per_month(self, user_name, from_date, to_date):
sql = """SELECT
avg((t_track.audio_feature_data->>'tempo') :: FLOAT) AS avg_tempo,
avg((t_track.audio_feature_data->>'energy') :: FLOAT) AS avg_energy,
avg((t_track.audio_feature_data->>'valence') :: FLOAT) AS avg_valence,
avg((t_track.audio_feature_data->>'key') :: FLOAT) AS avg_key,
avg((t_track.audio_feature_data->>'loudness') :: FLOAT) AS avg_loudness,
t_play.month
FROM
t_play
JOIN t_track ON t_play.track_id = t_track.track_id
WHERE t_play.user_name = '{}'
AND t_play.played_at_cet >= '{}-{}-{}'
AND t_play.played_at_cet <= '{}-{}-{}'
GROUP BY t_play.month
ORDER BY t_play.month ASC"""
rows = db.session.execute(sql.format(user_name,
from_date.year,
from_date.month,
from_date.day,
to_date.year,
to_date.month,
to_date.day))
return self._rows_to_data(rows)
def _get_audio_feature_per_day(self, user_name, from_date, to_date):
sql = """SELECT
avg((t_track.audio_feature_data->>'tempo') :: FLOAT) AS avg_tempo,
avg((t_track.audio_feature_data->>'energy') :: FLOAT) AS avg_energy,
avg((t_track.audio_feature_data->>'valence') :: FLOAT) AS avg_valence,
avg((t_track.audio_feature_data->>'key') :: FLOAT) AS avg_key,
avg((t_track.audio_feature_data->>'loudness') :: FLOAT) AS avg_loudness,
t_play.day_of_week
FROM
t_play
JOIN t_track ON t_play.track_id = t_track.track_id
WHERE t_play.user_name = '{}'
AND t_play.played_at_cet >= '{}-{}-{}'
AND t_play.played_at_cet <= '{}-{}-{}'
GROUP BY t_play.day_of_week
ORDER BY t_play.day_of_week ASC"""
rows = db.session.execute(sql.format(user_name,
from_date.year,
from_date.month,
from_date.day,
to_date.year,
to_date.month,
to_date.day))
return self._rows_to_data(rows)
def _get_audio_feature_per_hour(self, user_name, from_date, to_date):
sql = """SELECT
avg((t_track.audio_feature_data->>'tempo') :: FLOAT) AS avg_tempo,
avg((t_track.audio_feature_data->>'energy') :: FLOAT) AS avg_energy,
avg((t_track.audio_feature_data->>'valence') :: FLOAT) AS avg_valence,
avg((t_track.audio_feature_data->>'key') :: FLOAT) AS avg_key,
avg((t_track.audio_feature_data->>'loudness') :: FLOAT) AS avg_loudness,
t_play.hour
FROM
t_play
JOIN t_track ON t_play.track_id = t_track.track_id
WHERE t_play.user_name = '{}'
AND t_play.played_at_cet >= '{}-{}-{}'
AND t_play.played_at_cet <= '{}-{}-{}'
GROUP BY t_play.hour
ORDER BY t_play.hour ASC"""
rows = db.session.execute(sql.format(user_name,
from_date.year,
from_date.month,
from_date.day,
to_date.year,
to_date.month,
to_date.day))
return self._rows_to_data(rows)
def _rows_to_data(self, rows):
result = dict()
for row in rows:
result[str(row[5])] = {
'avg_tempo': row[0],
'avg_energy': row[1],
'avg_valence': row[2],
'avg_key': row[3],
'avg_loudness': row[4]
}
return {'data': result}
def _get_data_by_unit(self, unit, user_name, from_date, to_date):
UNIT_MAPPING = {
'hour': self._get_audio_feature_per_hour,
'day': self._get_audio_feature_per_day,
'month': self._get_audio_feature_per_month,
}
if unit in UNIT_MAPPING:
return UNIT_MAPPING[unit](user_name, from_date, to_date)
return {}
def get(self, unit, user_name, from_date=None, to_date=None):
from_date, to_date = arg_date_to_datetime(from_date, to_date)
data = self._get_data_by_unit(unit, user_name, from_date, to_date)
data.update(self._apply_meta_data(unit, user_name, from_date, to_date, resource='audio_feature'))
response = jsonify(data)
response.headers.add('Access-Control-Allow-Origin', '*')
return response