Exemplo n.º 1
0
def _audio_tcmp(atuple):
    audio, atag, advanced, _, _ = atuple
    if advanced:
        param = ast.literal_eval(atag)
        audio.add(TCMP(3, param[1]))
    else:
        audio.add(TCMP(3, atag))
Exemplo n.º 2
0
def mp3_tag(mp3_dirname, mp3_filename, artist, album, track, tracks, title, year, genre, bpms, compilation):
	# Delete existing tags
	try:
		id3 = ID3(mp3_filename)
		id3.delete()
	except ID3NoHeaderError:
		id3 = ID3()
	
	# Artist
	id3.add(TPE1(encoding=3, text=artist))
	
	# Artistsort
	id3.add(TSOP(encoding=3, text=artist))
	
	# Band
	id3.add(TPE2(encoding=3, text=artist))
	
	# Composer
	id3.add(TCOM(encoding=3, text=artist))
	
	# Album
	id3.add(TALB(encoding=3, text=album))
	
	# Albumsort
	id3.add(TSOA(encoding=3, text=album))
	
	# Track
	id3.add(TRCK(encoding=3, text=tracks))
	
	# Title
	id3.add(TIT2(encoding=3, text=title))
	
	# Year
	id3.add(TDRC(encoding=3, text=year))
	
	# Genre
	id3.add(TCON(encoding=3, text=genre))
	
	# BPMs
	id3.add(TBPM(encoding=3, text=bpms))

	# Compilation
	if (compilation):
		id3.add(TCMP(encoding=3, text='1'))
	else:
		id3.add(TCMP(encoding=3, text='0'))
	
	# Cover
	image = str(mp3_dirname + '/Cover.jpg')
	try:
		imagefile = open(image, 'rb').read()
		id3.add(APIC(3, 'image/jpeg', 3, 'Cover', imagefile))
	except:
		print("Warning. No Cover.jpg in directory " + mp3_dirname + ".")
	
	# Save tags to file
	id3.save(mp3_filename, v2_version=4, v1=2)
Exemplo n.º 3
0
def add_id3_tags(t, file, cover):
	audio = ID3(file)

	# album
	audio.add(TALB(encoding=3, text=u'' + dict_cue['album']))

	# genre
	audio.add(TCON(encoding=3, text=u'' + dict_cue['genre']))

	# year
	audio.add(TYER(encoding=3, text=u'' + dict_cue['year']))

	# compilation
	audio.add(TCMP(encoding=3, text=u'' + str(dict_cue['compilation'])))

	# track number
	audio.add(TRCK(encoding=3, text=u'' + str(t+1) + '/' + str(len(dict_cue['songs']))))

	# artist
	if len(dict_cue['songs'][t]) == 3:
		audio.add(TPE1(encoding=3, text=u'' + dict_cue['songs'][t][1]))
	else:
		audio.add(TPE1(encoding=3, text=u'' + dict_cue['artist']))

	# song title
	if len(dict_cue['songs'][t]) == 3:
		audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][2]))
	else:
		audio.add(TIT2(encoding=3, text=u'' + dict_cue['songs'][t][1]))

	# cover
	if cover:
		audio.add(APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=open(cover, 'rb').read()))

	audio.save()
Exemplo n.º 4
0
def setCompilationTag(srcCompleteFileName):
    """
    set the compilation tag TCMP to file
    """
    mutID3 = ID3(srcCompleteFileName)
    logging.debug("setting compilation tag for " +
                  os.path.basename(srcCompleteFileName))
    mutID3.add(TCMP(encoding=3, text='1'))
    mutID3.save()
Exemplo n.º 5
0
def dumpIt(entry):
    try:
        r = requests.get(entry['source'], stream=True)
    except Exception:
        return
    #filename ='{}.mp3'.format(entry['slug'].encode('utf8'))
    if not 'Content-Length' in r.headers: return
    filename = '{}.mp3'.format(entry['slug'])
    localSize = os.path.getsize(filename) if os.path.isfile(filename) else 0
    remoteSize = int(r.headers['Content-Length'])
    if remoteSize <= localSize:
        print("[skip] filename:{}, local size:{}, remote size:{}".format(
            filename, localSize, remoteSize))
        return
    f = open(filename, 'wb')
    print("[downloading] filename:{}, local size:{}, remote size:{}".format(
        filename, localSize, remoteSize))
    for chunk in r.iter_content(1024):
        f.write(chunk)
    f.truncate()
    f.close()

    #write id3 tags

    try:
        audio = ID3(filename)
    except ID3NoHeaderError:
        audio = ID3()
    audio.add(TIT2(encoding=3, text=entry['title']))
    audio.add(TPE1(encoding=3, text=entry['artist']))
    audio.add(TPE2(encoding=3, text="IndieShuffle"))
    # audio.add(TALB(encoding=3,text="IndieShuffle"))
    audio.add(TCMP(encoding=3, text="1"))
    try:
        r = requests.get(entry['artwork'], stream=True)
        r.raw.decode_content = True
        ####################################################################################################
        #inMemBuffer = BytesIO()
        #with Image.open(r.raw) as img:
        #img.save(inMemBuffer,'png')
        #inMemBuffer.seek(0)
        #encoding=3 is required to enable MacOs preview to show the coverart icon
        #audio.add(APIC(encoding=3,type=3,mime='image/png',data=inMemBuffer.read()))
        ####################################################################################################
        #encoding=3 is required to enable MacOs preview to show the coverart icon
        audio.add(
            APIC(encoding=3, type=3, mime='image/jpeg', data=r.raw.read()))
    except Exception:
        pass
    audio.save(filename)
Exemplo n.º 6
0
def setMetaTag(filename, title, artist, album, track, track_album, pic_data):
    audio = MP3(filename, ID3=ID3)
    try:
        audio.add_tags(ID3=ID3)
    except mutagen.id3.error:
        pass
    audio["TIT2"] = TIT2(encoding=3, text=title)
    audio["TPE1"] = TPE1(encoding=3, text=artist)
    audio["TALB"] = TALB(encoding=3, text=album)
    audio['TCON'] = TCON(encoding=3, text="Deemo")
    audio["TRCK"] = TRCK(encoding=3, text=str(track) + "/" + str(track_album))
    audio["TCMP"] = TCMP(encoding=3, text="1")

    if pic_data is not None:
        audio.tags.add(
            APIC(encoding=3,
                 mime='image/jpeg',
                 type=3,
                 desc=u'Cover',
                 data=pic_data))

    audio.save()
Exemplo n.º 7
0
def download_post(url):
    response = requests.get(
        url,
        headers={
            'User-Agent':
            'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15'
        })

    bs = BeautifulSoup(response.text, 'html5lib')
    title = bs.findSelect('a.fw_post_author')[0].text
    try:
        album = bs.findSelect('.wall_post_text')[0].text.split('\n')[0].strip()
    except IndexError:
        album = ''
    album_id = bs.findSelect('.fw_like_count')[0]['id'].replace(
        'like_count', '')
    try:
        cover = bs.findSelect('.page_media_thumb1 img')[0]['src']
    except IndexError:
        cover = None
    print title, '-', album
    songs = [{
        'url':
        input['value'].split(',')[0],
        'title':
        bs.findSelect('#audio%s .title_wrap' %
                      input['id'].replace('audio_info', ''))[0].text
    } for input in bs.findSelect('input[type=hidden]')
             if input.has_key('id') and input['id'].startswith('audio')]

    # Creating folder
    target_dir = os.path.join('/tmp/vk-post-downloader/', album_id)
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    # Downloading
    print '', title, '-', album_id
    if cover:
        download(cover, target_dir, 'cover.jpg', ' Cover')
        cover_filename = os.path.join(target_dir, 'cover.jpg')

        try:
            from PIL import Image
            image = Image.open(cover_filename)
            size = [min(image.size), min(image.size)]
            background = Image.new('RGBA', size, (255, 255, 255, 0))
            background.paste(image, ((size[0] - image.size[0]) / 2,
                                     (size[1] - image.size[1]) / 2))
            background.save(cover_filename, format='jpeg')
        except ImportError:
            print u'PIL не найден. Вы можете попробовать его установить командой easy_install PIL'
            print u'Ничего страшного, просто прямоугольные картинки для обложки не будут обрезаться до квадратных'

    print ' MP3s:'
    for i, song in enumerate(songs):
        download(song['url'], target_dir, '%d.mp3' % (i + 1),
                 '  - ' + song['title'])

    # Parsing
    for f in os.listdir(target_dir):
        if not f.endswith('.mp3'):
            continue
        filename = os.path.join(target_dir, f)
        try:
            id3 = ID3(filename, translate=False)
        except mutagen.id3.ID3NoHeaderError:
            id3 = mutagen.id3.ID3()
        id3.unknown_frames = getattr(id3, 'unknown_frames', [])
        id3.update_to_v24()
        id3.add(TPE2(encoding=3, text=title))
        if album:
            id3.add(TAL(encoding=3, text=album))
        id3.add(TCMP(encoding=3, text='1'))
        id3.add(TRCK(encoding=3, text=''))
        if cover:
            id3.add(
                APIC(
                    encoding=3,  # 3 is for utf-8
                    mime='image/jpeg',  # image/jpeg or image/png
                    type=3,  # 3 is for the cover image
                    desc=u'Cover',
                    data=open(cover_filename).read()))
        id3.save(filename)
        shutil.copyfile(filename, os.path.join(itunes_autoimport_dir, f))

    os.system('rm -rf %s' % target_dir)