Skip to content

Commit e5c8d56

Browse files
committed
mostly working, pre-cleanup
1 parent 6d5b2e9 commit e5c8d56

File tree

4 files changed

+81
-28
lines changed

4 files changed

+81
-28
lines changed

audiomanager.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ def bytestream_from_unknown_mp3(mp3_path):
77
base_name = os.path.basename(mp3_path)
88
base_name_no_ext = base_name[:base_name.rindex('.')]
99

10-
full_song = AudioSegment.from_mp3(mp3_path)
11-
first_5_seconds = full_song[:5000]
10+
# full_song = AudioSegment.from_mp3(mp3_path)
11+
full_song = AudioSegment.from_file(mp3_path)
12+
first_5_seconds = full_song[10000:15000]
1213

1314
extra_params = ["-ar", "44100", "-ac", "1"]
1415
first_5_seconds.export(base_name_no_ext + '.raw', format='s16le', codec='pcm_s16le', parameters=extra_params)

filemanager.py

+40-10
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,23 @@
22
import music_tag
33
import eyed3
44
from eyed3.id3.frames import ImageFrame
5-
# delete all raw files in directory for cleanup
6-
#maybe one for album artwork? would be cool
75

86
def music_file_with_missing_attributes(filepath):
97
if os.path.splitext(filepath)[1] != '.mp3':
108
return False
119

1210
file = music_tag.load_file(filepath)
13-
for key in ["title", "artist", "albumartist", "album"]:
11+
for key in ["title", "artist", "albumartist", "album", "genre", "year", "tracknumber"]:
12+
# for key in ["year"]:
1413
if not field_is_valid(file[key]):
1514
return True
1615
return False
1716

1817

1918
def field_is_valid(metadata_item):
19+
if type(metadata_item.value) == int:
20+
#todo this check isn't correct
21+
return True
2022
return len(metadata_item.value) > 0
2123

2224

@@ -35,12 +37,38 @@ def write_file_metadata(filepath, song_details, album_details):
3537
file['albumartist'] = album_details['data'][0]['attributes']['artistName']
3638
file['title'] = song_details['title']
3739
file['album'] = album_details['data'][0]['attributes']['name']
40+
file['genre'] = song_details['genres']['primary']
41+
file.raw['tracknumber'] = retrieve_track_number(song_details['title'], album_details)
42+
# file.raw['year'] = album_details['data'][0]['attributes']['releaseDate'][0:4]
43+
file['year'] = int(album_details['data'][0]['attributes']['releaseDate'][0:4])
44+
# f = eyed3.load(filepath)
45+
# f.initTag()
46+
# f.tag.year = int(album_details['data'][0]['attributes']['releaseDate'][0:4])
47+
# f.tag.save()
48+
# time.sleep(5)
49+
#year field is written but only displays when we view it first in the debugger
50+
# _ = file['year']
3851
file.save()
3952

4053

54+
def retrieve_track_number(song_title, album_details):
55+
song_list = album_details['data'][0]['relationships']['tracks']['data']
56+
57+
res = -1
58+
for idx, song in enumerate(song_list):
59+
if song['attributes']['name'] == song_title:
60+
res = idx + 1
61+
break
62+
63+
if res < 10:
64+
return '0' + str(res)
65+
return str(res)
66+
67+
4168
def rename_file(filepath, song_details):
4269
working_dir = os.path.dirname(filepath)
43-
os.rename(filepath, os.path.join(working_dir, song_details['title'] + '.mp3'))
70+
if not os.path.exists(os.path.join(working_dir, song_details['title'] + '.mp3')):
71+
os.rename(filepath, os.path.join(working_dir, song_details['title'] + '.mp3'))
4472

4573

4674
def add_album_artwork(filepath):
@@ -61,12 +89,14 @@ def add_album_artwork(filepath):
6189
def cleanup_raw_files():
6290
curr_dir = os.path.dirname(os.path.realpath(__file__))
6391

64-
for filename in os.listdir(curr_dir):
65-
if filename.endswith('.raw'):
66-
os.remove(os.path.join(curr_dir, filename))
92+
for root, dirs, files in os.walk(curr_dir):
93+
for filename in files:
94+
if filename.endswith('.raw'):
95+
os.remove(os.path.join(curr_dir, filename))
6796

6897

6998
def cleanup_jpg_files(working_dir):
70-
for filename in os.listdir(working_dir):
71-
if filename.endswith('.jpg'):
72-
os.remove(os.path.join(working_dir, filename))
99+
for root, dirs, files in os.walk(working_dir):
100+
for filename in files:
101+
if filename.endswith('.jpg'):
102+
os.remove(os.path.join(root, filename))

main.py

+36-14
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,46 @@
1+
import pydub.exceptions
2+
import requests
3+
14
from shazammanager import ShazamManager
25
from audiomanager import bytestream_from_unknown_mp3
36
from filemanager import find_candidate_files, write_file_metadata, rename_file, cleanup_raw_files, add_album_artwork, cleanup_jpg_files
47

58

6-
sm = ShazamManager()
7-
8-
for filepath in find_candidate_files("C:\\Users\\bennu\\OneDrive\\Desktop\\test_dir"):
9-
b = bytestream_from_unknown_mp3(filepath)
10-
song_id = sm.detect_raw_audio(b)['matches'][0]['id']
11-
song_details = sm.get_details_from_song_id(song_id)
12-
album_id = song_details['albumadamid']
13-
album_details = sm.get_album_details_from_album_id(album_id)
14-
15-
sm.get_album_artwork(filepath, song_details)
16-
write_file_metadata(filepath, song_details, album_details)
17-
add_album_artwork(filepath)
18-
rename_file(filepath, song_details)
9+
CLEANUP_DIRECTORY = "C:\\Users\\bennu\\OneDrive\\Desktop\\Chelsea_Phone\\test"
1910

11+
sm = ShazamManager()
12+
for filepath in find_candidate_files(CLEANUP_DIRECTORY):
13+
try:
14+
b = bytestream_from_unknown_mp3(filepath)
15+
song_id = sm.detect_raw_audio(b)['matches'][0]['id']
16+
song_details = sm.get_details_from_song_id(song_id)
17+
album_id = song_details['albumadamid']
18+
album_details = sm.get_album_details_from_album_id(album_id)
19+
20+
sm.get_album_artwork(filepath, song_details)
21+
write_file_metadata(filepath, song_details, album_details)
22+
add_album_artwork(filepath)
23+
rename_file(filepath, song_details)
24+
except requests.HTTPError:
25+
print("Bad API response when processing " + filepath + ". Continuing..")
26+
continue
27+
except KeyError:
28+
print("Incomplete Metadata for " + filepath + ". Continuing..")
29+
continue
30+
except IndexError:
31+
#todo why are we getting this when we have good response?
32+
# we had no matches from shazam API so we get a key error when trying to ID the song on ln 15
33+
print("??? " + filepath + ". Continuing..")
34+
continue
35+
except FileNotFoundError:
36+
print("Bad path? " + filepath + ". Continuing..")
37+
continue
38+
except pydub.exceptions.CouldntDecodeError:
39+
# might be fixed by the code change to from_file??
40+
print("WTF mate?")
41+
continue
2042

2143
cleanup_raw_files()
22-
cleanup_jpg_files("C:\\Users\\bennu\\OneDrive\\Desktop\\test_dir")
44+
cleanup_jpg_files(CLEANUP_DIRECTORY)
2345

2446

shazammanager.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ def __init__(self):
2525
def get_from_api(self, endpoint_url, querystring):
2626
response = requests.request("GET", endpoint_url, headers=self.headers_get, params=querystring)
2727

28-
# TODO this is broken if we don't get a match, harden this
28+
response.raise_for_status()
2929
return json.loads(response.text)
3030

3131
def post_to_api(self, endpoint_url, data):
3232
response = requests.request("POST", endpoint_url, data=data, headers=self.headers_post)
3333

34-
# TODO this is broken if we don't get a match, harden this
34+
response.raise_for_status()
3535
return json.loads(response.text)
3636

3737
def detect_raw_audio(self, bytestream):

0 commit comments

Comments
 (0)