Ejemplo n.º 1
0
def fix_music():
    '''
    Searches for '.mp3' files in directory
    and checks whether they already contain album art
    and album name tags or not.
    '''

    files = [f for f in listdir('.') if f[-4:] == '.mp3']

    for file_name in files:
        tags = File(file_name)

        if 'APIC:Cover' in tags.keys() and 'TALB' in tags.keys(
        ):  #Checks whether there is album art and album name
            print("%s already has tags " % tags["TIT2"])

        elif not ('APIC:Cover' in tags.keys()) and 'TALB' in tags.keys():
            album = tags["TALB"].text[0]
            print("........................\n")

            print("%s Adding metadata" % file_name)

            try:
                albumart = albumsearch.img_search_google(album)
            except Exception:
                albumart = albumsearch.img_search_bing(album)

            add_albumart(albumart, file_name)

        else:
            print("........................\n")

            print("%s Adding metadata" % file_name)

            try:
                artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
                    file_name)  # Try finding details through spotify

            except Exception:
                artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
                    file_name)  # Use bad scraping method as last resort

            try:
                print('*Trying to extract album art from Google.com')
                albumart = albumsearch.img_search_google(album)
            except Exception:
                print('*Trying to extract album art from Bing.com')
                albumart = albumsearch.img_search_bing(album)

            if match_bool:
                add_albumart(albumart, file_name)
                add_details(file_name, song_name, artist, album, lyrics)
            else:
                print("*Couldn't find appropriate details of your song")
                with open("musicrepair_log.txt", "a") as problems:
                    problems.write(str(file_name) +
                                   '\n')  #log song that couldn't be repaired

            print("\nMatch score : %s%s" % (round(score * 10, 1), "/10.0"))
            print("........................\n\n")
def getSongInfo(inputFile):
    info = {}
    # detect format and type of tags
    file = File(inputFile)
    """
    if 'APIC:' in file.keys():
        artwork = file.tags['APIC:'].data # access APIC frame and grab the image
        with open('./image.jpg', 'wb') as img:
            img.write(artwork) # write artwork to new image
    """
    # check for album art existence
    if "APIC:" in file.keys():
        artwork = file.tags["APIC:"].data  # access APIC frame and grab the image
        # extract image
        info["image"] = artwork

    # extract title
    info["title"] = str(file["TIT2"][0])
    # extract artist
    info["artist"] = str(file["TPE1"][0])
    # extract album
    info["album"] = str(file["TALB"][0])
    if "TDRC" in file.keys():
        # extract year
        info["year"] = str(file["TDRC"][0])
    if "TCON" in file.keys():
        # extract genre
        info["genre"] = str(file["TCON"][0])
    if "TPUB" in file.keys():
        # extract publisher
        info["publisher"] = str(file["TPUB"][0])
    # extract length / duration
    info["length"] = str(round(file.info.length / 60, 2))

    return info
Ejemplo n.º 3
0
def fix_music(rename_format, norename, files):
    """ 
    Checks whether files already contain album art and album name tags or not. 
    If not, calls other functions to add album art, details.
    """

    for file_path in files:
        tags = File(file_path)
        #Gets file name and removes .mp3 for better search results
        file_name = basename(file_path)[:-4]

        # Checks whether there is album art and album name
        if 'APIC:Cover' in tags.keys() and 'TALB' in tags.keys():
            log.log('%s already has tags ' % tags["TIT2"])

        elif not ('APIC:Cover' in tags.keys()) and 'TALB' in tags.keys():
            album = tags["TALB"].text[0]

            log.log(LOG_LINE_SEPERATOR)
            log.log(file_path)
            log.log('> Adding metadata')

            add_albumart(album, file_path)

        else:
            log.log(LOG_LINE_SEPERATOR)
            log.log(file_path)
            log.log('> Adding metadata')

            try:
                artist, album, song_name, lyrics = get_details_spotify(
                    file_name)
                add_albumart(artist + ' ' + album, file_path)
                add_details(file_path, song_name, artist, album, lyrics)
            except Exception:
                log.log_error("* Couldn't find metadata from Spotify")

            try:
                if not norename:
                    song_title = rename_format.format(title=song_name + '-',
                                                      artist=artist + '-',
                                                      album=album + '-')

                    song_title = song_title[:-1] if song_title.endswith(
                        '-') else song_title
                    rename(
                        file_path,
                        path.dirname(file_path) +
                        '/{song_title}.mp3'.format(song_title=song_title))

            except Exception:
                pass
Ejemplo n.º 4
0
def fix_cover(audio: File):
    """
    Transfers album cover from audio key APIC:XXXX to APIC:
    Example
    audio['APIC: Payday 2.jpg'] = APIC() becomes audio['APIC:'] = APIC()
    """
    restart = False
    for k in audio.keys():
        if k.startswith('APIC:') and k != 'APIC:':
            apic = audio.pop(k)
            apic.desc = ''
            apic.encoding = 0
            audio['APIC:'] = apic
            audio.save()
            restart = True
            break
        elif k == 'APIC:' and audio[k].encoding != 0:
            apic = audio.pop(k)
            apic.desc = ''
            apic.encoding = 0
            audio[k] = apic
            audio.save()
            restart = True
            break
    if restart: fix_cover(audio)
Ejemplo n.º 5
0
    def cleanup_tags(self) -> None:
        '''Delete any ReplayGain tags from track.

        This dicards any unsaved changes, then modifies and saves the
        track's tags on disk and then reloads the new tags from
        disk.

        '''
        tags_to_clean = set(rg_tags) # type: Set[str]
        tags_to_clean.update('QuodLibet::' + tag for tag in rg_tags)
        tags_to_clean.update('TXXX:' + tag for tag in rg_tags)
        tags_to_clean.update(['RVA2:track', 'RVA2:album'])
        tags_to_clean = { tag.lower() for tag in tags_to_clean }
        # Need a non-easy interface for proper ID3 cleanup
        t = MusicFile(self.filename, easy=False)
        tags_to_delete = []
        for k in t.keys():
            if k.lower() in tags_to_clean:
                tags_to_delete.append(k)
        for k in tags_to_delete:
            logger.debug("Deleting tag: %s", repr(k))
            del t[k]
        t.save()
        # Re-init to pick up tag changes
        new_track = type(self.track)(self.filename)
        self.track = new_track
Ejemplo n.º 6
0
def updatemusic():
    db = model()
    musiclist = glob.glob(MUSICFOLDER + "*.mp3")
    musicnames = [mi.split("/")[-1] for mi in musiclist]

    indb = [
        msi.arquivo for msi in db().iterselect(db.musica.arquivo)
        if msi.arquivo in musicnames
    ]

    notindb = list(set(musicnames) - set(indb))

    for msi in notindb:
        tag = File(MUSICFOLDER + msi)
        tempo = sec2minString(File(MUSICFOLDER + msi).info.length)
        if ('TIT2' in tag.keys()):
            db.musica.insert(nome=tag['TIT2'].text[0],
                             cantor=tag['TPE1'].text[0],
                             arquivo=msi,
                             tempo=tempo)
        else:
            db.musica.insert(arquivo=msi, tempo=tempo)

    notindir = [
        msi.arquivo for msi in db().iterselect(db.musica.arquivo)
        if msi.arquivo not in musicnames
    ]

    for msi in notindir:
        db(db.musica.arquivo == msi).delete()

    db.commit()
Ejemplo n.º 7
0
    def cleanup_tags(self) -> None:
        '''Delete any ReplayGain tags from track.

        This dicards any unsaved changes, then modifies and saves the
        track's tags on disk and then reloads the new tags from
        disk.

        '''
        tags_to_clean = set(rg_tags) # type: Set[str]
        tags_to_clean.update('QuodLibet::' + tag for tag in rg_tags)
        tags_to_clean.update('TXXX:' + tag for tag in rg_tags)
        tags_to_clean.update(['RVA2:track', 'RVA2:album'])
        tags_to_clean = { tag.lower() for tag in tags_to_clean }
        # Need a non-easy interface for proper ID3 cleanup
        t = MusicFile(self.filename, easy=False)
        tags_to_delete = []
        for k in t.keys():
            if k.lower() in tags_to_clean:
                tags_to_delete.append(k)
        for k in tags_to_delete:
            logger.debug("Deleting tag: %s", repr(k))
            del t[k]
        t.save()
        # Re-init to pick up tag changes
        new_track = type(self.track)(self.filename)
        self.track = new_track
Ejemplo n.º 8
0
def fix_music(rename_format, norename, files):
    """ 
    Checks whether files already contain album art and album name tags or not. 
    If not, calls other functions to add album art, details.
    """

    for file_path in files:
        tags = File(file_path)
        # Gets file name and removes .mp3 for better search results
        file_name = basename(file_path)[:-4]

        # Checks whether there is album art and album name
        if 'APIC:Cover' in tags.keys() and 'TALB' in tags.keys():
            print('%s already has tags' % tags["TIT2"])

        else:
            print('> ' + file_path)

            try:
                artist, album, song_name, albumart = musictools.get_metadata(
                    file_name, SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET)
                add_lyrics_genius(file_path, file_name)
                musictools.add_album_art(file_path, albumart)
                musictools.add_metadata(file_path, song_name, artist, album)

            except Exception as e:  # MetadataNotFound
                print(e)
                song_name = file_name
                album = "Unknown"
                artist = "Unknown"
                print('Could not find metadata')

            print('{}\n{}\n{}\n'.format(song_name, album, artist))

            if not norename:

                song_title = rename_format.format(title=song_name + ' -',
                                                  artist=artist + ' -',
                                                  album=album + ' -')

                song_title = song_title[:-1] if song_title.endswith(
                    '-') else song_title
                new_path = path.dirname(file_path) + '{}.mp3'.format(
                    song_title)

                rename(file_path, new_path)
Ejemplo n.º 9
0
        def from_tags(path: str) -> Optional[bytes]:
            """Get an album cover from a file's meta tags."""
            file = File(path)

            for tag in file.keys():
                if tag.startswith("APIC:"):
                    return file.tags[tag].data

            return None
Ejemplo n.º 10
0
def fix_cover(audio: File):
    """
    Transfers album cover from audio key APIC:XXXX to APIC:
    Example
    audio['APIC: Payday 2.jpg'] = APIC() becomes audio['APIC:'] = APIC()
     """
    for k in audio.keys():
        if k.startswith('APIC:') and k != 'APIC:':
            audio['APIC:'] = audio.pop(k)
            audio.save()
            break
Ejemplo n.º 11
0
def fix_music():
    '''
    Searches for '.mp3' files in directory
    and checks whether they already contain album art
    and album name tags or not.
    '''

    files = [f for f in listdir(music_dir) if f[-4:] == '.mp3']

    for file_name in files:
        tags = File(file_name)

        if 'APIC:Cover' in tags.keys() and 'TALB' in tags.keys():
            print("%s already has tags " % tags["TIT2"])

        elif not('APIC:Cover' in tags.keys()) and 'TALB' in tags.keys():
            album = tags["TALB"].text[0]
            print("........................\n")

            print("%s Adding metadata" % file_name)

            albumart = get_albumart(album)
            add_albumart(albumart, file_name)

        else:
            print("........................\n")

            print("%s Adding metadata" % file_name)

            try:
                artist, album, song_name, lyrics = get_details_spotify(
                    file_name)  # Try finding details through spotify

            except TypeError:
                artist, album, song_name, lyrics = get_details_letssingit(
                    file_name)  # Use bad scraping method as last resort

            albumart = get_albumart(album)

            add_albumart(albumart, file_name)
            add_details(file_name, song_name, artist, album, lyrics)
Ejemplo n.º 12
0
def get_cover_art(song):
  if song.path == 'None':
    return None
  file = File(song.path)
  APIC = None
  for key in file.keys():
    if 'APIC:' in key:
      APIC = key
  if APIC is None:
    return None
  artwork = file.tags[APIC].data
  return artwork
Ejemplo n.º 13
0
def get_cover_art(song):
    if song.path == 'None':
        return None
    file = File(song.path)
    APIC = None
    for key in file.keys():
        if 'APIC:' in key:
            APIC = key
    if APIC is None:
        return None
    artwork = file.tags[APIC].data
    return artwork
Ejemplo n.º 14
0
def unique_id(filename):
    f = File(filename)
    if 'APIC:' in f: del f['APIC:']
    if 'COMM::XXX' in f: del f['COMM::XXX']
    keys = list(f.keys())
    keys.sort()
    value = ''
    for k in keys:
        v = [str(i) for i in f[k].text]
        v.sort()
        value = value + '%s;' % (','.join(v))
    value = base64.b64encode(value.encode()).decode()
    return value
Ejemplo n.º 15
0
def getSongInfo(inputFile):
    info = {}
    # detect format and type of tags
    file = File(inputFile)
    '''
    if 'APIC:' in file.keys():
        artwork = file.tags['APIC:'].data # access APIC frame and grab the image
        with open('./image.jpg', 'wb') as img:
            img.write(artwork) # write artwork to new image
    '''
    # check for album art existence
    if 'APIC:' in file.keys():
        artwork = file.tags[
            'APIC:'].data  # access APIC frame and grab the image
        # extract image
        info['image'] = artwork

    # extract title
    info['title'] = str(file['TIT2'][0])
    # extract artist
    info['artist'] = str(file['TPE1'][0])
    # extract album
    info['album'] = str(file['TALB'][0])
    if 'TDRC' in file.keys():
        # extract year
        info['year'] = str(file['TDRC'][0])
    if 'TCON' in file.keys():
        # extract genre
        info['genre'] = str(file['TCON'][0])
    if 'TPUB' in file.keys():
        # extract publisher
        info['publisher'] = str(file['TPUB'][0])
    # extract length / duration
    info['length'] = str(round(file.info.length / 60, 2))

    return info
Ejemplo n.º 16
0
def home():
    musiclist = glob.glob("static/musics/*.mp3")

    musicJ = [{"fileName": mi.split("/")[-1],
                "coverURL": url_for('coverImage', music=mi),
                "fileURL": url_for('sounds', music=mi),
                "length": sec2minString(File(mi).info.length),
                "Tags": None
                } for mi in musiclist]

    for i in range(len(musicJ)):
        tag = File(musiclist[i])
        if('TIT2' in tag.keys()):
            musicJ[i]['tags'] = {'TIT2': tag['TIT2'].text[0], 'TPE1':tag['TPE1'].text[0]}

    return render_template("home.html", musicJ=musicJ)
Ejemplo n.º 17
0
    def get_file_metadata(self):
        """ Return current file metadata. 
            Valid only for modes: audio files and collection

        :return: dictionary with metadata
        """
        meta = {}
        mode = self.config[CURRENT][MODE]

        if mode == AUDIO_FILES:
            folder = self.config[FILE_PLAYBACK][CURRENT_FOLDER]
            filename = self.config[FILE_PLAYBACK][CURRENT_FILE]
        elif mode == COLLECTION:
            folder = self.config[COLLECTION_PLAYBACK][COLLECTION_FOLDER]
            filename = self.config[COLLECTION_PLAYBACK][COLLECTION_FILE]
        else:
            return meta

        path = os.path.join(folder, filename)
        if not path:
            return meta

        meta["filename"] = filename
        try:
            filesize = os.stat(path).st_size
            meta["filesize"] = filesize
            m = File(path)
            for i in INFO:
                meta[i] = getattr(m.info, i, None)

            if filename.lower().endswith(EXT_MP4) or filename.lower().endswith(
                    EXT_M4A):
                metadata = MP4_METADATA
            else:
                metadata = METADATA

            for i, key in enumerate(metadata):
                if key not in m.keys() or len(m[key][0].replace(
                        " ", "").strip()) == 0:
                    v = None
                else:
                    v = m[key][0].strip()
                meta[METADATA[i]] = v
        except Exception as e:
            logging.debug(e)

        return meta
Ejemplo n.º 18
0
def home():
    musiclist = glob.glob('static/musics/*.mp3')
    musicJ = [{
        'fileName': mi.split("/")[-1],
        'coverUrl': url_for('coverImage', music=mi),
        'fileUrl': url_for('sounds', music=mi),
        'length': sec2minstring(File(mi).info.length),
        'Tags': None
    } for mi in musiclist]
    for i in range(len(musicJ)):
        tag = File(musiclist[i])
        if ('TIT2' in tag.keys()):
            musicJ[i]['Tags'] = {
                'TIT2': tag['TIT2'].text[0],
                'TPE1': tag['TPE1'].text[0]
            }

    return render_template("home.html", musicJ=musicJ)
  def process_metadata(self, metadata):

    Log('Reading OGG tags from: ' + self.filename)
    try: 
      tags = MFile(self.filename)
      Log('Found tags: ' + str(tags.keys()))
    except:
      Log('An error occured while attempting to parse the OGG file: ' + self.filename)
      return

    # Genres
    try:
      genres = tags.get('genre')
      if genres is not None and len(genres) > 0:
        metadata.genres.clear()
        for genre in genres:
          for sub_genre in parse_genres(genre):
            metadata.genres.add(sub_genre.strip())
    except Exception, e:
      Log('Exception reading genre: ' + str(e))
Ejemplo n.º 20
0
    def process_metadata(self, metadata):

        Log('Reading OGG tags from: ' + self.filename)
        try:
            tags = MFile(self.filename)
            Log('Found tags: ' + str(tags.keys()))
        except:
            Log('An error occured while attempting to parse the OGG file: ' +
                self.filename)
            return

        # Genres
        try:
            genres = tags.get('genre')
            if genres is not None and len(genres) > 0:
                metadata.genres.clear()
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        metadata.genres.add(sub_genre.strip())
        except Exception, e:
            Log('Exception reading genre: ' + str(e))
Ejemplo n.º 21
0
    def process_metadata(self, metadata):

        Log("Reading FLAC tags from: " + self.filename)
        try:
            tags = MFile(self.filename)
            Log("Found tags: " + str(tags.keys()))
        except:
            Log("An error occurred while attempting to parse the FLAC file: " + self.filename)
            return

        # Genres
        try:
            genres = tags.get("genre")
            if genres is not None and len(genres) > 0:
                metadata.genres.clear()
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        if sub_genre.strip():
                            metadata.genres.add(sub_genre.strip())
        except Exception, e:
            Log("Exception reading genre: " + str(e))
Ejemplo n.º 22
0
    def process_metadata(self, metadata):

        Log("Reading MP4 tags from: " + self.filename)
        try:
            tags = MFile(self.filename)
            Log("Found tags: " + str(tags.keys()))
        except:
            Log("An error occurred while attempting to parse the MP4 file: " + self.filename)
            return

        # Genres
        try:
            genres = tags.get("\xa9gen")
            if genres is not None and len(genres) > 0:
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        sub_genre_stripped = sub_genre.strip()
                        if sub_genre_stripped:
                            if sub_genre_stripped not in metadata.genres:
                                metadata.genres.add(sub_genre_stripped)
        except Exception, e:
            Log("Exception reading \xa9gen (genre): " + str(e))
Ejemplo n.º 23
0
    def process_metadata(self, metadata):

        Log('Reading MP4 tags from: ' + self.filename)
        try:
            tags = MFile(self.filename)
            Log('Found tags: ' + str(tags.keys()))
        except:
            Log('An error occurred while attempting to parse the MP4 file: ' +
                self.filename)
            return

        # Genres
        try:
            genres = tags.get('\xa9gen')
            if genres is not None and len(genres) > 0:
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        sub_genre_stripped = sub_genre.strip()
                        if sub_genre_stripped:
                            if sub_genre_stripped not in metadata.genres:
                                metadata.genres.add(sub_genre_stripped)
        except Exception, e:
            Log('Exception reading \xa9gen (genre): ' + str(e))
Ejemplo n.º 24
0
class OGGAudioHelper(AudioHelper):
    def __init__(self, filename):
        super(OGGAudioHelper, self).__init__(filename)
        try:
            Log('Reading OGG tags from: ' + self.filename)
            self.tags = MFile(self.filename)
            Log('Found OGG tags: ' + str(self.tags.keys()))
        except:
            Log('An error occured while attempting to parse the OGG file: ' +
                self.filename)

    @classmethod
    def is_helper_for(cls, tagType):
        return tagType in ['OggVorbis', 'OggOpus']

    def process_metadata(self, metadata, prefs):
        # Genres
        try:
            genres = self.tags.get('genre')
            if genres is not None and len(genres) > 0:
                metadata.genres.clear()
                for genre in genres:
                    for sub_genre in parse_genres(genre):
                        if sub_genre.strip():
                            metadata.genres.add(sub_genre.strip())
        except Exception, e:
            Log('Exception reading genre: ' + str(e))

        # Release Date
        try:
            release_date = self.tags.get('date')
            if release_date is not None and len(release_date) > 0:
                metadata.originally_available_at = Datetime.ParseDate(
                    release_date[0])
        except Exception, e:
            Log('Exception reading release date' + str(e))
Ejemplo n.º 25
0
    def hydrate(self, bundle):
        #Translate model field name to audio metadata name
        tag_name_translator: Dict[str, List[str]] = {
            'title': ['title'],
        }
        if 'audio' in bundle.data.keys() and bundle.request.method == 'POST':
            if settings.USE_ACOUSTID:
                tmp_file_path = bundle.data.get('audio').temporary_file_path()
                matches = acoustid.match(settings.ACOUSTID_API_KEY,
                                         tmp_file_path)
                try:
                    score, recording_id, title, artist_entry = next(matches)
                except StopIteration:
                    pass
                else:
                    musicbrainzngs.set_useragent('Open_Sound_Stream:Server',
                                                 settings.OSS_VERSION)
                    try:
                        rec = musicbrainzngs.get_recording_by_id(
                            recording_id,
                            includes=['artists', 'tags', 'releases'])
                    except musicbrainzngs.WebServiceError:
                        pass
                    else:
                        bundle_data_translate: Dict[str,
                                                    Union[List[str],
                                                          List[Artist],
                                                          List[Album]]] = {
                                                              'title': title,
                                                              'mbid':
                                                              recording_id,
                                                          }
                        for key, val in bundle_data_translate.items():
                            if key not in bundle.data:
                                bundle.data[key] = val
                        artists: List[str] = []
                        artist_obj_list: List[Artist] = []
                        if "artists" not in bundle.data:
                            artist_list: List[Dict] = rec['recording'][
                                'artist-credit']
                            for artist_entry in artist_list:
                                artist_by_id: Artist = Artist.get_by_mbid(
                                    bundle.request.user,
                                    artist_entry["artist"]["id"])
                                if artist_by_id is not None:
                                    artists.append("/api/v1/artist/{}/".format(
                                        artist_by_id.pk))
                                    artist_obj_list.append(artist_by_id)
                            bundle.data['artists'] = artists
                        else:
                            for artist_entry in bundle.data.getlist('artist'):
                                artist_entry_splitted = artist_entry.split("/")
                                if artist_entry_splitted[-1] == '':
                                    del artist_entry_splitted[-1]
                                try:
                                    artist_id = int(artist_entry_splitted[-1])
                                except ValueError:
                                    continue
                                try:
                                    artist_obj_list.append(
                                        Artist.objects.get(
                                            user=bundle.request.user,
                                            pk=artist_id))
                                except ObjectDoesNotExist:
                                    #dont process any further, let tastypie throw the exception
                                    return bundle
                        if "album" not in bundle.data and len(
                                rec['recording']['release-list']) >= 1:
                            release = rec['recording']['release-list'][0]
                            album, created = Album.objects.get_or_create(
                                user=bundle.request.user,
                                name=release['title'])
                            for artist_entry in artist_obj_list:
                                album.artist.add(artist_entry)
                            album.mbid = release["id"]
                            try:
                                img = musicbrainzngs.get_image_list(
                                    release["id"])
                            except musicbrainzngs.ResponseError:
                                pass
                            else:
                                if len(img["images"]) > 0:
                                    album.cover_url = img["images"][0]["image"]

                            album.save()
                            bundle.data['album'] = "/api/v1/album/{}/".format(
                                album.pk)
            metadata = GetTags(fileobj=bundle.data['audio'].file)
            for field_name, tag_names in tag_name_translator.items():
                if field_name not in bundle.data.keys():
                    for tag_name in tag_names:
                        if tag_name in metadata.keys():
                            bundle.data[field_name] = metadata.get(tag_name)
                            break
        return bundle
Ejemplo n.º 26
0
					except KeyError:
						artist = unicode("")
					try:
						album = data["album"][0].strip()
					except KeyError:
						album = unicode("")
					try:
						title = data["title"][0].strip()
					except KeyError:
						title = unicode("")
					duration = int(data.info.length)
					print (fp, artist, album, title, duration)
					cur.execute("insert into songs values(?,?,?,?,?)",(fp, artist, album, title, duration))
					con.commit()
				except KeyError:
					print fp,data.keys()
					raise

cur.execute("select artist,album, count(title) from songs group by artist,album having count(title)>2 and artist!=\"\"")
artists = {}
lower = {}
d = cur.fetchall()
#print d
for (artist, album,title) in d:
	if artist.lower() in lower:
		artist = lower[artist.lower()]
	if artist not in artists:
		artists[artist] = {}
		lower[artist.lower()] = artist
	artists[artist][album] = title
	
Ejemplo n.º 27
0
class podcast_reader(object):
    """ Simple podcast MP3 audio reader """

    audio_picture = None
    audio_date = None
    audio_id = None

    image_file = None
    image_fullpath = None
    image_data = None

    title = 'foo'
    type = 'bar'

    def __init__(self, file_path, output_path):
        self._path = file_path
        self._output = output_path
        self.audio_data = File(file_path)
        self.duration = int(self.audio_data.info.length / 60)
        self._load_internal_data()

    def get_tags(self, tag):
        return self._get_list(self.audio_data.tags.getall(TAGS[tag])[0])

    def text(self):
        return str(self._tag('TEXTO')[0]).decode('utf-8')

    def _image(self):
        # looking for 'APIC:xxxx.ext'
        for tag in self.audio_data.keys():
            if 'APIC:' in tag:
                self.audio_picture = self.audio_data[tag]

        image_ext = ".%s" % (self.audio_picture.mime).split("/")[1]
        self.image_file = path.join(
            PATH_AUDIO, PATH_IMGS,
            path.basename(self._path).replace('.mp3', image_ext))
        self.image_fullpath = path.join(self._output, PATH_AUDIO, PATH_IMGS)
        self.image_data = self.audio_picture.data

    def _title(self):
        self.title = str(self._tag('TITULO')[0]).decode('utf-8')
        self.title_safe = self._safe_me(self.title)

    def _date(self):
        date = str(self._tag('FECHA')[0])
        self.audio_date = datetime.datetime.strptime(date, "%Y-%m-%d")

    # generate global id - to identify the file (unique_id)
    def _id(self):
        # if the user generate an ID, just use it
        if self._tag('ID'):
            self.audio_id = str(self._tag('ID')[0])

        # we use date and safe version of title string
        else:
            self.audio_id = self.audio_date.strftime("%d%m%Y_")
            self.audio_id += self.title_safe

    def _type(self):
        self.type = str(self._tag('TIPO')[0]).decode('utf-8')
        self.type_safe = self._safe_me(self.type)

    def _safe_me(self, name):
        regex = re.compile("[^\w\-]")
        return regex.sub("", name.replace(" ", "_").lower())

    def _tag(self, audio_tag):
        return self.audio_data.tags.getall(TAGS[audio_tag])

    def _get_list(self, audio_tag):
        return [x.strip() for x in str(audio_tag).decode('utf-8').split(",")]

    def _load_internal_data(self):
        self._image()
        self._title()
        self._date()
        self._id()
        self._type()
Ejemplo n.º 28
0
class AudioFile(MutableMapping):
    """A simple class just for tag editing.

    No internal mutagen tags are exposed, or filenames or anything. So
    calling clear() won't destroy the filename field or things like
    that. Use it like a dict, then .write() it to commit the changes.
    When saving, tags that cannot be saved by the file format will be
    skipped with a debug message, since this is a common occurrance
    with MP3/M4A.

    Optional argument blacklist is a list of regexps matching
    non-transferrable tags. They will effectively be hidden, nether
    settable nor gettable.

    Or grab the actual underlying mutagen format object from the
    .data field and get your hands dirty.

    """
    def __init__(self, filename: str, blacklist: List[Pattern[str]]=[],
                 easy: bool=True) -> None:
        self.filename = filename
        self.data = MusicFile(self.filename, easy=easy)
        if self.data is None:
            raise ValueError("Unable to identify %s as a music file" % (repr(filename)))
        # Also exclude mutagen's internal tags
        self.blacklist = [ re.compile("^~") ] + blacklist
    def __getitem__(self, item: str) -> Any:
        if self.blacklisted(item):
            logger.debug("Attempted to get blacklisted key: %s." % repr(item))
        else:
            return self.data.__getitem__(item)
    def __setitem__(self, item: str, value: Any) -> None:
        if self.blacklisted(item):
            logger.debug("Attempted to set blacklisted key: %s." % repr(item))
        else:
            try:
                return self.data.__setitem__(item, value)
            except KeyError:
                logger.debug("Skipping unsupported tag %s for file type %s",
                             item, type(self.data))
    def __delitem__(self, item: str):
        if self.blacklisted(item):
            logger.debug("Attempted to del blacklisted key: %s." % repr(item))
        else:
            return self.data.__delitem__(item)
    def __len__(self) -> int:
        return len(list(self.keys()))
    def __iter__(self) -> Iterable[Any]:
        return iter(self.keys())

    def blacklisted(self, item: str) -> bool:
        """Return True if tag is blacklisted.

        Blacklist automatically includes internal mutagen tags (those
        beginning with a tilde)."""
        for regex in self.blacklist:
            if re.search(regex, item):
                return True
        else:
            return False
    def keys(self) -> Iterable[str]:
        return [ key for key in self.data.keys() if not self.blacklisted(key) ]
    def write(self) -> None:
        return self.data.save()
Ejemplo n.º 29
0
def fix_music(rename_format, norename=False, recursive=False):
    '''
    Searches for '.mp3' files in directory (optionally recursive)
    and checks whether they already contain album art and album name tags or not.
    '''
    files = []

    if recursive:
        for dirpath, _, filenames in walk("."):
            for filename in [f for f in filenames if f.endswith(".mp3")]:
                if Py3:
                    files += [path.join(dirpath, filename)]
                else:
                    files += [path.join(dirpath, filename).decode('utf-8')]
    else:
        if Py3:
            files = [f for f in listdir('.') if f.endswith('.mp3')]

        else:
            files = [f.decode('utf-8') for f in listdir('.') if f.endswith('.mp3')]

    for file_path in files:
        tags = File(file_path)
        file_name = basename(file_path)[:-4] #Gets file name and removes .mp3 for better search results

        if 'APIC:Cover' in tags.keys() and 'TALB' in tags.keys():  # Checks whether there is album art and album name
            log('%s already has tags ' % tags["TIT2"])

        elif not('APIC:Cover' in tags.keys()) and 'TALB' in tags.keys():
            album = tags["TALB"].text[0]
            log(LOG_LINE_SEPERATOR)

            log(file_path)
            log('> Adding metadata')

            try:
                albumart = albumsearch.img_search_google(album)
            except Exception:
                albumart = albumsearch.img_search_bing(album)

            add_albumart(albumart, file_path)

        else:
            log(LOG_LINE_SEPERATOR)

            log(file_path)
            log('> Adding metadata')

            try:
                artist, album, song_name, lyrics, match_bool, score = get_details_spotify(
                    file_name)  # Try finding details through spotify

            except Exception:
                artist, album, song_name, lyrics, match_bool, score = get_details_letssingit(
                    file_name)  # Use bad scraping method as last resort

            try:
                log_indented('* Trying to extract album art from Google.com')
                albumart = albumsearch.img_search_google(artist+' '+album)
            except Exception:
                log_indented('* Trying to extract album art from Bing.com')
                albumart = albumsearch.img_search_bing(arist+' '+album)

            if match_bool:
                add_albumart(albumart, file_path)
                add_details(file_path, song_name, artist, album, lyrics)

                try:
                    if not norename:
                        song_title = rename_format.format(title=song_name + '-', artist=artist + '-', album=album+'-')
                        song_title = song_title[:-1] if song_title.endswith('-') else song_title
                        rename(file_path, path.dirname(file_path) + '/{song_title}.mp3'.format(song_title=song_title))
                except Exception:
                    pass
            else:
                log_error("* Couldn't find appropriate details of your song", indented=True)
                with open(LOG_FILENAME, "a") as problems:
                    problems.write(str(file_path) + '\n')  # log song that couldn't be repaired

            log("Match score: %s/10.0" % round(score * 10, 1))
            log(LOG_LINE_SEPERATOR)
Ejemplo n.º 30
0
def test_add_album_art():

    musictools.add_album_art(location, albumart)
    tags = File(location)

    assert 'APIC:Cover' in tags.keys() != None
Ejemplo n.º 31
0

# 3.: copy the tags and rename files

oldfiles = sorted(os.listdir(os.getcwd()))
for f in oldfiles:
	if not os.path.isfile(f):
		oldfiles.remove(f)
newfiles = sorted(glob.glob("abcde*/*.flac"))
if len(newfiles) != numfiles:
	print("Anzahl der Tracks stimmt nicht überein!")
	print(oldfiles)
	print("---")
	print(newfiles)
	sys.exit(1)
for i in range(len(oldfiles)):
	new_audio = File(newfiles[i])
	old_audio = File(oldfiles[i])
	for key in old_audio.keys():
		new_audio[key] = old_audio[key]
	new_audio.save()
	newname = oldfiles[i].rsplit(".",1)[0] + ".flac"
	os.rename(newfiles[i],newname)
	print("successfully tagged and renamed " + newname)

subprocess.call(["rm", "-rf"] + glob.glob("abcde*"))
ans = raw_input("Delete ogg files? [Y/n] ").strip()
if ans in "yYjJ" or ans == "":
	for f in oldfiles:
		os.remove(f)
Ejemplo n.º 32
0
def updatemusic():   
   db = model()    
   musiclist = glob.glob(MUSICFOLDER + "*.mp3")   
   musicnames = [mi.split("/")[-1] for mi in musiclist]   

   indb = [msi.arquivo
   for msi in db().iterselect(db.musica.arquivo)
   if msi.arquivo in musicnames]   

   notindb = list(set(musicnames) - set(indb))

    
  for msi in notindb:
    tag = File(MUSICFOLDER + msi)       
    tempo = sec2minString(File(MUSICFOLDER + msi).info.length)
    if('TIT2'in tag.keys()):
      db.musica.insert(nome=tag['TIT2'].text[0], cantor=tag['TPE1'].text[0], arquivo=msi, tempo=tempo)
    else:
      db.musica.insert(arquivo=msi, tempo=tempo)

    notindir = [msi.arquivo 
    for msi in db().iterselect(db.musica.arquivo) 
    if msi.arquivo notin musicnames ]

    for msi in notindir:
      db(db.musica.arquivo == msi).delete()
      db.commit()

def get_musics():
    db = model()
    musiclist = db().select(db.musica.arquivo, db.musica.tempo, db.musica.cantor, db.musica.cantor, db.musica.nome, orderby = db.musica.arquivo | db.musica.nome)