-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
266 lines (220 loc) · 7.99 KB
/
app.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
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse
from beetsstatistics import AlbumSort, BeetsStatistics, DBNotFoundError, DBQueryError
import humanize
from fastapi import Depends
from typing import Annotated
from pydantic_settings import BaseSettings
from fastapi import HTTPException
import logging
from urllib.parse import quote_plus
logger = logging.getLogger("uvicorn.error")
class InitializationError(Exception):
pass
class Settings(BaseSettings):
musiclibrary_db: str
beets_statistics = None
async def get_beets_statistics():
global beets_statistics
try:
beets_statistics = BeetsStatistics(settings.musiclibrary_db)
if beets_statistics.get_db_connection() is None:
raise InitializationError("Could not get access database file.")
except (DBNotFoundError, DBQueryError) as e:
raise HTTPException(
status_code=500,
detail="Could not find find or access database file: {}".format(e),
)
try:
yield beets_statistics
finally:
beets_statistics.close()
settings = Settings()
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
templates.env.filters['quote_plus'] = lambda u: quote_plus(u)
@app.get("/", response_class=HTMLResponse)
async def get_general_stats(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
try:
track_count = beets_statistics.get_track_count()
album_count = beets_statistics.get_album_count()
playback_length = beets_statistics.get_playback_length()
playback_length_str = humanize.precisedelta(playback_length)
file_size_str = humanize.naturalsize(beets_statistics.get_file_size())
avg_bpm = beets_statistics.get_avg_bpm()
format_count, lossless, lossy, unknown = beets_statistics.get_track_formats()
except (DBQueryError, DBNotFoundError) as e:
raise HTTPException(
status_code=500, detail="Could not query general statistics: {}".format(e)
)
return templates.TemplateResponse(
request=request,
name="index.html",
context={
"track_count": track_count,
"album_count": album_count,
"playback_length": playback_length_str,
"file_size": file_size_str,
"avg_bpm": avg_bpm,
"format_count": format_count,
"lossless": lossless,
"lossy": lossy,
"unknown": unknown,
},
)
@app.get("/albums", response_class=HTMLResponse)
async def get_album_stats(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
sort_by: AlbumSort = AlbumSort.ARTIST,
):
albums = beets_statistics.get_albums_from_db(sort_by=sort_by)
return templates.TemplateResponse(
request=request, name="albums.html", context={"albums": albums}
)
@app.get("/genres", response_class=HTMLResponse)
async def get_genre_count(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
genres = beets_statistics.get_genre_count(limit=20)
genre_list = []
count_list = []
for genre in genres[0]:
genre_list.append(genre["genre"])
count_list.append(genre["count"])
return templates.TemplateResponse(
request=request,
name="genres.html",
context={"genres": genres, "genre_list": genre_list, "count_list": count_list},
)
@app.get("/artists", response_class=HTMLResponse)
async def get_artist_stats(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
artists = beets_statistics.get_artist_stats(limit=100)
artist_list = []
count_list = []
for artist in artists:
artist_list.append(artist["artist"])
count_list.append(artist["track_count"])
count = beets_statistics.get_track_count()
return templates.TemplateResponse(
request=request,
name="artists.html",
context={
"artists": artists,
"track_count": count,
"artist_list": artist_list,
"count_list": count_list,
},
)
@app.get("/decades", response_class=HTMLResponse)
async def get_track_decades(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
decades = beets_statistics.get_track_decades()
return templates.TemplateResponse(
request=request,
name="decades.html",
context={"decades": decades},
)
@app.get("/quality", response_class=HTMLResponse)
async def get_track_quality(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
bitrates = beets_statistics.get_track_quality()
return templates.TemplateResponse(
request=request,
name="quality.html",
context={"bitrates": bitrates},
)
@app.get("/genre-decade-heatmap", response_class=HTMLResponse)
async def get_genre_decade_heatmap(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
results = beets_statistics.get_genre_decade_heatmap()
min_decade = 9999
max_decade = 0
heatmap = {}
genre_list = []
for result in results:
decade = result["decade"]
count = result["count"]
genre = result["genre"]
if genre not in genre_list:
genre_list.append(genre)
min_decade = min(min_decade, decade)
max_decade = max(max_decade, decade)
if genre not in heatmap:
heatmap[genre] = {}
heatmap[genre][decade] = count
# Fill out sparse table
for genre in heatmap:
for decade in range(min_decade, max_decade + 1, 10):
if decade not in heatmap[genre]:
heatmap[genre][decade] = 0
# Sort z values per genre
for genre in heatmap:
sorted_genre = dict(sorted(heatmap[genre].items()))
heatmap[genre] = sorted_genre
return templates.TemplateResponse(
request=request,
name="genre-decade-heatmap.html",
context={
"heatmap": heatmap,
"decades": range(min_decade, max_decade + 1, 10),
"genre_list": genre_list,
},
)
@app.get("/cover/{album_id}", response_class=FileResponse)
async def get_album_cover(
album_id: str,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
album_cover_path = beets_statistics.get_album_cover_path(album_id)
if album_cover_path is None:
album_cover_path = "static/blank.png"
return album_cover_path
@app.get("/added-timeline", response_class=HTMLResponse)
async def get_added_timeline(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
timeline = beets_statistics.get_added_timeline()
return templates.TemplateResponse(
request=request,
name="added-timeline.html",
context={"timeline": timeline},
)
@app.get("/duplicates", response_class=HTMLResponse)
async def get_duplicates(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
duplicates = beets_statistics.get_duplicates()
return templates.TemplateResponse(
request=request, name="duplicates.html", context={"duplicates": duplicates}
)
@app.get("/not-in-mb", response_class=HTMLResponse)
async def get_not_in_mb(
request: Request,
beets_statistics: Annotated[BeetsStatistics, Depends(get_beets_statistics)],
):
items_not_in_mb = beets_statistics.get_items_not_in_mb()
albums_not_in_mb = beets_statistics.get_albums_not_in_mb()
return templates.TemplateResponse(
request=request,
name="not-in-mb.html",
context={"tracks": items_not_in_mb, "albums": albums_not_in_mb},
)