Created
June 24, 2015 14:22
-
-
Save w1ndy/93ddfe9b47a67dbe36fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
from bs4 import BeautifulSoup | |
from mutagen.easymp4 import EasyMP4 | |
from mutagen.flac import FLAC | |
from mutagen.apev2 import APEv2 | |
from mutagen.easyid3 import EasyID3 | |
Path = "" | |
AllowFallbackToRawFileName = True | |
def scanID3(fn): | |
return EasyID3(fn) | |
def scanAPEv2(fn): | |
return APEv2(fn) | |
def scanFLAC(fn): | |
return FLAC(fn) | |
def scanMP4(fn): | |
return EasyMP4(fn) | |
handler = { | |
"mp3": scanID3, | |
"ape": scanAPEv2, | |
"flac": scanFLAC, | |
"m4a": scanMP4, | |
"m4b": scanMP4, | |
"m4p": scanMP4 | |
} | |
def scan(soup, fn, opener): | |
try: | |
tag = opener(fn) | |
if not tag['title'] or not tag['artist']: | |
raise Exception("warning: no tag found, using file name") | |
else: | |
return newTrackTag(soup, tag['title'][0], tag['artist'][0]) | |
except Exception as e: | |
print("Exception occurred when processing", fn, ":", e) | |
if AllowFallbackToRawFileName: | |
return newTrackTag(soup, os.path.basename(fn)) | |
else: | |
return '' | |
def newTrackTag(soup, name, artist=None): | |
tag_file = soup.new_tag('File') | |
tag_type = soup.new_tag('MediaFileType') | |
tag_type.string = '0' | |
tag_name = soup.new_tag('FileName') | |
if artist: | |
tag_name.string = '%s - %s.mp3' % (artist, name) | |
else: | |
tag_name.string = name | |
tag_path = soup.new_tag('FilePath') | |
tag_path.string = '.' | |
tag_file.append(tag_type) | |
tag_file.append(tag_name) | |
tag_file.append(tag_path) | |
return tag_file | |
def main(): | |
soup = BeautifulSoup('<?xml version="1.0" encoding="UTF-8"?>') | |
root = soup.new_tag('List', ListName='Local') | |
unknown_ext = [] | |
scanned, added = 0, 0 | |
for folder, sub, fns in os.walk(Path): | |
for fn in fns: | |
p = os.path.join(folder, fn) | |
scanned += 1 | |
result = re.findall(r"\.([0-9A-Za-z]+)$", fn) | |
if result: | |
ext = result[0].lower() | |
if ext in handler: | |
print("Scanning", p) | |
root.append(scan(soup, p, handler[ext])) | |
added += 1 | |
else: | |
if not ext in unknown_ext: | |
unknown_ext.append(ext) | |
else: | |
print("No extension found in", p) | |
print("%d of %d added, unknown extensions:" % (added, scanned), unknown_ext if unknown_ext else "none") | |
soup.append(root) | |
open("local.kgl", "w").write(soup.prettify()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment