Compare commits
3 Commits
c82c7b74ac
...
9dd4f2318e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dd4f2318e | ||
|
|
00125b1f3f | ||
|
|
e3c8be9eb8 |
123
make_folders.py
123
make_folders.py
@@ -85,22 +85,20 @@ def search_google_images_and_save(x: str, audio):
|
|||||||
audio.save(x)
|
audio.save(x)
|
||||||
|
|
||||||
found_image = False
|
found_image = False
|
||||||
|
# Try album art search first
|
||||||
if (check_tag(audio, x, "TALB","album")):
|
if (check_tag(audio, x, "TALB","album")):
|
||||||
# search for artist and album
|
|
||||||
if x.endswith(".flac"):
|
if x.endswith(".flac"):
|
||||||
songpath = join(".",str(audio["artist"]),str(audio["album"]))
|
songpath = join(".",str(audio["artist"]),str(audio["album"]))
|
||||||
else:
|
else:
|
||||||
# Use TPE2 if available, otherwise fallback to TPE1
|
|
||||||
artist_folder = str(audio.get("TPE2", audio.get("TPE1", "Unknown Artist")))
|
artist_folder = str(audio.get("TPE2", audio.get("TPE1", "Unknown Artist")))
|
||||||
songpath = join(".", artist_folder, str(audio["TALB"]))
|
songpath = join(".", artist_folder, str(audio["TALB"]))
|
||||||
if "\x00" in songpath:
|
if "\x00" in songpath:
|
||||||
# having null bytes in os.replace will throw an error
|
|
||||||
songpath = songpath.replace("\x00",", ")
|
songpath = songpath.replace("\x00",", ")
|
||||||
make_folder(songpath)
|
make_folder(songpath)
|
||||||
os.replace(join(".",x),join(songpath,x))
|
os.replace(join(".",x),join(songpath,x))
|
||||||
google_keyword = ""
|
|
||||||
if x.endswith(".flac"):
|
if x.endswith(".flac"):
|
||||||
google_keyword = str(audio.get("artist", "Unknown Artist")) + " " + str(audio.get("album", "Unknown Album")) + " album"
|
artist_val = str(audio.get("artist", "Unknown Artist"))
|
||||||
|
album_val = str(audio.get("album", "Unknown Album"))
|
||||||
else:
|
else:
|
||||||
artist_val = str(audio.get("TPE2", audio.get("TPE1", "Unknown Artist")))
|
artist_val = str(audio.get("TPE2", audio.get("TPE1", "Unknown Artist")))
|
||||||
album_val = str(audio.get("TALB", "Unknown Album"))
|
album_val = str(audio.get("TALB", "Unknown Album"))
|
||||||
@@ -108,46 +106,38 @@ def search_google_images_and_save(x: str, audio):
|
|||||||
logging.info("Moved file! Now searching for album art... keyword is " + google_keyword)
|
logging.info("Moved file! Now searching for album art... keyword is " + google_keyword)
|
||||||
google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
|
google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
|
||||||
try:
|
try:
|
||||||
google_Crawler.crawl(keyword = google_keyword, max_num = 1)
|
result = google_Crawler.crawl(keyword = google_keyword, max_num = 1)
|
||||||
found_image = True
|
found_image = True
|
||||||
except:
|
except Exception as e:
|
||||||
logging.info("could not find Google result by album, searching by track and artist")
|
logging.info(f"could not find Google result by album, searching by track and artist: {e}")
|
||||||
if (found_image):
|
# Fallback: if no image found, try searching by song and artist
|
||||||
logging.info("changing name of cover art file...")
|
if not found_image or not any(f.split('.')[-1].lower() in ["jpg","png"] for f in listdir(songpath)):
|
||||||
logging.info(songpath)
|
song_keyword = artist_val + " " + str(audio.get("TIT2", ""))
|
||||||
|
logging.info("Fallback: searching for song art... keyword is " + song_keyword)
|
||||||
|
try:
|
||||||
|
google_Crawler.crawl(keyword = song_keyword, max_num = 1)
|
||||||
|
found_image = True
|
||||||
|
except Exception as e:
|
||||||
|
logging.info(f"could not find Google result by song: {e}")
|
||||||
|
# Rename cover art file if found
|
||||||
for f in listdir(songpath):
|
for f in listdir(songpath):
|
||||||
logging.info(f)
|
|
||||||
if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
|
if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
|
||||||
os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
|
os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
|
||||||
logging.info("Done!")
|
logging.info("Done!")
|
||||||
#TODO search for song name and artist if album not found on google images
|
|
||||||
# else:
|
|
||||||
# songpath = join(".",str(audio["TPE1"]),str(audio["TIT2"]))
|
|
||||||
# make_folder(songpath)
|
|
||||||
# os.replace(join(".",x),join(songpath,x))
|
|
||||||
# logging.info("Moved file! Now searching for album art... keyword is " + str(audio["TPE1"]) + " " + str(audio["TIT2"]))
|
|
||||||
# google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
|
|
||||||
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# search for song name and artist
|
# search for song name and artist
|
||||||
# search for artist and album
|
songpath = join(".",str(audio.get("TPE2", "Unknown Artist")),str(audio.get("TIT2", "Unknown Title")))
|
||||||
# use TPE2 (album artist), because we want to find the album
|
|
||||||
songpath = join(".",str(audio["TPE2"]),str(audio["TIT2"]))
|
|
||||||
make_folder(songpath)
|
make_folder(songpath)
|
||||||
os.replace(join(".",x),join(songpath,x))
|
os.replace(join(".",x),join(songpath,x))
|
||||||
logging.info("Moved file! Now searching for album art... keyword is " + str(audio["TPE2"]) + " " + str(audio["TIT2"]))
|
song_keyword = str(audio.get("TPE2", "Unknown Artist")) + " " + str(audio.get("TIT2", "Unknown Title"))
|
||||||
|
logging.info("Moved file! Now searching for album art... keyword is " + song_keyword)
|
||||||
google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
|
google_Crawler = GoogleImageCrawler(storage = {'root_dir': songpath})
|
||||||
try:
|
try:
|
||||||
google_Crawler.crawl(keyword = str(audio["TPE2"]) + " " + str(audio["TIT2"]), max_num = 1)
|
google_Crawler.crawl(keyword = song_keyword, max_num = 1)
|
||||||
found_image = True
|
found_image = True
|
||||||
except:
|
except Exception as e:
|
||||||
logging.info("could not find Google result by track and artist")
|
logging.info(f"could not find Google result by track and artist: {e}")
|
||||||
if (found_image):
|
|
||||||
logging.info("changing name of cover art file...")
|
|
||||||
logging.info(songpath)
|
|
||||||
for f in listdir(songpath):
|
for f in listdir(songpath):
|
||||||
logging.info(f)
|
|
||||||
if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
|
if (isfile(join(songpath,f)) and f.split(".")[-1].lower() in ["jpg","png"]):
|
||||||
os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
|
os.replace(join(songpath,f),join(songpath,"Cover." + f.split(".")[-1].lower()))
|
||||||
logging.info("Done!")
|
logging.info("Done!")
|
||||||
@@ -236,25 +226,24 @@ def check_title_songname(x: str, audio):
|
|||||||
logging.info("Detected ' - Topic - ' in name, removing 'Topic'.")
|
logging.info("Detected ' - Topic - ' in name, removing 'Topic'.")
|
||||||
# Rebuild items without 'Topic'
|
# Rebuild items without 'Topic'
|
||||||
items = [items[0]] + items[2:]
|
items = [items[0]] + items[2:]
|
||||||
if (len(items) > 2):
|
# Set artist and title tags robustly
|
||||||
logging.info("song title has more than 1 part after the -: " + str(items))
|
if len(items) == 2:
|
||||||
if (items[1].count(".mp3") >= 1):
|
artist, title = items[0].strip(), items[1].strip()
|
||||||
logging.info("setting TIT2 tag to: " + str(items[1].strip().rstrip().rsplit(".")[0])) # get second part of title and remove the file extension
|
elif len(items) > 2:
|
||||||
audio["TIT2"] = TIT2(encoding=3,text=str(items[1].strip().rstrip().rsplit(".")[0]))
|
artist, title = items[0].strip(), items[1].strip()
|
||||||
elif (items[1].count(".flac") >= 1):
|
|
||||||
logging.info("setting title tag to " + str(items[1].strip().rstrip().rsplit(".")[0])) # get second part of title and remove the file extension
|
|
||||||
audio["title"] = str(items[1].strip().rstrip().rsplit(".")[0])
|
|
||||||
else:
|
else:
|
||||||
logging.info("title: " + str(items[1].strip().rstrip())) # get second part of title and remove the file extension
|
artist, title = x.strip(), x.strip()
|
||||||
audio["TIT2"] = TIT2(encoding=3,text=str(items[1].strip().rstrip()))
|
# Set both TPE1 (song artist) and TPE2 (album artist)
|
||||||
audio["title"] = TIT2(encoding=3,text=str(items[1].strip().rstrip()))
|
audio["TPE1"] = TPE1(encoding=3, text=artist)
|
||||||
else:
|
audio["TPE2"] = TPE2(encoding=3, text=artist)
|
||||||
logging.info("song title has only 1 part after the -: " + items[1])
|
# Only set 'artist' as a string for FLAC, not for MP3
|
||||||
if ("TIT2" not in audio.keys()):
|
if hasattr(audio, 'mime') and audio.mime and 'flac' in audio.mime[0].lower():
|
||||||
song_title = items[1].strip().rstrip()
|
audio["artist"] = artist
|
||||||
logging.info("TIT2 tag not found, creating it. Using song title: " + song_title)
|
# Set title tags
|
||||||
audio["TIT2"] = TIT2(encoding=3,text=song_title)
|
audio["TIT2"] = TIT2(encoding=3, text=title)
|
||||||
audio["title"] = TIT2(encoding=3,text=song_title)
|
if hasattr(audio, 'mime') and audio.mime and 'flac' in audio.mime[0].lower():
|
||||||
|
audio["title"] = title
|
||||||
|
logging.info(f"Set artist: {artist}, title: {title}")
|
||||||
else:
|
else:
|
||||||
logging.info("no - found in title, setting full name as title: " + x)
|
logging.info("no - found in title, setting full name as title: " + x)
|
||||||
if ("TIT2" not in audio.keys()):
|
if ("TIT2" not in audio.keys()):
|
||||||
@@ -295,15 +284,18 @@ def check_for_multiple_artists(audio, filename: str, name: str):
|
|||||||
def check_artist_songname(x: str, audio):
|
def check_artist_songname(x: str, audio):
|
||||||
items = x.split(" - ")
|
items = x.split(" - ")
|
||||||
logging.info("Checking artist by name. items: " + str(items))
|
logging.info("Checking artist by name. items: " + str(items))
|
||||||
if (len(items) > 2):
|
# Remove 'Topic' if present
|
||||||
check_for_multiple_artists(audio, x, items[0].strip())
|
if len(items) > 2 and items[1].strip().lower() == "topic":
|
||||||
|
logging.info("Detected ' - Topic - ' in name, removing 'Topic'.")
|
||||||
else: # no multiple artists in name
|
items = [items[0]] + items[2:]
|
||||||
logging.info("Setting artist tags TPE1 and TPE2 to " + str(items[0].strip().rstrip()))
|
artist = items[0].strip()
|
||||||
|
# Set both TPE1 (song artist) and TPE2 (album artist)
|
||||||
audio["TPE1"] = TPE1(encoding=3,text=str(items[0].strip().rstrip()))
|
audio["TPE1"] = TPE1(encoding=3, text=artist)
|
||||||
audio["TPE2"] = TPE2(encoding=3,text=str(items[0].strip().rstrip()))
|
audio["TPE2"] = TPE2(encoding=3, text=artist)
|
||||||
audio["artist"] = audio["TPE1"]
|
# Only set 'artist' as a string for FLAC, not for MP3
|
||||||
|
if hasattr(audio, 'mime') and audio.mime and 'flac' in audio.mime[0].lower():
|
||||||
|
audio["artist"] = artist
|
||||||
|
logging.info(f"Set artist tags TPE1 and TPE2 to {artist}")
|
||||||
|
|
||||||
def check_artist(audio, filename: str) -> bool:
|
def check_artist(audio, filename: str) -> bool:
|
||||||
res = False
|
res = False
|
||||||
@@ -682,6 +674,19 @@ def check_spotify_and_save(spotify, audio,x: str) -> bool:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
# Preprocess: rename files with '- Topic -' in the name to 'artist - title'
|
||||||
|
for fname in [f for f in listdir(".") if isfile(join(".",f)) and "- Topic -" in f]:
|
||||||
|
parts = fname.rsplit("- Topic -", 1)
|
||||||
|
if len(parts) == 2:
|
||||||
|
artist = parts[0].strip().rstrip("- ")
|
||||||
|
title = parts[1].rsplit('.', 1)[0].strip()
|
||||||
|
ext = fname.rsplit('.', 1)[-1]
|
||||||
|
new_name = f"{artist} - {title}.{ext}"
|
||||||
|
if not os.path.exists(new_name):
|
||||||
|
logging.info(f"Renaming file '{fname}' to '{new_name}'")
|
||||||
|
os.rename(fname, new_name)
|
||||||
|
else:
|
||||||
|
logging.warning(f"Target filename '{new_name}' already exists. Skipping rename for '{fname}'")
|
||||||
|
|
||||||
# for spotipy to be able to log in, the environment variables SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET have to be set
|
# for spotipy to be able to log in, the environment variables SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET have to be set
|
||||||
# these can be obtained from the spotify developer dashboard
|
# these can be obtained from the spotify developer dashboard
|
||||||
|
|||||||
Reference in New Issue
Block a user