Example #1
0
def _audio_trck(atuple):
    audio, atag, advanced, _, _ = atuple
    if advanced:
        param = ast.literal_eval(atag)
        audio.add(TRCK(3, param[1]))
    else:
        audio.add(TRCK(3, atag))
    def add_tags(self):
        self.logger.debug("Started adding tags to YouTube tracks")
        tag_count = 0
        downloaded_track: DownloadedTrack
        for downloaded_track in self.all_tracks_to_download:
            if "name" in downloaded_track.youtube_tags:
                file_path = Path(downloaded_track.youtube_tags["filepath"])

                try:
                    tagged_file = ID3()
                except mutagen.id3.ID3NoHeaderError:
                    tagged_file = File()
                    tagged_file.add_tags()
                    tagged_file.save()
                    tagged_file = ID3()

                if downloaded_track.youtube_tags["name"]:
                    tagged_file["TIT2"] = TIT2(
                        encoding=3, text=downloaded_track.youtube_tags["name"])
                if downloaded_track.youtube_tags["track_number"]:
                    try:
                        tagged_file["TRCK"] = TRCK(
                            encoding=3,
                            text=str(
                                downloaded_track.youtube_tags["track_number"]))
                    except:
                        tagged_file["TRCK"] = TRCK(encoding=3, text=u"1")
                if downloaded_track.youtube_tags["album"]:
                    tagged_file["TALB"] = TALB(
                        encoding=3,
                        text=downloaded_track.youtube_tags["album"])
                if downloaded_track.youtube_tags["artist"]:
                    tagged_file["TPE1"] = TPE1(
                        encoding=3,
                        text=downloaded_track.youtube_tags["artist"])

                tagged_file.save(file_path)

                while True:
                    try:
                        file_path.rename(file_path)
                    except:
                        continue
                    break

                new_path = Path(file_path.parent / Path(
                    util.clean_path_child(
                        f"{downloaded_track.youtube_tags['artist']} - {downloaded_track.youtube_tags['name']}.mp3"
                    )))

                os.rename(file_path, new_path)
                downloaded_track.download_location = new_path
                downloaded_track.store_to_master_file()
                tag_count += 1

        self.logger.debug(
            f"Finished adding tags to {tag_count} YouTube tracks")
Example #3
0
  def encodeMP3(self, wavf, dstf, cover, meta):
    FNULL = open(os.devnull, 'w')
    subprocess.call(['lame', '-V2', wavf, dstf], stdout=FNULL, stderr=FNULL)
    FNULL.close()
    # tag MP3
    mm = TrackMeta(meta)
    mp3 = MP3(dstf, ID3=ID3)
    mp3["TIT2"] = TIT2(encoding=3, text=mm.title())
    mp3["TPE1"] = TPE1(encoding=3, text=mm.artist())
    mp3["TALB"] = TALB(encoding=3, text=mm.album())
    mp3["TPE2"] = TPE2(encoding=3, text=mm.albumartist())
    if mm.date():
      mp3["TDRC"] = TDRC(encoding=3, text=mm.date())
    mp3["TRCK"] = TRCK(encoding=3,
                       text=mm.tracknumber()+"/"+mm.tracktotal())
    mp3["TPOS"] = TPOS(encoding=3,
                       text=mm.discnumber()+"/"+mm.disctotal())

    # composer
    if mm.composer():
      mp3["TCM"] = TCM(encoding=3, text=mm.composer())

    # cover
    if cover:
      data = open(cover, 'rb').read()
      covr = []
      if cover.endswith('png'):
        mime = 'image/png'
      else:
        mime = 'image/jpeg'
      mp3.tags.add(APIC(encoding=3, mime=mime, type=3, desc=u'Cover', data=data))

    # save
    mp3.save()
Example #4
0
    def apply_meta(self, filename: str, meta: dict):
        album_cover = self._album_cover_download(
            meta["album"]["images"][0]["url"]
        )
        album_artists = ", ".join(meta["album"]["artists"])
        artists = ", ".join(meta["artist"])
        lyric = LyricsSearcher(meta["name"], artists).search()

        tag = ID3(filename)
        tag["TIT2"] = TIT2(3, meta["name"])  # Title
        tag["TPE1"] = TPE1(3, artists)  # Artist
        tag["TPE2"] = TPE2(3, album_artists)  # Album Artist
        tag["TALB"] = TALB(3, meta["album"]["name"])  # Album Title
        tag["TRCK"] = TRCK(3, str(meta["track_number"]))  # Track Number
        tag["TYER"] = TYER(
            3, meta["album"]["released_at"].split("-")[0]
        )  # Released Year
        tag["APIC"] = APIC(
            encoding=3,
            mime="image/jpeg",
            type=3,
            desc="Album Cover",
            data=album_cover,
        )  # Album Cover

        if lyric is not None:
            tag["USLT"] = USLT(3, desc="", text=lyric)
        tag.save(v2_version=3)  # ID3

        os.rename(
            filename,
            self._safe_name("{} - {}".format(artists, meta["name"])) + ".mp3",
        )
Example #5
0
def set_file_tags(filename, tags):
    try:
        default_tags = ID3(filename)
    except ID3NoHeaderError:
        # Adding ID3 header
        default_tags = ID3()

    # Tag Breakdown
    # Track: TIT2
    # OG Filename: TOFN # Artist - Song Title.MP3
    # Artist: TOPE, TPE1, WOAR(official), TSO2(itunes), TPE2(band)
    # Lyrics: TEXT
    # Album: TOAL(original), TSO2(itunes), TSOA(sort), TALB
    # Genres: TCON
    # Year: TORY(release), TYER(record)
    # Publisher: TPUB, WPUB(info)

    default_tags["TOFN"] = TOFN(encoding=3, text=os.path.split(filename[0])[1])  # Original Filename
    default_tags["TIT2"] = TIT2(encoding=3, text=tags.song)  # Title
    default_tags["TRCK"] = TRCK(encoding=3, text=tags.track_number)  # Track Number

    # Artist tags
    default_tags["TOPE"] = TOPE(encoding=3, text=tags.artist)  # Original Artist/Performer
    default_tags["TPE1"] = TPE1(encoding=3, text=tags.artist)  # Lead Artist/Performer/Soloist/Group
    default_tags["TPE2"] = TPE2(encoding=3, text=tags.album_artist)  # Band/Orchestra/Accompaniment

    # Album tags
    default_tags["TOAL"] = TOAL(encoding=3, text=tags.album)  # Original Album
    default_tags["TALB"] = TALB(encoding=3, text=tags.album)  # Album Name
    default_tags["TSO2"] = TSO2(encoding=3, text=tags.album)  # iTunes Album Artist Sort
    # tags["TSOA"] = TSOA(encoding=3, text=tags.album[0]) # Album Sort Order key

    default_tags["TCON"] = TCON(encoding=3, text=tags.genres)  # Genre
    default_tags["TDOR"] = TORY(encoding=3, text=str(tags.year))  # Original Release Year
    default_tags["TDRC"] = TYER(encoding=3, text=str(tags.year))  # Year of recording
    default_tags["USLT"] = USLT(encoding=3, text=tags.lyrics)  # Lyrics
    default_tags.save(v2_version=3)

    # Album Cover
    if type(tags.album_cover) == str:
        r = requests.get(tags.album_cover, stream=True)
        r.raise_for_status()
        r.raw.decode_content = True
        with open('img.jpg', 'wb') as out_file:
            shutil.copyfileobj(r.raw, out_file)
        del r

        with open('img.jpg', 'rb') as albumart:
            default_tags.add(APIC(
                              encoding=3,
                              mime="image/jpg",
                              type=3, desc='Cover',
                              data=albumart.read()))
    elif type(tags.album_cover) == bytes:
        default_tags.add(APIC(
                                encoding=3,
                                mime="image/jpg",
                                type=3, desc='Cover',
                                data=tags.album_cover))
    default_tags.save(v2_version=3)
Example #6
0
 def add_audio_tags(self, filename: str, info: dict):
     audio = MP3(filename)
     tags = {
         # Title/songname/content description
         'TIT2':
         TIT2(encoding=3, text=info.get('track', '')),
         # Lead performer(s)/Soloist(s)
         'TPE1':
         TPE1(encoding=3, text=info.get('artist', '')),
         # Date
         'TDRC':
         TDRC(encoding=3, text=f'{info.get("release_year","")}'),
         # Content type (genre)
         'TCON':
         TCON(encoding=3, text=info.get('genre', '')),
         # Album/Movie/Show title
         'TALB':
         TALB(encoding=3, text=info.get('album', '')),
         # Track number/Position in set
         'TRCK':
         TRCK(encoding=3, text=info.get('track_number', '')),
         # Comments
         'COMM':
         COMM(encoding=3, text=f'https://youtu.be/{info.get("id", "")}'),
     }
     audio.update(tags)
     audio.save()
Example #7
0
def write_id3_single_file(path, filename, title, episode, season, album,
                          album_artist, artist):
    print(episode)
    print(season)
    try:
        audio = ID3(path + filename)
        audio.delete()
        audio = ID3()
    except ID3NoHeaderError:
        audio = ID3()

    audio.add(TIT2(encoding=3, text=title))
    if episode != '':
        audio.add(TRCK(encoding=3, text=episode))
    else:
        print('No Episode Number')

    if season != '':
        audio.add(TPOS(encoding=3, text=season))
    else:
        print('No Season Number')

    audio.add(TPE1(encoding=3, text=artist))
    audio.add(TPE2(encoding=3, text=album_artist))
    audio.add(TALB(encoding=3, text=album))
    audio.save(path + filename)
Example #8
0
def setSongInfo(song_path, music_info, lyr_path, pic_path, media_type):
    lyrics = open(lyr_path, encoding='utf-8').read().strip()
    # try to find the right encoding
    for enc in ('utf8', 'iso-8859-1', 'iso-8859-15', 'cp1252', 'cp1251', 'latin1'):
        try:
            lyrics = lyrics.decode(enc)
            print(enc, )
            break
        except:
            pass

    if media_type == 'mp3':
        # 用eyed3库只支持英文歌名,对utf-8格式的文件无法修改;所以使用mutagen库替代修改mp3信息
        # 传入mp3、jpg的url路径以及其他字符串
        tags = ID3(song_path)
        tags.update_to_v23()  # 把可能存在的旧版本升级为2.3
        # 插入歌名
        tags['TIT2'] = TIT2(encoding=3, text=[music_info['name']])
        # 插入歌曲艺术家
        tags['TPE1'] = TPE1(encoding=3, text=[music_info['artist']])
        # 插入专辑名称
        tags['TALB'] = TALB(encoding=3, text=[music_info['albumName']])
        # 插入专辑公司
        # tags['TCOP'] = TCOP(encoding=3, text=[music_info['Company']])
        # 插入声道数
        tags['TRCK'] = TRCK(encoding=3, text=[music_info['trackNumber']])
        # 插入发行时间
        tags['TYER'] = TYER(encoding=3, text=[music_info['publishYear']])
        tags["TDRC"] = TDRC(encoding=3, text=music_info['publishYear'])
        # 插入专辑图片
        # response = urllib.request.urlopen(mp3_header_info['albumPicDownUrl'])
        # tags['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=response.data)
        with open(pic_path, 'rb') as img:
            tags['APIC'] = APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=img.read())
        # 插入歌词
        # remove old unsychronized lyrics
        if len(tags.getall(u"USLT::'en'")) != 0:
            mylogger.info("Removing Lyrics.")
            tags.delall(u"USLT::'en'")
            tags.save()

        # tags.add(USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics))
        # apparently the description is important when more than one
        # USLT frames are present
        tags[u"USLT::'eng'"] = (USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics))
        tags.save()

    elif media_type == 'm4a':
        tags = MP4(song_path).tags
        tags['\xa9nam'] = music_info['name']
        tags['\xa9alb'] = music_info['albumName']
        tags['\xa9ART'] = music_info['artist']
        tags['\xa9day'] = music_info['pub_time']
        tags['\xa9cmt'] = music_info['subtitle']
        tags['\xa9gen'] = music_info['genre']
        with open(pic_path, 'rb') as img:
            tags["covr"] = [MP4Cover(img.read(), imageformat=MP4Cover.FORMAT_JPEG)]
        tags.save(song_path)
    else:
        mylogger.error("%s 类型不支持." % song_path)
Example #9
0
    def run(self):
        audio = MP3(mp3Arquivo)

        capaMp3 = ''
        if not capaArquivo:
            try:
                capaMp3 = audio.tags['APIC:'].data
            except:
                pass

        audio.delete()
        audio["TIT2"] = TIT2(encoding=3, text=unicode(strTitulo))
        audio["TALB"] = TALB(encoding=3, text=unicode(strAlbum))
        audio["TPE1"] = TPE1(encoding=3, text=unicode(strBanda))
        audio["TDRC"] = TDRC(encoding=3, text=unicode(strAno))
        audio["TRCK"] = TRCK(encoding=3,
                             text=unicode(strTrack + '/' + strTotal))
        audio["TPOS"] = TPOS(encoding=3,
                             text=unicode(strNumAlbum + '/' + strTotalAlbum))
        if capaArquivo or capaMp3:
            imagedata = capaArquivo or capaMp3
            audio["APIC"] = APIC(encoding=3,
                                 mime='image/jpg',
                                 type=3,
                                 desc='',
                                 data=imagedata)
        audio.save()

        print 'Arquivo finalizado: ', self.mp3Arquivo
Example #10
0
    def set(self,property,value):
        ''' Set value of given property. 1) Make sure value is valid. 2) check
            that property is valid. 3) check that property exists. 4) either
            modify or remove property. See self.tags for valid properties.
        '''
        if(type(value)!=str):
            value = str(value)
            print("WARNING: value type of "+property+" has been corrected to 'str'")

        # ensure that property is valid
        assert property in self.tags,'Invalid property "{}"'.format(property)

        # check if property in object. if not, create it.
        if(self._d[property] not in self.dat.keys()):
            # property doesn't already exist in metadata
            if(property=='title'):self.dat.add(TIT2(encoding=3,text=value))
            elif(property=='artist'): self.dat.add(TPE1(encoding=3,text=value))
            elif(property=='album'): self.dat.add(TALB(encoding=3,text=value))
            elif(property=='track'): self.dat.add(TRCK(encoding=3,text=value))
            elif(property=='genre'): self.dat.add(TCON(encoding=3,text=value))
            elif(property=='year'): self.dat.add(TDRC(encoding=3,text=str(value)))
            elif(property=='comment'): self.dat.add(COMM(encoding=3,lang='eng',text=value))
            else: raise Exception('Invalid property to add')
        elif(value == ''):
            # user wants to clear the tag, so remove from object
            self.dat.pop(self._d[property])
        elif(property=='year'):
            # having issues with year value. will specifically use 'add'
            self.dat.add(TDRC(encoding=3,text=str(value)))
        else:
            # simply modify the property
            self.dat[self._d[property]].text[0] = value
        return True
Example #11
0
def get_cover(path, cover_path, composer, album, track):
    audio = MP3(path, ID3=ID3)
    print('try getting cover image from', cover_path)
    img = None
    try:
        img = requests.get(cover_path, headers=headers).content
        # img = requests.get(cover_path, headers=headers).content
    except error:
        print(error)
        return

    if audio.tags == None:
        audio.add_tags()
    audio.tags.add(
        APIC(
            encoding=3,
            mime='image/jpeg',
            type=3,
            desc=u'Cover',
            data=img,
        ))
    audio.tags.add(TPE1(text=composer))
    audio.tags.add(TAL(text=album))
    if track:
        audio.tags.add(TRCK(text=track))
        print("adding track %s" % track)

    audio.save()
Example #12
0
    def write_id3_tags(self, file_name):
        """Writes ID3 tags from out music file into given MP3 file

        Args:
            :file_name
        """
        try:
            tags = ID3(file_name)
        except ID3NoHeaderError:
            # Adding ID3 header
            tags = ID3()

        tags[self.TAG_TITLE] = TIT2(encoding=3,
                                    text='{} (Mp3VoiceStamp)'.format(
                                        self.title))
        tags[self.TAG_ALBUM_TITLE] = TALB(encoding=3, text=self.album_title)
        tags[self.TAG_ALBUM_ARTIST] = TPE2(encoding=3, text=self.album_artist)
        tags[self.TAG_ARTIST] = TPE1(encoding=3, text=self.artist)
        tags[self.TAG_COMPOSER] = TCOM(encoding=3, text=self.composer)
        tags[self.TAG_TRACK_NUMBER] = TRCK(encoding=3, text=self.track_number)

        tags[self.TAG_ORIGINAL_FILENAME] = TOFN(encoding=3,
                                                text=self.file_name)
        tags[self.TAG_SOFTWARE] = TSSE(encoding=3,
                                       text='{app} v{v} {url}'.format(
                                           app=APP_NAME,
                                           v=VERSION,
                                           url=APP_URL))

        tags.save(file_name)
Example #13
0
 def modified_id3(self, file_name, info):
     id3 = ID3()
     id3.add(TRCK(encoding=3, text=info['track']))
     id3.add(TDRC(encoding=3, text=info['year']))
     id3.add(TIT2(encoding=3, text=info['song_name']))
     id3.add(TALB(encoding=3, text=info['album_name']))
     id3.add(TPE1(encoding=3, text=info['artist_name']))
     id3.add(TPOS(encoding=3, text=info['cd_serial']))
     #id3.add(USLT(encoding=3, text=self.get_lyric(info['lyric_url'])))
     #id3.add(TCOM(encoding=3, text=info['composer']))
     #id3.add(WXXX(encoding=3, desc=u'xiami_song_url', text=info['song_url']))
     #id3.add(TCON(encoding=3, text=u'genres'))
     #id3.add(TSST(encoding=3, text=info['sub_title']))
     #id3.add(TSRC(encoding=3, text=info['disc_code']))
     id3.add(
         COMM(encoding=3,
              desc=u'Comment',
              text=u'\n\n'.join(
                  [info['song_url'], info['album_description']])))
     id3.add(
         APIC(encoding=3,
              mime=u'image/jpeg',
              type=3,
              desc=u'Front Cover',
              data=self.get_cover(info)))
     id3.save(file_name)
Example #14
0
def tag_resulting_track(out_file_path, track_info):
    try:
        track_to_tag = ID3(out_file_path)
    except mutagen.id3.error:
        track_to_tag = ID3()
        track_to_tag.save(out_file_path)

    track_to_tag.add(TPE1(encoding=3,
                          text=track_info['track_artist']))  # Artist

    track_to_tag.add(TIT2(encoding=3, text=track_info['track_title']))  # Title
    track_to_tag.add(TSRC(encoding=3, text=track_info['ISRC']))  # ISRC

    track_to_tag.add(TRCK(encoding=3,
                          text=track_info['track_number']))  # Track Number
    track_to_tag.add(TPOS(encoding=3,
                          text=track_info['disc_number']))  # Disc Number

    track_to_tag.add(TALB(encoding=3,
                          text=track_info['album_title']))  # Album Title
    track_to_tag.add(TDRC(encoding=3, text=track_info['album_year']))  # Year
    track_to_tag.add(TPUB(encoding=3, text=track_info['label']))  # Label
    track_to_tag.add(TPE2(encoding=3,
                          text=track_info['album_artist']))  # Album artist
    track_to_tag.add(TCON(encoding=3, text=track_info['genre']))  # Genre

    track_to_tag.save(out_file_path)
    def __update_metadata(self, path = str(), info = dict()):
        with open(path, 'r+b') as mp3f:
            mp3 = MP3(mp3f)
            id3 = ID3()

            track_num = info.get('trackNumber', 1)
            id3.add(TRCK(encoding=3, text=[track_num if track_num > 0 else 1]))

            id3.add(TIT2(encoding=3, text=info['title']))
            id3.add(TPE1(encoding=3, text=[info.get('artist', None)]))
            id3.add(TCOM(encoding=3, text=[info.get('composer', None)]))
            id3.add(TCON(encoding=3, text=[info.get('genre', None)]))
            id3.add(TAL(encoding=3, text=[info.get('album', None)]))

            year = info.get('year', 0)
            if year > 0:
                id3.add(TYER(encoding=3, text=[year]))
            
            if 'albumArtRef' in info and len(info['albumArtRef']) > 0:
                img_url = info['albumArtRef'][0]['url']
                if img_url:
                    req = requests.get(img_url, allow_redirects=True)
                    id3.add(APIC(encoding=3, mime='image/jpeg', type=3, data=req.content))
                    
            mp3.tags = id3
            mp3.save(mp3f)
Example #16
0
def setData(path, song):
    meta = ID3(path)
    meta.delete()
    meta.add(TIT2(encoding=3, text=song.track))
    meta.add(TPE1(encoding=3, text=song.artist))
    meta.add(TPE2(encoding=3, text=song.artist))
    meta.add(TALB(encoding=3, text=song.album))
    meta.add(TCON(encoding=3, text=song.genre))
    meta.add(TRCK(encoding=3, text=song.track_number + '/' + song.track_count))
    meta.add(TPOS(encoding=3, text=song.disc_number + '/' + song.disc_count))
    meta.add(TDRC(encoding=3, text=song.release_date[0:4]))
    meta.save()
    # Embed cover-art in ID3 metadata
    meta = MP3(path, ID3=ID3)
    imgURL = song.artwork_url
    dir = Path.home() / 'Downloads' / 'Music' / 'CoverArt'
    os.system('mkdir -p %s' % (dir))
    imgPath = os.path.join(dir, 'cover.jpg')
    response = requests.get(imgURL)
    img = Image.open(io.BytesIO(response.content))
    img.save(imgPath)
    meta.tags.add(
        APIC(encoding=3,
             mime='image/jpg',
             type=3,
             desc=u'Cover',
             data=open(imgPath, 'rb').read()))
    meta.save()
    shutil.rmtree(dir)
Example #17
0
    def start(self):
        songinfo, session, headers = self.songinfo, self.session, self.headers
        filename = os.path.join(songinfo['savedir'], songinfo['savename']+'.'+songinfo['ext'])
        cover_file = None
        checkDir(songinfo['savedir'])
        if os.path.exists(filename):
            print('already downloaed, skip')
            return True
        try:
            if songinfo['cover_url']:
                cover_file = os.path.join(songinfo['savedir'], "%s - cover.jpg" % filterBadCharacter(songinfo['album']))
                if not os.path.exists(cover_file):
                    with open(cover_file, 'wb') as f:
                        r = session.get(songinfo['cover_url'], headers=headers)
                        f.write(r.content)
                        f.close()
            is_success = False
            with closing(session.get(songinfo['download_url'], headers=headers, stream=True, verify=False)) as response:
                total_size = int(response.headers['content-length'])
                chunk_size = 1024
                if response.status_code == 200:
                    label = '[FileSize]: %0.2fMB' % (total_size/1024/1024)
                    with click.progressbar(length=total_size, label=label) as progressbar:
                        with open(filename, "wb") as fp:
                            for chunk in response.iter_content(chunk_size=chunk_size):
                                if chunk:
                                    fp.write(chunk)
                                    progressbar.update(chunk_size)
                    is_success = True
            # ensure there's ID3 tag in mp3 file
            if filename.endswith('mp3'):
                from mutagen.mp3 import MP3
                from mutagen.id3 import TPE1, TALB, TIT2, TRCK, APIC

                mp3 = MP3(filename, v2_version=3)
                try:
                    mp3.add_tags()
                except:
                    pass

                mp3.tags['TPE1'] = TPE1(encoding=3, text=songinfo['singers'])
                mp3.tags['TALB'] = TALB(encoding=3, text=songinfo['album'])
                mp3.tags['TIT2'] = TIT2(encoding=3, text=songinfo['songname'])
                mp3.tags['TRCK'] = TRCK(encoding=3, text=str(songinfo['track']))
                mp3.tags.add(APIC(
                        encoding=3,
                        mime='image/jpeg',
                        type=3,
                        desc='Cover',
                        data=open(cover_file, 'rb').read()
                ))
                mp3.save(v2_version=3)
            if filename.endswith('m4a'):
                checkDir(os.path.join(songinfo['savedir'], 'output'))
                os.system("ffmpeg -i \"%s\" -i \"%s\" -map 0:0 -map 1:0 -metadata album=\"%s\" -metadata artist=\"%s\" -metadata title=\"%s\" -metadata track=\"%d/%d\" \"%s\"" %\
                        (filename, cover_file, songinfo['album'], songinfo['singers'], songinfo['songname'], songinfo['track'], songinfo['total'], os.path.join(songinfo['savedir'], 'output', songinfo['savename']+'.mp3')))
        except Exception as e:
            print(e)
            is_success = False
        return is_success
Example #18
0
def modify_mp3_tag(song, song_path, image_path, genreArg):
    
    # Set genre
    genre = None
    if genreArg is None or genreArg.strip() == "":
        # Try extracting genre from existing tag
        try:
            tag = ID3(song_path) # will call load() on the path
            genre = tag.get("TCON").genres[0] if tag.get("TCON") else None
        except ID3NoHeaderError:
            pass
    else:
        genre = genreArg
    
    # Set genre to default if genre could not be extracted
    genre = DEFAULT_GENRE if genre is None or genre.strip() == "" else genre

    # Create empty tag and add frames to it
    tag = ID3()
    tag.add(TIT2(encoding=3, text=unicode(song.title) ))          # TITLE
    tag.add(TRCK(encoding=3, text=unicode(int(song.track_num))))  # TRACK
    tag.add(TPE1(encoding=3, text=unicode(song.artist) ))         # ARTIST
    tag.add(TPE2(encoding=3, text=unicode(song.artist) ))         # ALBUMARTIST
    tag.add(TALB(encoding=3, text=unicode(song.album) ))          # ALBUM
    tag.add(TYER(encoding=3, text=unicode(song.year) ))           # YEAR
    tag.add(TDRC(encoding=3, text=unicode(song.year) ))           # YEAR
    tag.add(TCON(encoding=3, text=unicode(genre) ))               # GENRE

    if image_path:
        image_data = open(image_path, 'rb').read()
        image_type = image_path.split('.')[-1]  # get the file extension without dot
        tag.add(APIC(3, "image/"+image_type, 3, 'Album Cover', image_data))  # Album Artwork

    tag.save(song_path, v2_version=3) # write the tag as ID3v2.3
Example #19
0
def add_mp3_tags(fileobj,
                 tags,
                 cover=None,
                 lyrics=None,
                 image_mimetype='image/png'):
    handle = MP3(fileobj=fileobj)
    if 'artist' in tags:
        handle['TPE1'] = TPE1(text=tags['artist'])
    if 'title' in tags:
        handle['TIT2'] = TIT2(text=tags['title'])
    if 'album' in tags:
        handle['TALB'] = TALB(text=tags['album'])
    if 'albumartist' in tags:
        handle['TPE2'] = TPE2(text=tags['albumartist'])
    if 'genre' in tags:
        handle['TCON'] = TCON(genres=[tags['genre']])
    if 'tracknumber' in tags:
        handle['TRCK'] = TRCK(text=tags['tracknumber'])
    if 'year' in tags:
        handle['TYER'] = TYER(text=tags['year'])
    if 'date' in tags:
        handle['TDAT'] = TDAT(text=tags['date'])
    if 'bpm' in tags:
        handle['TBPM'] = TBPM(text=tags['bpm'])
    if 'isrc' in tags:
        handle['TSRC'] = TSRC(text=tags['isrc'])
    if 'explicit' in tags:
        handle['TXXX'] = TXXX(text=tags['explicit'])
    if lyrics:
        handle['USLT'] = USLT(text=lyrics)
    if cover:
        handle['APIC'] = APIC(data=cover, mime=image_mimetype)
    handle.save(fileobj)
    fileobj.seek(0)
Example #20
0
    def applyTrackMetadata(self):
        audio_file = ID3(self.file_path)

        # album cover image
        album_cover_art = urlopen(self.track.cover)
        audio_file['APIC'] = APIC(encoding=3,
                                  mime='image/jpeg',
                                  type=3,
                                  desc=u'Cover',
                                  data=album_cover_art.read())

        # album name
        audio_file['TALB'] = TALB(encoding=3, text=self.track.album_name)

        # album release year
        audio_file['TYER'] = TYER(encoding=3,
                                  text=self.track.release_date.split('-')[0])

        # album artist
        audio_file['TPE2'] = TPE2(encoding=3,
                                  text=self.track.album_artist.split(';'))

        # track name
        audio_file['TIT2'] = TIT2(encoding=3, text=self.track.name)

        # track number
        audio_file['TRCK'] = TRCK(encoding=3, text=str(self.track.number))

        # track artist name
        audio_file['TPE1'] = TPE1(encoding=3,
                                  text=self.track.featured_artists.split(';'))

        album_cover_art.close()
        audio_file.save(v2_version=3)
        self.SUCCESS = True
Example #21
0
def write_id3(pod_path, file_name, titles, episode_num, season_num, alb,
              albart, art):

    print(season_num)
    for file_name_entry in file_name:
        file_name_index = file_name_entry.index(file_name_entry)
        try:
            audio = ID3(pod_path + file_name_entry)
            audio.delete()
            audio = ID3()
        except ID3NoHeaderError:
            audio = ID3()
        audio.add(TIT2(encoding=3, text=titles[file_name_index]))
        if len(episode_num) != 0:
            audio.add(TRCK(encoding=3, text=episode_num[file_name_index]))
        else:
            print("No Ep Num")
        if len(season_num) != 0:
            audio.add(TPOS(encoding=3, text=season_num[file_name_index]))
        else:
            print("No Sn Num")
        audio.add(TPE1(encoding=3, text=art))
        audio.add(TPE2(encoding=3, text=albart))
        audio.add(TALB(encoding=3, text=alb))
        audio.save(pod_path + file_name_entry)
Example #22
0
File: md.py Project: araa47/vidl
def add_metadata(filename, md):
    try:
        tags = ID3(filename)
    except mutagen.id3.ID3NoHeaderError:
        file = mutagen.File(filename)
        file.add_tags()
        tags = file

    if 'title' in md: tags["TIT2"] = TIT2(text=md['title'])
    if 'artist' in md: tags["TPE1"] = TPE1(text=md['artist'])
    if 'album' in md: tags["TALB"] = TALB(text=md['album'])
    if 'album_artist' in md: tags["TPE2"] = TPE2(text=md['album_artist'])
    if 'track_number' in md:
        track_number = str(md['track_number'])
        if 'track_count' in md:
            track_number += '/' + str(md['track_count'])
        tags["TRCK"] = TRCK(encoding=3, text=track_number)
    if 'genre' in md: tags["TCON"] = TCON(text=md['genre'])
    if 'year' in md: tags["TDRC"] = TDRC(text=md['year'])

    if 'comment' in md: tags["COMM"] = COMM(text=md['comment'], lang='eng')
    if 'lyrics' in md: tags["USLT"] = USLT(text=md['lyrics'])
    if 'composer' in md: tags["TCOM"] = TCOM(text=md['composer'])

    for key, value in md.items():
        whitespace = ' ' * (10 - len(key))
        log('  ' + key + ':' + whitespace + pformat(value))

    tags.save(filename)
Example #23
0
    def to_id3_tags(self, audio_path):
        """Loads an MP3 file and adds ID3v2.4 tags based on the given discogs entry"""
        audio = ID3(audio_path, v2_version=4)

        # Set album art
        album_art_url = self.get_album_art_url()
        if album_art_url:
            r = requests.get(album_art_url)
            audio.add(APIC(
                encoding=3,
                mime='image/jpeg',
                type=3,
                desc='Cover',
                data=r.content
            ))
            del r

        # Set title
        audio.add(TIT2(encoding=3, text=[self.track.title]))

        # Set artists
        audio.add(TPE1(encoding=3, text=self.get_artists()))

        # Set album
        audio.add(TALB(encoding=3, text=[self.get_release_title()]))

        # Set track number
        audio.add(TRCK(encoding=3, text=[self.track.position]))

        # Set labels
        labels = list(self.get_labels())
        if len(labels) > 0:
            audio.add(TPUB(encoding=3, text=labels[0:1]))

        # Set genres
        audio.add(TCON(encoding=3, text=self.get_genres()))

        # Set year
        audio.add(TYER(encoding=3, text=[self.get_year()])) # for backwards compatibility with v2.3
        # The timestamp fields are based on a subset of ISO 8601. When being as
        # precise as possible the format of a time string is
        # yyyy-MM-ddTHH:mm:ss (year, "-", month, "-", day, "T", hour (out of
        # 24), ":", minutes, ":", seconds), but the precision may be reduced by
        # removing as many time indicators as wanted. Hence valid timestamps
        # are
        # yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddTHH, yyyy-MM-ddTHH:mm and
        # yyyy-MM-ddTHH:mm:ss. All time stamps are UTC. For durations, use
        # the slash character as described in 8601, and for multiple non-
        # contiguous dates, use multiple strings, if allowed by the frame
        # definition.
        audio.add(TDRL(encoding=3, text=[self.get_year()]))
        audio.add(TDOR(encoding=3, text=[self.get_year()]))

        # Set tagging time
        # aka right now
        # for completeness sake
        audio.add(TDTG(encoding=3, text=[datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M')]))

        # Write to disk
        audio.save()
Example #24
0
    def modified_id3(self, file_name, info):
        '''
        给歌曲增加id3 tag信息
        :file_name 待修改的歌曲完整地址
        :info 歌曲信息
        :return None
        '''

        if not os.path.exists(file_name):
            return None

        id3 = ID3()
        id3.add(TRCK(encoding=3, text=info['track']))
        id3.add(TDRC(encoding=3, text=info['year']))
        id3.add(TIT2(encoding=3, text=info['song_name']))
        id3.add(TALB(encoding=3, text=info['album_name']))
        id3.add(TPE1(encoding=3, text=info['artist_name']))
        id3.add(TPOS(encoding=3, text=info['cd_serial']))
        id3.add(COMM(encoding=3, desc=u'Comment', text=info['song_url']))

        http = requests.urllib3.PoolManager()

        with http.request('GET', info['album_pic_url'],
                          preload_content=False) as r, open('img.jpg',
                                                            'wb') as out_file:
            shutil.copyfileobj(r, out_file)
        img = open('img.jpg', 'rb')
        id3['APIC'] = APIC(encoding=3,
                           mime='image/jpeg',
                           type=3,
                           desc=u'Cover',
                           data=img.read())

        id3.save(file_name)
Example #25
0
 def set_id3(self, path, resolution=480):
     """
 Assigns the ID3 metadata of the MP3 file
 Args:
   path: The path of the converted MP3 file
   resolution: The target resolution of the cover-art
 """
     tags = ID3(path)
     tags.delete()
     tags.add(TIT2(encoding=3, text=self.track))
     tags.add(TPE1(encoding=3, text=self.artist))
     tags.add(TPE2(encoding=3, text=self.artist))
     tags.add(TALB(encoding=3, text=self.album))
     tags.add(TCON(encoding=3, text=self.genre))
     tags.add(
         TRCK(encoding=3, text=self.track_number + '/' + self.track_count))
     tags.add(
         TPOS(encoding=3, text=self.disc_number + '/' + self.disc_count))
     tags.add(TDRC(encoding=3, text=self.release_date[0:4]))
     # Embed cover-art in ID3 metadata
     img_path = self.get_cover_image(resolution)
     tags.add(
         APIC(encoding=3,
              mime='image/jpg',
              type=3,
              desc=u'Cover',
              data=open(img_path, 'rb').read()))
     tags.save()
Example #26
0
def addtag(fname,
           m_song,
           m_album,
           m_artist,
           m_singer,
           m_cover,
           m_year='',
           m_trackid='',
           m_cd=''):
    '''Add Tag for MP3'''
    ml = mylogger(logfile, get_funcname())
    try:
        tags = ID3(fname)
    except ID3NoHeaderError:
        ml.dbg("Adding ID3 header on " + m_trackid)
        tags = ID3()
    tags["TIT2"] = TIT2(encoding=3, text=m_song)
    tags["TALB"] = TALB(encoding=3, text=m_album)
    tags["TPE2"] = TPE2(encoding=3, text=m_artist)  #album artist
    #tags["COMM"] = COMM(encoding=3, lang=u'eng', desc='desc', text=u'mutagen comment')
    tags["TPE1"] = TPE1(encoding=3, text=m_singer)  # singer
    #tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer')
    #tags["TCON"] = TCON(encoding=3, text=u'mutagen Genre')
    tags["TDRC"] = TDRC(encoding=3, text=m_year)
    tags["TRCK"] = TRCK(encoding=3, text=str(m_trackid))
    tags["TPOS"] = TPOS(encoding=3, text=m_cd)
    if m_cover != '':
        with open(m_cover, 'rb') as c:
            cover = c.read()  #prepare for tag
        tags["APIC"] = APIC(encoding=3,
                            mime=u'image/png',
                            type=3,
                            desc=u'Cover',
                            data=cover)
    tags.save(fname, v2_version=3)
Example #27
0
def id_SongsID3(songs, highestID):
    #Gives each song in the library an ID
    for song in songs:
        string = str(highestID + 1)
        song["TRCK"] = TRCK(encoding=3, text=string)
        highestID += 1
        song.save()
Example #28
0
File: tags.py Project: Jerk-art/DFY
def insert_tags(filepath, tags):
    """Using mutagen inject tags inside mp3 file

    :param filepath: path to file
    :type filepath: str
    :param tags: dict of tags
    :type tags: dict
    """
    try:
        file = ID3(filepath)
    except ID3NoHeaderError:
        file = ID3()
    for key in tags:
        if key == 'album':
            file['TALB'] = TALB(encoding=3, text=tags[key])
        elif key == 'artist':
            file['TPE1'] = TPE1(encoding=3, text=tags[key])
        elif key == 'title':
            file['TIT2'] = TIT2(encoding=3, text=tags[key])
        elif key == 'image':
            file.add(
                APIC(3, 'image/jpeg', 3, 'Front cover',
                     get_image_bytes_from_url(tags[key])))
        elif key == 'release_date':
            file['TDRC'] = TDRC(encoding=3, text=tags[key])
        elif key == 'number':
            file['TRCK'] = TRCK(encoding=3, text=str(tags[key]))
    file.save(filepath)
Example #29
0
def modifySongInfo(id_card, songInfo: dict):
    """ 从字典中读取信息并修改歌曲的标签卡信息 """

    if songInfo['suffix'] == '.mp3':
        id_card['TRCK'] = TRCK(encoding=3, text=songInfo['tracknumber'])
        id_card['TIT2'] = TIT2(encoding=3, text=songInfo['songName'])
        id_card['TDRC'] = TDRC(encoding=3, text=songInfo['year'][:4])
        id_card['TPE1'] = TPE1(encoding=3, text=songInfo['songer'])
        id_card['TPE2'] = TPE2(encoding=3, text=songInfo['songer'])
        id_card['TALB'] = TALB(encoding=3, text=songInfo['album'])
        id_card['TCON'] = TCON(encoding=3, text=songInfo['tcon'])

    elif songInfo['suffix'] == '.flac':
        id_card['tracknumber'] = songInfo['tracknumber']
        id_card['title'] = songInfo['songName']
        id_card['year'] = songInfo['year'][:4]
        id_card['artist'] = songInfo['songer']
        id_card['album'] = songInfo['album']
        id_card['genre'] = songInfo['tcon']

    elif songInfo['suffix'] == '.m4a':
        # m4a写入曲目时还需要指定总曲目数
        tag = TinyTag.get(id_card.filename)
        trackNum = int(songInfo['tracknumber'])
        trackTotal = 1 if not tag.track_total else int(tag.track_total)
        trackTotal = max(trackNum, trackTotal)
        id_card['trkn'] = [(trackNum, trackTotal)]
        id_card['©nam'] = songInfo['songName']
        id_card['©day'] = songInfo['year'][:4]
        id_card['©ART'] = songInfo['songer']
        id_card['aART'] = songInfo['songer']
        id_card['©alb'] = songInfo['album']
        id_card['©gen'] = songInfo['tcon']
Example #30
0
def setAlbumSize(album, total_tracks):
    app.logger.info('setAlbumSize')

    total_tracks = int(total_tracks)

    # update tag
    for song in album.songs:
        app.logger.info('Updating total tracks for song {}'.format(song))
        if song.path_name.lower().endswith('mp3'):
            tags = ID3(song.abs_path)
            tags["TRCK"] = TRCK(encoding=3,
                                text=u'{}/{}'.format(song.track_number,
                                                     total_tracks))
            tags.save(song.abs_path)
        elif song.path_name.lower().endswith('m4a'):
            mp4_song = MP4(song.abs_path)
            mp4_song.tags['trkn'] = [(song.track_number, total_tracks)]
            mp4_song.save()

    # update album
    album.total_tracks = int(total_tracks)
    album.count_songs = len(album.songs)
    db.session.commit()
    app.logger.info('Update album')

    return album