示例#1
0
def get_tags_and_add(dir, verbose=1):
    for file in os.listdir(dir):
        if verbose > 0:
            print(f'sending {file} to API')
        sub = subprocess.check_output([
            f'curl -F "audio=@Mp3ToPCM/{file};type=audio/wav" -XPOST http://localhost:5000/model/predict'
        ],
                                      shell=True)
        response_dict = eval(sub)
        tags_to_add = []
        try:
            audio = ID3(f'Mp3/{file[0:-3]}mp3')
        except:
            audio = MP3(f'Mp3/{file[0:-3]}mp3')
            audio.add_tags()
            audio.save()
            audio = ID3(f'Mp3/{file[0:-3]}mp3')
        for pred in response_dict['predictions']:
            if pred['probability'] > .25:
                tags_to_add.append(pred['label'])
        if verbose > 0:
            print('Adding these tags: ' + ', '.join(tags_to_add))
            print('-------------------------------')
        existing = audio.get('TCON')
        if existing:
            audio.add(
                TCON(text=' '.join(set(audio.get('TCON').text[0].split()))))
        else:
            audio.add(TCON(text=' '.join(tags_to_add)))
        audio.save()
示例#2
0
def _audio_tcon(atuple):
    audio, atag, advanced, _, _ = atuple
    if advanced:
        param = ast.literal_eval(atag)
        audio.add(TCON(3, param[1]))
    else:
        audio.add(TCON(3, atag))
示例#3
0
    def _add_metadata(self, show, file_name):
        if file_name is None:
            raise "file_name is not set - you cannot add metadata to None"

        config = Configuration()

        time_string = format_date(config.date_pattern,
                                  time.localtime(self.start_time))
        comment = config.comment_pattern % {
            'show': show.name,
            'date': time_string,
            'year': time.strftime('%Y', time.gmtime()),
            'station': show.station.name,
            'link_url': show.get_link_url()
        }

        audio = ID3()
        # See http://www.id3.org/id3v2.3.0 for details about the ID3 tags

        audio.add(TIT2(encoding=2, text=["%s, %s" % (show.name, time_string)]))
        audio.add(
            TDRC(encoding=2,
                 text=[format_date('%Y-%m-%d %H:%M', self.start_time)]))
        audio.add(TCON(encoding=2, text=[u'Podcast']))
        audio.add(TALB(encoding=2, text=[show.name]))
        audio.add(TLEN(encoding=2, text=[show.duration * 1000]))
        audio.add(TPE1(encoding=2, text=[show.station.name]))
        audio.add(TCOP(encoding=2, text=[show.station.name]))
        audio.add(COMM(encoding=2, lang='eng', desc='desc', text=comment))
        audio.add(TCOM(encoding=2, text=[show.get_link_url()]))
        self._add_logo(show, audio)
        audio.save(file_name)
示例#4
0
def main():
    dataDir = './'

    if (len(sys.argv) == 2):
        dataDir = sys.argv[1]

        if (not os.path.isdir(dataDir)):
            warnings.warn(dataDir + ' is not vaild a directory')
            sys.exit()

        if dataDir[-1] != '/':
            dataDir += '/'

    elif (len(sys.argv) > 2):
        warnings.warn("Too many arguemnts")
        sys.exit()

    files = glob.glob(dataDir + '*/*.mp3')

    for file in files:
        print(file)
        filename = file.split('/')[-1]
        genre = file.split('/')[-2]

        tags = ID3(file)
        tags["TCON"] = TCON(encoding=3, text=genre)
        tags.save(file)
示例#5
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
示例#6
0
def editFiles(genres, descriptors, dir):
    #Put the genres in the files
    files = os.listdir(dir)
    for file in files:
        if str(file).endswith('.mp3'):
            print file
            if '?' in str(file):
                print 'Invalid file name. Skipping...'
                continue
            try:
                tags = ID3(dir + '\\' + file)
            except ID3NoHeaderError:
                print "Adding ID3 header;",
                tags = ID3()
            except:
                print 'Could not find file. Skipping...'
                continue

            # tags["TIT2"] = TIT2(encoding=3, text='title')
            # tags["TALB"] = TALB(encoding=3, text=u'mutagen Album Name')
            # tags["TPE2"] = TPE2(encoding=3, text=u'mutagen Band')
            tags.delall("COMM")
            # tags["COMM"] = COMM(encoding=3, desc='desc', lang=u'eng', text=descriptors)
            # tags["COMM"] = COMM(encoding=3, lang=u'eng', text='')
            # tags["COMM"] = COMM(encoding=3, text=descriptors)
            # tags["TPE1"] = TPE1(encoding=3, text=u'mutagen Artist')
            # tags["TCOM"] = TCOM(encoding=3, text=u'mutagen Composer')
            tags["TCON"] = TCON(encoding=3, text=genres)
            # tags["TDRC"] = TDRC(encoding=3, text=u'2010')
            # tags["TRCK"] = TRCK(encoding=3, text=u'track_number')
            tags["TMOO"] = TMOO(encoding=3, text=descriptors)

            tags.save(dir + '\\' + file)
            print(tags.pprint()).encode('utf-8')
示例#7
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']
示例#8
0
 def tagFile(self, filename, metadata, art_url):
     image = None
     if art_url is not None:
         self.getFile('artwork.jpg', art_url, True)
         try:
             with open('artwork.jpg', 'rb') as file:
                 image = file.read()
         except:
             pass
     if filename.endswith('.mp3'):
         audio = MP3(filename, ID3=ID3)
         try:
             audio.add_tags()
         except:
             pass
         audio.tags.add(
             APIC(encoding=3,
                  mime='image/jpeg',
                  type=3,
                  desc=u'Cover',
                  data=image))
         audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title'])
         audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist'])
         audio.tags["TDRC"] = TDRC(encoding=3,
                                   text=unicode(metadata['year']))
         audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre'])
         audio.save()
     elif filename.endswith('.flac'):
         audio = FLAC(filename)
         try:
             audio.add_tags()
         except:
             pass
         audio.tags['title'] = metadata['title']
         audio.tags['artist'] = metadata['artist']
         audio.tags['year'] = metadata['year']
         audio.tags['genre'] = metadata['genre']
         audio.tags.add(
             APIC(encoding=3,
                  mime='image/jpeg',
                  type=3,
                  desc=u'Cover',
                  data=image))
         audio.save()
     elif filename.endswith('.m4a'):
         audio = MP4(filename)
         try:
             audio.add_tags()
         except:
             pass
         covr = []
         covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG))
         audio.tags['covr'] = covr
         audio.tags['title'] = metadata['title']
         audio.tags['artist'] = metadata['artist']
         #audio.tags['year'] = metadata['year']
         audio.tags['genre'] = metadata['genre']
         audio.save()
     if os.path.isfile('artwork.jpg'):
         os.remove('artwork.jpg')
示例#9
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()
示例#10
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()
示例#11
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)
示例#12
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()
示例#13
0
文件: md.py 项目: 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)
示例#14
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
示例#15
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()
示例#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)
示例#17
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)
示例#19
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)
示例#20
0
    def ConfirmPopupEntry(self, columnNum, entry, fileNames):

        for fileName in fileNames:

            audioItem = self.master.audioFileList[fileName]
            audioFile = audioItem.audioFile

            rowNum = audioItem.rowNum

            title = audioItem.titleTag
            artist = audioItem.artistTag
            genre = audioItem.genreTag

            # Change ARTIST tag
            if columnNum is 2:
                audioFile["TPE1"] = TPE1(encoding=3, text=entry)

                self.treeview.item(fileName, values=(
                    fileName, entry, title, genre))

                if self.treeview.item(fileName)['tags'][0] == 'error':
                    if entry != 'None' and entry != '':
                        if rowNum % 2 is 0:
                            self.treeview.item(
                                fileName, tags=('ready', 'even'))
                        else:
                            self.treeview.item(
                                fileName, tags=('ready', 'odd'))
                    else:
                        if rowNum % 2 is 0:
                            self.treeview.item(
                                fileName, tags=('error'))
                        else:
                            self.treeview.item(
                                fileName, tags=('error'))

                audioItem.artistTag = entry

            # Change TITLE tag
            if columnNum is 3:
                audioFile["TIT2"] = TIT2(encoding=3, text=entry)

                self.treeview.item(fileName, values=(
                    fileName, artist, entry, genre))

                audioItem.titleTag = entry

            # Change GENRE tag
            if columnNum is 4:
                audioFile["TCON"] = TCON(encoding=3, text=entry)

                self.treeview.item(fileName, values=(
                    fileName, artist, title, entry))

                audioItem.genreTag = entry

            audioFile.save()
        self.DeletePopup()
示例#21
0
文件: py3tag.py 项目: korseby/py3tag
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)
示例#22
0
def get_american_life(epno,
                      directory='/mnt/media/thisamericanlife',
                      extraStuff=None,
                      verify=True):
    """
    Downloads an episode of This American Life into a given directory.
    The description of which URL the episodes are downloaded from is given in
    http://www.dirtygreek.org/t/download-this-american-life-episodes.

    The URL is http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/epno.mp3
    
    Otherwise, the URL is http://www.podtrac.com/pts/redirect.mp3/podcast.thisamericanlife.org/podcast/epno.mp3
    """
    try:
        title, year = get_americanlife_info(epno,
                                            extraStuff=extraStuff,
                                            verify=verify)
    except ValueError as e:
        print(e)
        print(
            'Cannot find date and title for This American Life episode #%d.' %
            epno)
        return

    if not os.path.isdir(directory):
        raise ValueError("Error, %s is not a directory." % directory)
    outfile = os.path.join(directory, 'PRI.ThisAmericanLife.%03d.mp3' % epno)
    urlopn = 'http://www.podtrac.com/pts/redirect.mp3/podcast.thisamericanlife.org/podcast/%d.mp3' % epno

    resp = requests.get(urlopn, stream=True, verify=verify)
    if not resp.ok:
        urlopn = 'http://audio.thisamericanlife.org/jomamashouse/ismymamashouse/%d.mp3' % epno
        resp = requests.get(urlopn, stream=True, verify=verify)
        if not resp.ok:
            print(
                "Error, could not download This American Life episode #%d. Exiting..."
                % epno)
            return
    with open(outfile, 'wb') as openfile:
        for chunk in resp.iter_content(65536):
            openfile.write(chunk)

    mp3tags = ID3()
    mp3tags['TDRC'] = TDRC(encoding=0, text=[u'%d' % year])
    mp3tags['TALB'] = TALB(encoding=0, text=[u'This American Life'])
    mp3tags['TRCK'] = TRCK(encoding=0, text=[u'%d' % epno])
    mp3tags['TPE2'] = TPE2(encoding=0, text=[u'Chicago Public Media'])
    mp3tags['TPE1'] = TPE1(encoding=0, text=[u'Ira Glass'])
    try:
        mp3tags['TIT2'] = TIT2(encoding=0, text=['#%03d: %s' % (epno, title)])
    except:
        mp3tags['TIT2'] = TIT2(
            encoding=0,
            text=[codecs.encode('#%03d: %s' % (epno, title), 'utf8')])
    mp3tags['TCON'] = TCON(encoding=0, text=[u'Podcast'])
    mp3tags.save(outfile)
示例#23
0
def setStuff(filename, title=None, artist=None, albumArtist=None, album=None, track=None,
             totalTracks=None, year=None, genre=None, artwork=False, write=False, clean=False):
    try:
        audio = MP3(filename)
    except:
        print(" - Failed.")
        return False

    if clean:
        # Delete all tags
        audio.clear()
        audio["TPOS"] = TPOS(encoding=3, text=u"1/1")

    if title is not None:
        audio["TIT2"] = TIT2(encoding=3, text=title)

    if artist is not None:
        audio["TPE1"] = TPE1(encoding=3, text=artist)
        if albumArtist is None:
            audio["TPE2"] = TPE2(encoding=3, text=artist)

    if albumArtist is not None:
        audio["TPE2"] = TPE2(encoding=3, text=albumArtist)
        if artist is None:
            audio["TPE1"] = TPE1(encoding=3, text=albumArtist)

    if album is not None:
        audio["TALB"] = TALB(encoding=3, text=album)

    if track is not None:
        audio["TRCK"] = TRCK(encoding=3, text="%d" % int(track))

    if year is not None:
        audio["TDRC"] = TDRC(encoding=3, text=str(year))

    if genre is not None:
        audio["TCON"] = TCON(encoding=3, text=genre)

    if artwork:
        # Add artwork
        audio.tags.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'',
                data=artwork
            )
        )

    if write:
        audio.save()
        print(" - Done.")
    else:
        print("")
    return audio
示例#24
0
def write_metadata(song_f: pathlib.Path):
    metadata_f = song_f.with_suffix('.json')

    if not metadata_f.exists():
        print(f"No metadata for file '{song_f}'. Skipping.")
        return

    with open(metadata_f, 'r') as f:
        metadata = json.load(f)

    mp3 = MP3(str(song_f))
    if mp3.tags is None:
        mp3.add_tags()
    tags = mp3.tags

    title = metadata.get('title')
    if title:
        tags.add(TIT2(encoding=3, text=title))
    artist = metadata.get('artist')
    if artist:
        tags.add(TPE1(encoding=3, text=artist))
    composer = metadata.get('composer')
    if composer:
        tags.add(TCOM(encoding=3, text=composer))
    album = metadata.get('album')
    if artist:
        tags.add(TALB(encoding=3, text=album))
    albumArtist = metadata.get('albumArtist')
    if albumArtist:
        tags.add(TPE2(encoding=3, text=albumArtist))
    genre = metadata.get('genre')
    if genre:
        tags.add(TCON(encoding=3, text=genre))
    tracknum = metadata.get('trackNumber')
    if tracknum:
        tags.add(TRCK(encoding=3, text=str(tracknum)))
    year = metadata.get('year')
    if year:
        tags.add(TDRC(encoding=3, text=str(year)))
    duration = metadata.get('durationMillis')
    if duration:
        tags.add(TLEN(encoding=3, text=str(duration)))

    albumart_f = song_f.with_name('folder.jpg')
    if albumart_f.is_file():
        with open(albumart_f, 'rb') as f:
            tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc='Front Cover',
                     data=f.read()))

    mp3.save()
示例#25
0
def set_MP3_data(song, song_path):
    """
    Set the meta data if the passed data is mp3.
    """
    # A variable to see if cover image was added.
    IS_IMG_ADDED = False

    try:
        SONG_PATH = os.path.join(defaults.DEFAULT.SONG_TEMP_DIR,
                                 song_path)

        audio = MP3(SONG_PATH, ID3=ID3)
        data = ID3(SONG_PATH)

        # Download the cover image, if failed, pass
        if dwCover(song):
            imagedata = open(defaults.DEFAULT.COVER_IMG, 'rb').read()
            data.add(APIC(3, 'image/jpeg', 3, 'Front cover', imagedata))
            # REmove the image
            os.remove(defaults.DEFAULT.COVER_IMG)
            IS_IMG_ADDED = True

        # If tags are not present then add them
        try:
            audio.add_tags()
        except Exception:
            pass

        audio.save()

        logger.debug("Passed song release date: ", song.release_date)

        data.add(TYER(encoding=3, text=song.release_date))
        data.add(TIT2(encoding=3, text=song.track_name))
        data.add(TPE1(encoding=3, text=song.artist_name))
        data.add(TALB(encoding=3, text=song.collection_name))
        data.add(TCON(encoding=3, text=song.primary_genre_name))
        data.add(TRCK(encoding=3, text=str(song.track_number)))

        data.save()

        defaults.DEFAULT.SONG_NAME_TO_SAVE = song.track_name + '.mp3'

        # Rename the downloaded file
        os.rename(SONG_PATH, os.path.join(
            defaults.DEFAULT.SONG_TEMP_DIR,
            defaults.DEFAULT.SONG_NAME_TO_SAVE
        ))

        return IS_IMG_ADDED

    except Exception as e:
        logger.debug("{}".format(e))
        return e, False
示例#26
0
def write_tags():
    if type_scan == 's':
        music = MP3(path_to_song)

        b = BytesIO()
        results['image'].save(b, format='PNG')

        music.tags.add(TIT2(text=results['title']))
        music.tags.add(TPE1(text=results['artist']))
        music.tags.add(TDRC(text=results['year']))
        music.tags.add(TCON(text=results['genre']))
        music.tags.add(APIC(data=b.getvalue(), mime='image/png'))

        music.tags.save(path_to_song, pathlib_song.name)
    else:
        for s in songs_in_directory:
            if Path(s).suffix != '.mp3':
                continue

            song_path = os_join(path_to_song, s)
            music = MP3(song_path)

            for s_number, s2 in zip(results['track_number'], results['title']):
                if s2.lower() in s.lower():
                    music.tags.add(TIT2(text=s2))
                    music.tags.add(TRCK(text=s_number))
                    break

            b = BytesIO()
            results['image'].save(b, format='PNG')

            music.tags.add(TPE1(text=results['artist']))
            music.tags.add(TDRC(text=results['year']))
            music.tags.add(TCON(text=results['genre']))
            music.tags.add(TALB(text=results['album']))
            music.tags.add(APIC(data=b.getvalue(), mime='image/png'))

            music.tags.save(song_path, pathlib_song.name)
示例#27
0
def set_data(path, song):
    """
    Sets the ID3 meta data of the MP3 file
    found at the end of path.

    Song must be a track object.
    """
    new_song = ID3(path)
    new_song.delete()
    new_song.add(TIT2(encoding=3, text=song.track_name))
    new_song.add(TPE1(encoding=3, text=song.artist_name))
    new_song.add(TALB(encoding=3, text=song.collection_name))
    new_song.add(TCON(encoding=3, text=song.primary_genre_name))
    new_song.save()
    return
示例#28
0
文件: tagHelper.py 项目: memoz/AIGPY
 def _saveMp3(self, coverPath):
     self._handle.tags.add(TIT2(encoding=3, text=self.title))
     self._handle.tags.add(TALB(encoding=3, text=self.album))
     # self._handle.tags.add(TOPE(encoding=3, text=self.albumartist))
     self._handle.tags.add(TPE1(encoding=3, text=self.artist))
     self._handle.tags.add(TCOP(encoding=3, text=self.copyright))
     self._handle.tags.add(TRCK(encoding=3, text=str(self.tracknumber)))
     # self._handle.tags.add(TRCK(encoding=3, text=self.discnum))
     self._handle.tags.add(TCON(encoding=3, text=self.genre))
     self._handle.tags.add(TDRC(encoding=3, text=self.date))
     self._handle.tags.add(TCOM(encoding=3, text=self.composer))
     self._handle.tags.add(TSRC(encoding=3, text=self.isrc))
     self._savePic(coverPath)
     self._handle.save()
     return True
示例#29
0
def tag_file(filename, metadata):
    image = None
    if metadata['artwork_url']:
        download_file('artwork.jpg', metadata['artwork_url'], silent=True)
    if os.path.isfile('artwork.jpg'): image = open('artwork.jpg', 'rb').read()
    if filename.endswith('.mp3'):
        audio = MP3(filename, ID3=ID3)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title'])
        audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist'])
        audio.tags["TDRC"] = TDRC(encoding=3, text=metadata['year'])
        audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre'])
        audio.save()
    elif filename.endswith('.flac'):
        audio = FLAC(filename)
        audio.add_tags()
        if image:
            audio.tags.add(
                APIC(encoding=3,
                     mime='image/jpeg',
                     type=3,
                     desc=u'Cover',
                     data=image))
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    elif filename.endswith('.m4a'):
        audio = MP4(filename)
        audio.add_tags()
        covr = []
        if image: covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG))
        audio.tags['covr'] = covr
        audio.tags['title'] = metadata['title']
        audio.tags['artist'] = metadata['artist']
        audio.tags['year'] = metadata['year']
        audio.tags['genre'] = metadata['genre']
        audio.save()
    if os.path.isfile('artwork.jpg'): os.remove('artwork.jpg')
示例#30
0
    def write_ID3v2(self):
        if MUTAGEN:
            if "MP3" in self.__audio_codec:
                try:
                    tags = ID3(self.__filepath)
                except ID3NoHeaderError:
                    tags = ID3()

                # Track number
                tags["TRCK"] = TRCK(encoding=3,
                                    text=unicode(self.get_tag("track_number")))
                # Title
                tags["TIT2"] = TIT2(encoding=3,
                                    text=unicode(self.get_tag("title")))
                # Artist
                tags["TPE1"] = TPE1(encoding=3,
                                    text=unicode(self.get_tag("artist")))
                # Album
                tags["TALB"] = TALB(encoding=3,
                                    text=unicode(self.get_tag("album")))
                # Year
                tags["TDRC"] = TDRC(encoding=3,
                                    text=unicode(self.get_tag("year")))
                # Genre
                tags["TCON"] = TCON(encoding=3,
                                    text=unicode(self.get_tag("genre")))
                # Comment
                tags["COMM"] = COMM(encoding=3,
                                    lang=u'eng',
                                    desc='desc',
                                    text=unicode(self.get_tag("comment")))
                #tags["COMM"] = COMM(encoding=3, text=unicode(self.get_tag("comment")))
                # Album artist
                tags["TPE2"] = TPE2(encoding=3,
                                    text=unicode(self.get_tag("album_artist")))
                # Composer
                tags["TCOM"] = TCOM(encoding=3,
                                    text=unicode(self.get_tag("composer")))
                # Disc number
                tags["TPOS"] = TPOS(encoding=3,
                                    text=unicode(self.get_tag("disc_number")))
                # Cover
                tags["APIC"] = APIC(3, 'image/jpeg', 3, 'Front cover',
                                    self.get_tag("cover"))

                #tags.update_to_v24()
                tags.save(self.__filepath, v1=2)
示例#31
0
 def test_set_string(self):
     gen = TCON(encoding=0, text="")
     gen.genres = "foo"
     self.assertEquals(gen.genres, ["foo"])
示例#32
0
 def test_set_genre(self):
     gen = TCON(encoding=0, text="")
     self.assertEquals(gen.genres, [])
     gen.genres = ["a genre", "another"]
     self.assertEquals(gen.genres, ["a genre", "another"])
示例#33
0
 def test_nodoubledecode(self):
     gen = TCON(encoding=1, text=u"(255)genre")
     gen.genres = gen.genres
     self.assertEquals(gen.genres, [u"Unknown", u"genre"])