def on_episode_downloaded(self, episode):
        log(u'on_episode_downloaded(%s/%s)' % (episode.channel.title, episode.title))

        filename = episode.local_filename(create=False, check_only=True)
        if filename is None:
            return

        basename, extension = os.path.splitext(filename)
        if episode.file_type() == 'audio' and extension.lower() == '.ogg':
            log(u'trying to remove cover from %s' % filename)
            found = False

            try:
                ogg = OggVorbis(filename)
                for key in ogg.keys():
                    if key.startswith('cover'):
                        found = True
                        ogg[key]=''
                
                if found:
                    log(u'removed cover from the ogg file successfully')
                    ogg.save()
                else:
                    log(u'there was no cover to remove in the ogg file')
            except:
                None
Beispiel #2
0
def set_start(filename, start_time):
    """
    Writes the start of the song section to file
    """
    song_meta = OggVorbis(filename)
    song_meta[Settings.song_start_tag] = start_time
    song_meta.save()
def download_and_fix_ogg(ogg, audio_metadata, cover_art_file):
    global DRY_RUN
    if DRY_RUN:
        print "This is a dry run. So pretending to download the ogg..."
        return "/tmp/ogg"
    print "Now downloading the ogg in order to set the metadata in it..."
    if not LIVE and len(sys.argv) >= 6 and os.path.exists(sys.argv[5]):
        ogg_local_fn = sys.argv[5]
        print "(using presupplied file %s)" % ogg_local_fn
    else:
        f, metadata = client.get_file_and_metadata(ogg)
        ogg_local_fn = fetch_file(f, metadata)
    print "Successfully downloaded (to %s): now editing metadata..." % ogg_local_fn
    audio = OggVorbis(ogg_local_fn)
    for k in audio_metadata.keys():
        audio[k] = audio_metadata[k]
    # add cover art
    im=Image.open(cover_art_file)
    w,h=im.size
    p=Picture()
    imdata=open(cover_art_file,'rb').read()
    p.data=imdata
    p.type=3
    p.desc=''
    p.mime='image/jpeg';
    p.width=w; p.height=h
    p.depth=24
    dt=p.write(); 
    enc=base64.b64encode(dt).decode('ascii');
    audio['metadata_block_picture']=[enc];
    audio.save()
    print "Successfully updated metadata."
    return ogg_local_fn
Beispiel #4
0
    def getFileInfoFromMeta(self, filepath):
        artist = ''
        title = ''
        genre = ''

        musicfile = self.getMusicForCdg(filepath)
        if musicfile:
            name, ext = os.path.splitext(musicfile)
            print "Name:", name
            print "Ext:", ext
            if ext == '.mp3':
                print "MP3"
                try:
                    eid = EasyID3(musicfile)
                    artist = eid.get('artist', [''])[0]
                    title = eid.get('title', [''])[0]
                    genre = eid.get('genre', ['karaoke'])[0]
                    print "Got: (%s, %s, %s)" % (artist, title, genre)
                except ID3NoHeaderError:
                    print "No ID Header for", musicfile
            elif ext == '.ogg':
                audio = OggVorbis(musicfile)
                artist = audio.get('artist', '')[0]
                title = audio.get('title', '')[0]
                genre = audio.get('genre', ['karaoke'])[0]

        return artist, title, genre
class _EasyPythonMutagenOggVorbis(object):
    '''An interface like EasyId3, but for OggVorbis files.'''
    
    def __init__(self, filename):
        from mutagen.oggvorbis import OggVorbis
        self.obj = OggVorbis(filename)
        self.map = {
            'album': 'album',
            'comment': 'comment',
            'artist': 'artist',
            'title': 'title',
            'albumartist': 'albumartist',
            'tracknumber': 'tracknumber',
            'discnumber': 'discnumber',
            'composer': 'composer',
            'genre': 'genre',
            'description': 'description',
            'website': 'www'}
        
    def __getitem__(self, key):
        return self.obj[self.map[key]]
            
    def __setitem__(self, key, val):
        self.obj[self.map[key]] = val
            
    def __contains__(self, key):
        return key in self.map and self.map[key] in self.obj
    
    def save(self):
        self.obj.save()
Beispiel #6
0
class Vorbis(object):
    tags = ['title', 'artist', 'album', 'genre', 'tracknumber']
    def __init__(self, filename):
        self._comment = OggVorbis(filename)
    def write_random_tag(self, data):
        tag = random.choice(Vorbis.tags)
        self._comment[tag] = data
        self._comment.save()
Beispiel #7
0
def ogg_tag(config):
    print("Tagging " + config.ogg_file)
    audio = OggVorbis(config.ogg_file)

    # Add the tags.
    for k in config.tags.keys():
        audio[k] = config.tags[k]
    audio.save()
    def remove_all(self):
        if self.backup is True:
            shutil.copy2(self.filename, self.output)
            self.filename = self.output

        mfile = OggVorbis(self.filename)
        mfile.delete()
        mfile.save()
def add_tag(f, tag, value):
    if f.endswith('ogg'):
        audio = OggVorbis(f)
    elif f.endswith('flac'):
        audio = FLAC(f)
    audio[tag] = value
    # audio.pprint()
    audio.save()
Beispiel #10
0
    def convert(self):
        ''' Convert wav -> ogg.'''
        if self.songwav == self.song:
            success = True
            dec = None
        else:
            success, dec = self.decode()
        if not success:
            warn('Decoding of "%s" failed.' % self.song)
            return

        if dec and self.decoder == 'mpg123':
            import mutagen
            try:
                info("additional option:" )
                opts=['-R', str(mutagen.File(self.song).info.sample_rate)]
                info(str(opts))
            except:
                opts=[]
        else:
            opts=[]

        if dec:
            enc = Popen(['oggenc', '-Q', '-o', self.songogg, '-q', str(self.conf.quality).replace('.', ','), '-'] + opts, stdin=dec.stdout)
            enc.communicate()
            dec.wait()
            if dec.returncode < 0:
                warn('Decoding of "%s" failed.' % self.song)
                return False
            elif enc.returncode < 0:
                warn('Encoding of "%s" failed.' % self.song)
                return False
        else:
            enc = call(['oggenc', '-o', self.songogg, '-q', str(self.conf.quality).replace('.', ','), self.songwav])
            if enc != 0:
                warn('Encoding of "%s" failed.' % self.songwav)
                return False
            elif not self.conf.preserve_wav and self.song != self.songwav:
                os.remove(self.songwav)

        if self.tags != {}:
            try:
                # Add tags to the ogg file
                from mutagen.oggvorbis import OggVorbis
                myogg = OggVorbis(self.songogg)
                myogg.update(self.tags)
                myogg.save()
            except:
                warn('Could not save the tags')
                import traceback
                traceback.print_exc()
                return False
        elif self.songwav != self.song or 'cd-' in self.decoder:
            warn('No tags found...')

        if self.conf.delete_input:
            os.remove(self.song)
        return True
Beispiel #11
0
 def ogg_write_tags(self, path, tag_type, input_string):
     try:
         ogg_audio = OggVorbis(path) #Reading tags
     except:
         print ("No Ogg tag found or %r is not a valid OGG file") \
         % (path.encode(sys.stdout.encoding or "utf-8", "replace"), )
         return
     ogg_audio[tag_type] = input_string
     ogg_audio.save()
Beispiel #12
0
 def test_save_split_setup_packet(self):
     fn = os.path.join(DATA_DIR, "multipage-setup.ogg")
     shutil.copy(fn, self.filename)
     audio = OggVorbis(self.filename)
     tags = audio.tags
     self.failUnless(tags)
     audio.save()
     self.audio = OggVorbis(self.filename)
     self.failUnlessEqual(self.audio.tags, tags)
    def saveLabel(self, file, label):
        '''read file and save label tag'''
        af = OggVorbis(file)

        logger.info( "Tags BEFORE labelizer: " + str(af) )

        af['label'] = label
        af.save()
        logger.info( "Tags AFTER labelizer: " + str(af) )
Beispiel #14
0
	def setValue(path, tag, value):
		format = os.path.splitext(path)[1]
		if(format == ".mp3"):
			audio = EasyID3(path)
		elif(format == ".ogg"):
			audio = OggVorbis(path)
			
		audio[tag] = value
		audio.save()
def _get_OGG_tags(filename):
    tagsOGG = OggVorbis(filename)
    tags = {}
    tags['album'] = ''.join(tagsOGG.get('album', ['']))
    tags['title'] = ''.join(tagsOGG.get('title', ['']))
    tags['artist'] = ''.join(tagsOGG.get('artist', ['']))
    tags['length'] = tagsOGG.info.length * 1000
    tags['genre'] = 'Podcast'
    return tags
Beispiel #16
0
def write_tags_to_ogg(path, tags):
    audio = OggVorbis(path)
    for dest, source in [['TITLE', 'TIT2'], ['ARTIST', 'TPE1'],
                         ['ALBUM', 'TALB'], ['DATE', 'TDRC'],
                         ['COPYRIGHT', 'TCOP'], ['LICENSE', 'WXXX:']]:
        audio[dest] = tags[source]
    audio['coverartmime'] = 'image/jpeg'
    audio['coverartdescription'] = 'Radiotux_ID3Tag.jpg'
    audio['coverart'] = get_ogg_coverart()
    audio.save()
Beispiel #17
0
 def __song_ogg(filename):
     f = OggVorbis(filename)
     artist = f.get("artist", ("",))[0]
     title = f.get("title", ("",))[0]
     rating = 0
     for k, v in f.iteritems():
         if k.startswith("rating"):
             rating = SongFiles.__adjust_rating_ogg(float(v[0]))
             break
     return Song(filename, artist, title, rating)
Beispiel #18
0
def get_ogg_tag_info(f):
  global blankstr
  ret = {"file":f,"length":"0"}
  try:
    i = OggVorbis(f)
    ret["length"] = str(i.info.length)
    for k in ["artist", "album", "year", "tracknumber", "title"]:
      if i.has_key(k):
        ret[k] = str(i[k])
  except Exception, e:
    print("\r%s\rUnable to read OGG info for\n%s" %(blankstr, f))
    print(str(e))
Beispiel #19
0
def walk_audio_files():
        
        tag_count = 0

	for root, dirs, files in os.walk('.'):
		for name in files:
                        
                        audio_set = False

			if name.lower().endswith(".mp3"):
                                try:
                                        audio = ID3(os.path.join(root, name))
                                except Exception, e:
                                        print 'ERROR: ID3 Error %s : %s' % (e, os.path.join(root, name))
                                        continue

				if not select_audio(audio):
					continue
				if tag_mode == TAG_MODE_NORMAL and audio.has_key('TPE1'):
					artist = audio["TPE1"]
					genre = artist_to_genre(artist[0])
					grouping = artist_to_groupings(artist[0])
					if genre != None:
						audio["TCON"] = TCON(encoding=3, text=genre)
                                                audio_set = True
					if grouping != None:
						audio["TIT1"] = TIT1(encoding=3, text=grouping)
                                                audio_set = True
				else:
					if audio.has_key("TIT1"):
						genre = refine_genre(audio["TIT1"].text[0].split(","))
						if genre != "":
							print "Refining genre for artist %s from %s to %s" % (audio["TPE1"].text[0], audio["TCON"].text[0], genre)
							audio["TCON"] = TCON(encoding=3, text=genre)
                                                        audio_set = True


                        elif name.lower().endswith(".ogg"):
                                try:
                                        audio = OggVorbis(os.path.join(root, name))
                                except Exception, e:
                                        print 'ERROR: Ogg Comment Error %s : %s' % (e, os.path.join(root, name))
                                        continue

                                if not audio.has_key('artist'):
                                        print 'ERROR: Vorbis comment has no "artist" key in file %s' % os.path.join(root, name)
                                        continue

                                artist = audio['artist']
                                genre = artist_to_genre(artist[0])
                                if genre != None:
                                        audio["genre"] = genre
                                        audio_set = True
Beispiel #20
0
def CopyTags(source_file, target_file):
    o = OggVorbis(source_file)
    m = EasyID3(target_file)

    for key in ["artist", "title", "album", "date", "genre", "tracknumber"]:
        if o.has_key(key):
            m[key] = o[key]
    m.save()

    if o.has_key("discnumber"):
        m = MP3(target_file)
        m["TPOS"] = TPOS(encoding=3, text=o["discnumber"])
        m.save()
Beispiel #21
0
 def write_tags_ogg(self):
    file = self.file_dir + os.sep + self.filename
    if os.path.exists(file):
         audio = OggVorbis(file)
         audio['TITLE'] = self.new_title.decode('utf8')
         audio['ARTIST'] = self.professor.decode('utf8')
         audio['ALBUM'] = self.organization.decode('utf8')
         audio['DATE'] = self.date.decode('utf8')
         audio['GENRE'] = self.genre.decode('utf8')
         audio['SOURCE'] = self.organization.decode('utf8')
         audio['ENCODER'] = self.encoder.decode('utf8')
         audio['COMMENT'] = self.comment.decode('utf8')
         audio.save()
Beispiel #22
0
class _OggVorbisWrapper(_AbstractWrapper):
    TAG_MAP = {
        'artwork': 'metadata_block_picture',
        'artist': 'artist', 'album': 'album',
        'title': 'title', 'genre': 'genre',
    }
    VALID_TAG_KEYS = ('artwork', 'artist', 'album', 'title', 'genre', )

    def __init__(self, filename):
        _AbstractWrapper.__init__(self)
        self.audio = OggVorbis(filename)

    def __getattr__(self, attr):
        if attr in self.VALID_TAG_KEYS:
            if attr == 'artwork':
                try:
                    raw_artwork_data = b64decode(
                        self.audio['metadata_block_picture'][0])
                    picture = Picture(raw_artwork_data)
                    return Artwork(picture.mime, picture.data)
                except KeyError:
                    return None
            else:
                try:
                    return self.audio[attr][0]
                except KeyError:
                    return None
        raise TagError(self, attr)

    def __setattr__(self, attr, value):
        if attr in self.VALID_TAG_KEYS:
            if isinstance(value, Artwork):
                picture = Picture()
                picture.type = 3
                picture.mime = value.mime
                picture.data = value.data
                self.audio['metadata_block_picture'] = [
                    b64encode(picture.write()).decode('utf-8')
                ]
            elif isinstance(value, str):
                self.audio[attr] = [value]
            else:
                raise TagValueError(value)
        else:
            object.__setattr__(self, attr, value)

    def __repr__(self):
        return repr(self.audio)

    def save(self):
        self.audio.save()
Beispiel #23
0
def get_file_info(filename):
    # Get needed information from file
    name, ext = os.path.splitext(os.path.basename(filename))
    if ext.lower() == ".mp3":
        track = MP3(filename)
        data = ID3(filename)
        title = data["TIT2"].text[0]
    elif ext.lower() == ".ogg":
        track = OggVorbis(filename)
        title = str(track.get("title")).strip('[u"]')
    elif ext.lower() == ".flac":
        track = FLAC(filename)
        title = str(track.get("title")).strip('[u"]')
    return title, int(track.info.length)
 def __load_tags(self, tags, expected):
     m = OggVorbis(self.filename)
     for key, value in tags.iteritems():
         m.tags[key] = value
     m.save()
     song = OggFile(self.filename)
     for key, value in expected.iteritems():
         self.failUnlessEqual(song(key), value)
     if self.MAIN not in expected:
         self.failIf(self.MAIN in song)
     if self.SINGLE not in expected:
         self.failIf(self.SINGLE in song)
     if self.FALLBACK not in expected:
         self.failIf(self.FALLBACK in song)
Beispiel #25
0
    def get(self):
        """
            This is the no update version of musicd, so we read the FS once at
            load to sync the DB and then load the tracks into a template.

            A page refresh is necessary to reflect changes in the track listing.
        """
        library_path = os.path.normpath(Config.absolute_library)

        for root, dirs, files in os.walk(library_path):
            for filename in fnmatch.filter(files, "*.ogg") + fnmatch.filter(files, "*.mp3"):
                path = os.path.join(root, filename)
                track = {}
                try:
                    if re.search(".ogg", filename):
                        audio = OggVorbis(path)
                        track["length"] = audio.info.length
                    elif re.search(".mp3", filename):
                        audio = EasyID3(path)
                        track["length"] = MP3(path).info.length
                except:
                    print "Failed to read tags: %s" % path
                    continue

                for key in audio.keys():
                    if key in Config.tags:
                        track[key] = audio[key].pop()

                track["path"] = re.sub(library_path + "/", "", path)

                spec = {}
                for tag in ["artist", "album", "title"]:
                    if tag in track:
                        spec[tag] = track[tag]

                if not tracks.find_one(spec):
                    print "found %s" % track["path"]
                    tracks.save(track)

        # look for deleted files
        for track in tracks.find():
            path = os.path.join(library_path, track["path"])
            if not os.path.exists(path):
                print "deleting from db: %s" % path
                tracks.remove(track)

        self.render(
            "main.html",
            tracks=tracks.find(fields=Config.tags, sort=[("artist", pymongo.ASCENDING), ("album", pymongo.ASCENDING)]),
        )
Beispiel #26
0
    def SetVirtualData(self, item, col, data):
        print "Set Virtual Data"
        index = self.itemIndexMap[item]
        self.itemDataMap[index][col] = data

        if self._tabclose:
            print "Same row"
            return

        if self._origdata == str(self.itemDataMap[index]):
            print "Data did not change."
            return

        print "Data changed!"
        self._dirty = True
        #SortVirtList.SetVirtualData(self, item, col, data)
        #self.SetStringItem(self, item, col, data)
        artist = self.itemDataMap[index][0]
        title = self.itemDataMap[index][1]
        genre = self.itemDataMap[index][2]
        mtype = self.itemDataMap[index][3]
        path = self.itemDataMap[index][4]

        validexts = ['.mp3', '.ogg']
        name, ext = os.path.splitext(path)
        if ext == ".cdg":
            candidates = glob.glob("%s.*" % name)
            for candidate in candidates:
                name, ext = os.path.splitext(candidate)
                if ext in validexts:
                    path = candidate
                    break

        if mtype in ('mp3', '.mp3'):
            m = MP3(path, ID3=EasyID3)
            try:
                m.add_tags(ID3=EasyID3)
            except mutagen.id3.error:
                print "Already has tag"
        elif mtype in ('ogg', 'ogg'):
            m = OggVorbis(path)
        else:
            print "Unrecognized type."
            return

        m['title'] = title
        m['artist'] = artist
        m['genre'] = genre
        m.save()
        print "Updated data."
Beispiel #27
0
def copy_tags(origen, destino):
    """ Copia los tags de origen a destino """
    for i in range(len(origen)):

        ogg = OggVorbis(origen[i])
        flac = FLAC(destino[i])

        # limpiamos los tags del flac
        # flac.delete();

        for item in ogg.items():
            flac[item[0]] = item[1]

        flac.save()
Beispiel #28
0
 def __load_tags(self, tags, expected):
     m = OggVorbis(self.filename)
     for key, value in tags.iteritems():
         m.tags[key] = value
     m.save()
     song = OggFile(self.filename)
     for key, value in expected.iteritems():
         self.failUnlessEqual(song(key), value)
     if self.MAIN not in expected:
         self.failIf(self.MAIN in song)
     if self.SINGLE not in expected:
         self.failIf(self.SINGLE in song)
     if self.FALLBACK not in expected:
         self.failIf(self.FALLBACK in song)
Beispiel #29
0
    def SetVirtualData(self, item, col, data):
        print "Set Virtual Data"
        index=self.itemIndexMap[item]
        self.itemDataMap[index][col] = data
        
        if self._tabclose:
            print "Same row"
            return
        
        if self._origdata == str(self.itemDataMap[index]):
            print "Data did not change."
            return

        print "Data changed!"
        self._dirty = True
        #SortVirtList.SetVirtualData(self, item, col, data)
        #self.SetStringItem(self, item, col, data)
        artist = self.itemDataMap[index][0]
        title = self.itemDataMap[index][1]
        genre = self.itemDataMap[index][2]
        mtype = self.itemDataMap[index][3]
        path = self.itemDataMap[index][4]

        validexts = ['.mp3', '.ogg']
        name, ext = os.path.splitext(path)
        if ext == ".cdg":
            candidates = glob.glob("%s.*" % name)
            for candidate in candidates:
                name, ext = os.path.splitext(candidate)
                if ext in validexts:
                    path = candidate
                    break

        if mtype in ('mp3', '.mp3'):
            m = MP3(path, ID3=EasyID3)
            try:
                m.add_tags(ID3=EasyID3)
            except mutagen.id3.error:
                print "Already has tag"
        elif mtype in ('ogg', 'ogg'):
            m = OggVorbis(path)
        else:
            print "Unrecognized type."
            return

        m['title'] = title
        m['artist'] = artist
        m['genre'] = genre
        m.save()
        print "Updated data."
Beispiel #30
0
 def test_save_grown_split_setup_packet_reference(self):
     if ogg is None: return
     fn = os.path.join("tests", "data", "multipage-setup.ogg")
     shutil.copy(fn, self.filename)
     audio = OggVorbis(self.filename)
     audio["foobar"] = ["quux" * 50000]
     tags = audio.tags
     self.failUnless(tags)
     audio.save()
     self.audio = OggVorbis(self.filename)
     self.failUnlessEqual(self.audio.tags, tags)
     vfc = ogg.vorbis.VorbisFile(self.filename).comment()
     for key in self.audio:
         self.failUnlessEqual(vfc[key], self.audio[key])
     self.ogg_reference(self.filename)
Beispiel #31
0
 def test_save_grown_split_setup_packet_reference(self):
     if ogg is None: return
     fn = os.path.join("tests", "data", "multipage-setup.ogg")
     shutil.copy(fn, self.filename)
     audio = OggVorbis(self.filename)
     audio["foobar"] = ["quux" * 50000]
     tags = audio.tags
     self.failUnless(tags)
     audio.save()
     self.audio = OggVorbis(self.filename)
     self.failUnlessEqual(self.audio.tags, tags)
     vfc = ogg.vorbis.VorbisFile(self.filename).comment()
     for key in self.audio:
         self.failUnlessEqual(vfc[key], self.audio[key])
     self.ogg_reference(self.filename)
Beispiel #32
0
    def get_album_and_artist(self):
        """ Return Ogg tags for album and artist"""

        self.audio_files.sort()

        for file in self.audio_files:
            try:
                tags = OggVorbis(file)
                if tags:
                    if "album" in tags.keys() and "artist" in tags.keys():
                        return (tags["album"][0], tags["artist"][0])
                        break  # If we found ID3 tag info from a file, no reason to query the rest in a directory.
            except mutagen.oggvorbis.OggVorbisHeaderError:
                continue
        return (None, None)
 def __init__(self, filename):
     from mutagen.oggvorbis import OggVorbis
     self.obj = OggVorbis(filename)
     self.map = {
         'album': 'album',
         'comment': 'comment',
         'artist': 'artist',
         'title': 'title',
         'albumartist': 'albumartist',
         'tracknumber': 'tracknumber',
         'discnumber': 'discnumber',
         'composer': 'composer',
         'genre': 'genre',
         'description': 'description',
         'website': 'www'}
def rename(directory, filename, artist, title, extension, namingConvention):
    if namingConvention == "Artist - Title" or (namingConvention == 'Dynamic'
                                                and ' - ' in filename):
        try:
            os.rename(
                directory + '/' + filename,
                directory + '/' + str(artist) + ' - ' + str(title) + extension)
            filename = str(artist) + ' - ' + str(title) + extension
        except PermissionError:
            messagebox.showinfo(
                "Permission Error",
                "File cannot be renamed, it may still be open")
            return False, False
    elif namingConvention == "Title" or (namingConvention == 'Dynamic'
                                         and ' - ' not in filename):
        try:
            os.rename(directory + '/' + filename,
                      str(directory) + '/' + str(title) + extension)
            filename = str(title) + extension
        except PermissionError:
            messagebox.showinfo(
                "Permission Error",
                "File cannot be renamed, it may still be open")
            return False, False
    if extension == ".wav":
        audio = WAVE(str(directory) + '/' + filename)
        audio["TPE1"] = TPE1(encoding=3, text=artist)
        audio["TIT2"] = TIT2(encoding=3, text=title)
        audio.save()
        return audio, filename
    elif extension == ".flac":
        audio = FLAC(str(directory) + '/' + filename)
        audio['artist'] = artist
        audio['title'] = title
        audio.save()
        return audio, filename
    elif extension == ".aiff":
        audio = AIFF(str(directory) + '/' + filename)
        audio["TPE1"] = TPE1(encoding=3, text=artist)
        audio["TIT2"] = TIT2(encoding=3, text=title)
        audio.save()
        return audio, filename
    elif extension == ".m4a":
        audio = MP4(str(directory) + '/' + filename)
        audio["\xa9ART"] = artist
        audio["\xa9nam"] = title
        audio.save()
        return audio, filename
    elif extension == ".mp3":
        audio = MP3(str(directory) + '/' + filename)
        audio["TPE1"] = TPE1(encoding=3, text=artist)
        audio["TIT2"] = TIT2(encoding=3, text=title)
        audio.save()
        return audio, filename
    elif extension == ".ogg":
        audio = OggVorbis(str(directory) + '/' + filename)
        audio['artist'] = artist
        audio['title'] = title
        audio.save()
        return audio, filename
Beispiel #35
0
def build_index_object(path):
	from mutagen.id3._util import ID3NoHeaderError
	from mutagen.easyid3 import EasyID3
	from mutagen.oggvorbis import OggVorbis

	files = next(os.walk(path))[2]
	index = dict()

	for file in files:
		index[file] = list()
		index[file].append(file)
		meta = None

		try:
			if file.endswith(".mp3"):
				meta = EasyID3(path + file)
			elif file.endswith(".ogg"):
				meta = OggVorbis(path + file)
			else:
				log.info(str.format("No Parser for '%s'."% file ))
				continue
		except ID3NoHeaderError:
			log.warning(str.format("Failed to parse '%s': No ID3Header"% file))
			continue

		for thing in [meta[topic] for topic in meta if topic in VALID_TAGS]:
			index[file].append(*thing)

	return index
Beispiel #36
0
def extract_ogg_tag(path):
    """
		Read tags out of .ogg files encoded with different codecs
		Returns a tuple (tag, error)
	"""
    ogg_tag = None
    error = None

    # Encapsulate all try except blocks in if statements.
    # Only read for tag if it already does not exist.

    if not ogg_tag:
        try:
            # Try to read ogg-Vorbis files
            ogg_tag = OggVorbis(path)

        except Exception:
            # move to next codec type
            pass

    if not ogg_tag:
        try:
            # Try to read ogg-FLAC files
            ogg_tag = OggFLAC(path)

        except Exception:
            # move to next codec type
            pass

    if not ogg_tag:
        # log error for user to see
        error = 'Unable to read metadata from the .ogg/.oga file. Only Vorbis and FLAC are supported.'

    return (ogg_tag, error)
Beispiel #37
0
    def read(self):
        """
        Read the informations from the ogg vorbis tags
        """
        tags = OggVorbis(self.filename)

        try:
            self.name = tags["title"][0]
        except (KeyError, IndexError):
            pass

        try:
            self.license = tags["copyright"][0]
        except (KeyError, IndexError):
            pass

        try:
            self.author = tags["artist"][0]
        except (KeyError, IndexError):
            pass

        try:
            self.url = tags["contact"][0]
        except (KeyError, IndexError):
            pass
Beispiel #38
0
    def __init__(self, location):
        self.meta = dict()
        self.trackmetas = [
            'ID', 'title', 'album', 'artist', 'date', 'genre', 'length',
            'description'
        ]
        self.doNotAdd = False
        if os.path.splitext(location)[1].lower() == u'.mp3':
            try:
                self.file = EasyID3(location)
                self.mp3 = MP3(location)
            except ID3NoHeaderError:
                self.doNotAdd = True
                print 'No ID3 tags found for ' + location + ', so not adding to library.'
                return
            self.fileType = 'mp3'

        elif os.path.splitext(location)[1].lower() == '.flac':
            self.file = FLAC(location)
            self.fileType = 'flac'
        elif os.path.splitext(location)[1].lower() == '.ogg':
            self.file = OggVorbis(location)
            self.fileType = 'ogg'
        self.meta['location'] = location
        for item in self.trackmetas:
            self.readTag(item)
Beispiel #39
0
def find_release_mbids(albums):
    albums_aid_map = {}
    albums_gid_map = {}
    without_info = []
    for a in albums:
        filepath = os.path.join(a, os.listdir(a)[0])
        file_extension = filepath.split('.')[-1]
        if file_extension == 'mp3':
            id3_metadata = ID3(filepath)
            album_id = safe_get(id3_metadata, 'TXXX:MusicBrainz Album Id')
            album_gid = safe_get(id3_metadata,
                                 'TXXX:MusicBrainz Release Group Id')
        elif file_extension == 'flac' or file_extension == 'ogg':
            vorbis_metadata = FLAC(
                filepath) if file_extension == 'flac' else OggVorbis(filepath)
            album_id = squeeze(safe_get(vorbis_metadata,
                                        'musicbrainz_albumid'))
            album_gid = squeeze(
                safe_get(vorbis_metadata, 'musicbrainz_releasegroupid'))
        else:
            print('Unsupported file extension [{}] in album {}'.format(
                file_extension, a))
            continue

        if len(album_id) == 0 and len(album_gid) == 0:
            without_info.append(a)
        else:
            if len(album_id) != 0:
                albums_aid_map[album_id] = a
            if len(album_gid) != 0:
                albums_gid_map[album_gid] = a

    return albums_aid_map, albums_gid_map, without_info
Beispiel #40
0
def read_metainfo(path):
    ext = path[-3:].lower()
    if ext == 'mp3':
        audio = EasyID3(path)
    elif ext == 'ogg':
        audio = OggVorbis(path)
    return audio
Beispiel #41
0
def get_tag_values(filename):
    """Function to get the tag values."""
    # Initialise variables
    artist = ""
    album_artist = ""
    album = ""
    trackno = ""
    trackna = ""
    duration = ""
    genre = ""
    year = ""

    if filename.endswith('.mp3'):
        audio = MP3(filename)

        artist = mtl_mp3.artist(audio)
        album_artist = mtl_mp3.album_artist(audio)
        album = mtl_mp3.album(audio)
        trackno = mtl_mp3.trackno(audio)
        trackna = mtl_mp3.trackna(audio)
        duration = mtl_mp3.length(audio)
        genre = mtl_mp3.genre(audio)
        year = mtl_mp3.year(audio)

    elif filename.endswith('.flac'):
        audio = FLAC(filename)

        artist = mtl_flac.artist(audio)
        album_artist = mtl_flac.album_artist(audio)
        album = mtl_flac.album(audio)
        trackno = mtl_flac.trackno(audio)
        trackna = mtl_flac.trackna(audio)
        duration = mtl_flac.duration(audio)
        genre = mtl_flac.genre(audio)
        year = mtl_flac.year(audio)

    elif filename.endswith('.ogg'):
        audio = OggVorbis(filename)

        artist = mtl_flac.artist(audio)
        album_artist = mtl_flac.album_artist(audio)
        album = mtl_flac.album(audio)
        trackno = mtl_flac.trackno(audio)
        trackna = mtl_flac.trackna(audio)
        duration = mtl_flac.duration(audio)
        genre = mtl_flac.genre(audio)
        year = mtl_flac.year(audio)

    album_tags = {
        'artist': artist,
        'album_artist': album_artist,
        'album': album,
        'trackno': trackno,
        'trackna': trackna,
        'duration': duration,
        'genre': genre,
        'year': year
    }

    return album_tags
Beispiel #42
0
def SearchMusicFiles(dir):
    fileList = []
    ProcessFile = []
    for ext in (SUPPORTEDFILES):
        fileList.append(glob.glob((dir + "/**/*" + ext), recursive=True))
    for SFiles in SUPPORTEDFILES:
        if SFiles == ".flac":
            for y in range(len(fileList[0])):
                MFile = FLAC(fileList[0][y])
                not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
        elif SFiles == ".ogg":
            for y in range(len(fileList[1])):
                MFile = OggVorbis(fileList[1][y])
                not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
        elif SFiles == ".mp3":
            for y in range(len(fileList[2])):
                try:
                    MFile = EasyID3(fileList[2][y])
                    not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
                except:
                    MFile = MP3(fileList[2][y])
                    not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
        elif SFiles == ".m4a" or SFiles == ".mp4":
            for y in range(len(fileList[3])):
                MFile = EasyMP4(fileList[3][y])
                not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
            for y in range(len(fileList[4])):
                MFile = EasyMP4(fileList[4][y])
                not GetLyricsInFiles(MFile) and ProcessFile.append(MFile)
    return ProcessFile
Beispiel #43
0
def get_gain(mime, music_file):
    gain = None

    try:
        if mime == 'audio/mpeg':
            # mp3gain stores replay gain info in an APEv2 tag, not ID3.
            apev2 = APEv2(music_file)
            gain = apev2['REPLAYGAIN_TRACK_GAIN'].value

        elif mime == 'application/ogg':
            tags = OggVorbis(music_file)
            gain = tags['replaygain_track_gain'][0]

        elif mime == 'audio/mp4':
            tags = MP4(music_file)
            gain = tags['----:com.apple.iTunes:replaygain_track_gain'][
                0]  # Oh, how I wish I were kidding

        elif mime == 'audio/x-flac':
            tags = FLAC(music_file)
            gain = tags['replaygain_track_gain'][0]

    except:
        pass  # Lazily we assume that if anything went wrong it's because the tag was not there

    if gain:
        # We have e.g. -3.100000 dB. Remove the "dB" and convert to float
        gain = float(gain.split(" ")[0])
    return gain
Beispiel #44
0
    def __init__(self, media):
        MediaBase.__init__(self)

        self.description = "OGG Vorbis"
        self.mime_type = 'audio/ogg'
        self.extension = 'ogg'
        self.format = 'OGG'

        self.media = media
        self.sourceobj = OggVorbis(self.media)
        self.source = self.media
        self.bitrate_default = '192'

        self.tagdata = {
            'title': '',
            'artist': '',
            'album': '',
            'date': '',
            'comment': '',
            'genre': '',
            'copyright': ''
        }

        self.info = self.sourceobj.info
        self.bitrate = int(str(self.info.bitrate)[:-3])
        self.length = datetime.timedelta(0, self.info.length)
        self.read_file_metadata()
        self.media_info = get_file_info(self.media)
        self.file_name = self.media_info[0]
        self.file_title = self.media_info[1]
        self.file_ext = self.media_info[2]
        self.size = os.path.getsize(self.media)
    def __init__(self, filename, mastervolume):
        """
        Create a volume object from an ogg file. mastervolume is a
        reference to a MasterVolume object that will control this
        sound.
        """
        self.filename = filename

        # Read the title in the ogg vorbis tags
        tags = OggVorbis(filename)
        try:
            name = tags["title"][0]
        except KeyError:
            basename = os.path.basename(filename)
            name, ext = os.path.splitext(basename)
        Volume.__init__(self, name)

        try:
            self.index = int(tags["tracknumber"][0])
        except KeyError:
            self.index = 0

        # Link with the MasterVolume object
        self.mastervolume = mastervolume

        # The pygame.mixer.Sound object (only loaded when necessary)
        self.sound = None
Beispiel #46
0
def write_tags_to_ogg(path, tags):
    audio = OggVorbis(path)
    for dest, source in [['TITLE', 'title'], ['COMPOSER', 'composer'],
                         ['ALBUM', 'album'], ['DATE', 'date'],
                         ['ARTIST', 'artist'], ['GENRE', 'genre'],
                         ['ALBUMARTIST', 'album-artist'],
                         ['TRACKNUMBER', 'track'],
                         ['TRACKTOTAL', 'number-of-tracks'], ['DISCNUMBER',
                          'disc'], ['COMMENT', 'comment']]:
        if source in tags:
            audio[dest] = tags[source]
    if 'cover' in tags:
        audio['coverartmime'] = 'image/jpeg'
        audio['coverartdescription'] = 'Cover'
        audio['coverarttype'] = '3'
        audio['coverart'] = get_ogg_coverart(tags['cover'])
    audio.save()
Beispiel #47
0
 def findOGGTags(self):
     try:
         audio = OggVorbis(self.file)
     except:
         if self.debug:
             print("Could not get OGG tags for {0}".format(self.file))
         audio = None
     self.tagsOGG = audio
Beispiel #48
0
 def getMediawrapper(self, filename):
     root, ext = os.path.splitext(filename.lower())
     if (ext == '.mp3'): mediawrapper = ID3(filename)
     elif (ext == '.m4a'): mediawrapper = MP4(filename)
     elif (ext == '.ogg'): mediawrapper = OggVorbis(filename)
     elif (ext == '.flac'): mediawrapper = FLAC(filename)
     else: mediawrapper = mutagen.File(filename)
     return mediawrapper
Beispiel #49
0
def getTrack(filename):
    """ Return a Track created from an Ogg Vorbis file """
    from mutagen.oggvorbis import OggVorbis

    oggFile = OggVorbis(filename)

    length = int(round(oggFile.info.length))
    bitrate = int(oggFile.info.bitrate)
    samplerate = int(oggFile.info.sample_rate)

    try:
        title = str(oggFile['title'][0])
    except:
        title = None

    try:
        album = str(oggFile['album'][0])
    except:
        album = None

    try:
        artist = str(oggFile['artist'][0])
    except:
        artist = None

    try:
        albumArtist = str(oggFile['albumartist'][0])
    except:
        albumArtist = None

    try:
        genre = str(oggFile['genre'][0])
    except:
        genre = None

    try:
        musicbrainzId = str(oggFile['musicbrainz_trackid'][0])
    except:
        musicbrainzId = None

    try:
        trackNumber = str(oggFile['tracknumber'][0])
    except:
        trackNumber = None

    try:
        discNumber = str(oggFile['discnumber'][0])
    except:
        discNumber = None

    try:
        date = str(oggFile['date'][0])
    except:
        date = None

    return createFileTrack(filename, bitrate, length, samplerate, True, title,
                           album, artist, albumArtist, musicbrainzId, genre,
                           trackNumber, date, discNumber)
Beispiel #50
0
	def clean(self):
		file = self.cleaned_data.get('file', False)
		acceptedMime = ['audio/mpeg', 'audio/mpeg3', 'audio/x-mpeg-3', 'audio/ogg', 'application/ogg', 'audio/x-ogg', 'application/x-ogg', 'video/ogg', 'audio/wav', 'audio/x-wav', 'audio/wave', 'audio/x-pn-wav']
		type = "none"
		if file:
			if file._size > 10*1024*1024:
				raise forms.ValidationError(file.name + ': File too large. Max Limit: 10MB')
			elif not file.content_type in acceptedMime:
				raise forms.ValidationError(file.name + ': It is not a mp3, ogg, or wav file')

			try:
				OggVorbis(file.temporary_file_path())
				type = 'OGG'
			except:
				pass

			try:
				OggFLAC(file.temporary_file_path())
				type = 'OGG'
			except:
				pass

			try:
				OggOpus(file.temporary_file_path())
				type = 'OGG'
			except:
				pass

			try:
				OggSpeex(file.temporary_file_path())
				type = 'OGG'
			except:
				pass

			try:
				OggTheora(file.temporary_file_path())
				type = 'OGG'
			except:
				pass

			try:
				MP3(file.temporary_file_path())
				type = 'MP3'
			except:
				pass

			try:
				WavPack(file.temporary_file_path())
				type = 'WAV'
			except:
				pass

			if not type in ['OGG', 'MP3', 'WAV']:
				raise forms.ValidationError(file.name + ': Unsupported file type')

			return file
		else:
			raise forms.ValidationError(file.name + ': File cannot be opened')
Beispiel #51
0
    def add_ogg(self,
                path='',
                filename='file.ogg',
                artist='',
                album='',
                title='',
                tracknum=None,
                year=None,
                group='',
                conductor='',
                composer='',
                basefile='silence.ogg',
                apply_tags=True):
        """
        Adds a new ogg with the given parameters to our library.

        Pass in ``False`` for ``apply_tags`` to only use whatever tags happen to
        be present in the source basefile.
        """

        full_filename = self.add_file(basefile, filename, path=path)

        # Finish here if we've been told to.
        if not apply_tags:
            return

        # Apply the tags as specified
        tags = OggVorbis(full_filename)
        tags['ARTIST'] = artist
        tags['ALBUM'] = album
        tags['TITLE'] = title

        if group != '':
            tags['ENSEMBLE'] = group
        if conductor != '':
            tags['CONDUCTOR'] = conductor
        if composer != '':
            tags['COMPOSER'] = composer
        if tracknum is not None:
            tags['TRACKNUMBER'] = str(tracknum)
        if year is not None:
            tags['DATE'] = str(year)

        # Save to our filename
        tags.save()
Beispiel #52
0
    def rm_ogg_cover(self, episode):
        filename = episode.local_filename(create=False)
        if filename is None:
            return

        basename, extension = os.path.splitext(filename)

        if episode.file_type() != 'audio':
            return

        if extension.lower() != '.ogg':
            return

        try:
            ogg = OggVorbis(filename)

            found = False
            for key in ogg.keys():
                if key.startswith('cover'):
                    found = True
                    ogg.pop(key)

            if found:
                logger.info('Removed cover art from OGG file: %s', filename)
                ogg.save()
        except Exception, e:
            logger.warn('Failed to remove OGG cover: %s', e, exc_info=True)
Beispiel #53
0
def get_tags(audio_file, audio_format):
    print("Getting tags from " + audio_file)
    if audio_format is 'mp3':
        return EasyID3(audio_file)
    elif audio_format is 'ogg':
        return OggVorbis(audio_file)
    else:
        print("ERROR! Unknown audio format. Abort.")
        sys.exit(1)
Beispiel #54
0
 def __init__(self, file, threshold=60, duration_distance_threshold=10000):
     self.file = file
     self.threshold = threshold
     self.ddt = duration_distance_threshold
     self.cleaner = re.compile(r"[^A-Za-z0-9 ]").sub
     try:
         self.audio = MP3(file, ID3=EasyID3)
     except:
         try:
             self.audio = FLAC(file)
         except:
             try:
                 self.audio = OggVorbis(file)
             except:
                 try:
                     self.audio = OggFLAC(file)
                 except:
                     try:
                         self.audio = OggTheora(file)
                     except:
                         try:
                             self.audio = APEv2(file)
                         except:
                             try:
                                 self.audio = ASF(file)
                             except:
                                 try:
                                     self.audio = MP4(file)
                                 except:
                                     try:
                                         self.audio = Musepack(file)
                                     except:
                                         try:
                                             self.audio = TrueAudio(file)
                                         except:
                                             try:
                                                 self.audio = WavPack(file)
                                             except:
                                                 raise FileTypeException(
                                                     'Unknown file type, no metadata, or file not found.'
                                                 )
     try:
         [title] = self.audio['title']
         self.title = self.__clean_literal(str(title))
     except:
         self.title = None
     try:
         [artist] = self.audio['artist']
         self.artist = self.__clean_literal(str(artist))
     except:
         self.artist = None
     try:
         [album] = self.audio['album']
         self.album = self.__clean_literal(str(album))
     except:
         self.album = None
     self.mbzQuery()
 def handleOGG(self):
     from mutagen.oggvorbis import OggVorbis
     f = OggVorbis(self.fileName)
     for tag in f.tags:   # pylint: disable=not-an-iterable
         if tag[0].upper() == 'FMPS_RATING':
             frame = tag[1]
             print ("flac rating is", frame)
             self.rating = float(frame) * 10
             return
Beispiel #56
0
 def is_clean(self):
     '''
         Check if the "metadata" block is present in the file
     '''
     mfile = OggVorbis(self.filename)
     if mfile.tags == []:
         return True
     else:
         return False
Beispiel #57
0
 def get_meta(self):
     '''
         Return the content of the metadata block if present
     '''
     metadata = {}
     mfile = OggVorbis(self.filename)
     for key, value in mfile.tags:
         metadata[key] = value
     return metadata
Beispiel #58
0
def updateCoverOgg(lossyFileName, artworkFileName):
    #
    # Embed album art into transcoded file: OGG
    #
    import base64
    from mutagen.oggvorbis import OggVorbis
    from mutagen.flac import Picture
    import PIL.Image
    import tempfile
    from shutil import copyfile  # Use copyfile b/c this will *not* copy rights (which is error prone on gvfs/samba)

    log('- embedding album art ' + artworkFileName + ' to ' + lossyFileName)

    # Copy lossy file to a local location; to prevent (save) errors in a samba environment
    tempLossyFile = tempfile.gettempdir() + '/' + 'temp.ogg'
    copyfile(lossyFileName, tempLossyFile)

    # Embed the image
    o = OggVorbis(tempLossyFile)

    im = PIL.Image.open(artworkFileName)
    w, h = im.size

    p = Picture()
    imdata = open(artworkFileName, 'rb').read()
    p.data = imdata
    p.type = 3
    p.desc = ''
    p.mime = 'image/jpeg'
    p.width = w
    p.height = h
    p.depth = 24

    dt = p.write()
    enc = base64.b64encode(dt).decode('ascii')
    o['metadata_block_picture'] = [enc]
    o.save()

    # Now we are ready; copy the file to the desired output directory
    copyfile(tempLossyFile, lossyFileName)
    os.remove(tempLossyFile)  # Remove the temporary file(s)

    return
Beispiel #59
0
def read_ogg_tags(song, path):

    audio = OggVorbis(path)
    song[Song.artist] = get_str(audio, "artist", "unknown artist")
    song[Song.album] = get_str(audio, "album", "unknown album")
    song[Song.title] = get_str(audio, "title", "unknown title")
    song[Song.genre] = get_str(audio, "genre", "unknown genre")
    song[Song.album_index] = get_int(audio, 'tracknumber')
    song[Song.year] = get_int(audio, "date", '-')
    song[Song.length] = int(audio.info.length)
Beispiel #60
0
def run_ogg_info(filename):
    """Uses `Mutagen` library instead"""
    # This will capture, as a dictionary, the title, album etc.
    # However, each member will be a list, so grab 1st entry.
    data = OggVorbis(filename)
    # Can extract the length from data.info member
    length = math.ceil(data.info.length)
    # Return
    return OggInfo(data["title"][0], data["artist"][0], data["album"][0],
                   data["tracknumber"][0], length)