Example #1
0
 def __init__(self, container):
     self.container = container
     # fix #737 EasyID3 doesn't recognize subtitle and comment tags
     EasyID3.RegisterTextKey("comments", "COMM")
     EasyID3.RegisterTextKey("subtitle", "TIT3")
     EasyMP4Tags.RegisterTextKey("comments", "desc")
     EasyMP4Tags.RegisterFreeformKey("subtitle", "SUBTITLE")
Example #2
0
def assign_metadata_to_track(self, track_file_path,
                             track_full_path_minus_file_type):

    info = self.get_track_info(track_file_path)
    # This assigns the m4a track field values to the new mp3
    mp3 = EasyID3(f"{track_full_path_minus_file_type}.mp3")

    # Verify that there are values to assign to the new mp3 and assign them
    if info.album is not None:
        mp3['album'] = album
    if info.title is not None:
        mp3['title'] = title
    if info.artist is not None:
        mp3['artist'] = artist
    if info.composer is not None:
        mp3['composer'] = composer
    if genre is not None:
        mp3['genre'] = genre
    if year is not None:
        mp3['date'] = year
    if track_number is not None and track_total is not None:
        EasyID3.RegisterTextKey('track total', 'TRCK')
        mp3['track total'] = f"{track_number}/{track_total}"
    if disc_number is not None and disc_total is not None:
        EasyID3.RegisterTextKey('disc total', 'TPOS')
        mp3['disc total'] = f"{disc_number}/{disc_total}"

    mp3.save(v2_version=3)

    return album, title, artist, composer, genre, year, track_number, disc_number
Example #3
0
    def __init__(self, path):
        self.file = MP3(path, ID3=EasyID3)
        self.id3file = ID3(path)

        self.bitrateModeTable = {
            BitrateMode.UNKNOWN: "CBR",
            BitrateMode.CBR: "CBR",
            BitrateMode.VBR: "VBR",
            BitrateMode.ABR: "ABR"
        }

        EasyID3.RegisterTextKey("initialkey", "TKEY")
        EasyID3.RegisterTextKey("comment", "COMM")
        EasyID3.RegisterTextKey("modified", "TPE4")
        EasyID3.RegisterTXXXKey('tiktag', 'TikTag')
Example #4
0
    def _write_mp3_tags(self, path, track, tags=None):
        if "DATA" in track:
            track = track["DATA"]

        if not tags:
            tags = self.get_track_tags(track)

        audio = MP3(path, ID3=EasyID3)
        audio.delete()
        EasyID3.RegisterTextKey("label", "TPUB")

        cover = tags["_albumart"]
        del tags["_albumart"]

        for key, val in tags.items():
            if val:
                audio[key] = str(val)
        audio.save()

        if cover:
            cover_handle = ID3(path)
            cover_handle["APIC"] = APIC(type=3,
                                        mime=cover["mime_type"],
                                        data=cover["image"])
            cover_handle.save(path)

        return True
 def writeMP3Tags(filename, tags, coverArtId):
     handle = MP3(filename, ID3=EasyID3)
     handle.delete()
     # label is not supported by easyID3, so we add it
     EasyID3.RegisterTextKey("label", "TPUB")
     # tracknumber and total tracks is one tag for ID3
     tags['tracknumber'] = f'{str(tags["tracknumber"])}/{str(tags["totaltracks"])}'
     del tags['totaltracks']
     for key, val in tags.items():
         if key == 'artist':
             # Concatenate artists
             artists = val[0] # Main artist
             for artist in val[1:]:
                 artists += ";" + artist
             handle[key] = artists
         elif key == 'lyrics':
             if 'uslt' in val: # unsynced lyrics
                 handle.save()
                 id3Handle = ID3(filename)
                 id3Handle['USLT'] = USLT(encoding=3, text=val['uslt'])
                 id3Handle.save(filename)
                 handle.load(filename) # Reload tags
         else:
             handle[key] = str(val)
     handle.save()
     return True
Example #6
0
    def add_tag_mp3(self, fichero, name_cancion, parDir, directorio):

        patronMusicaMP3 = re.compile(
            '.\.mp3')  # Utilizaremos el patros para seleccionar archivos mp3
        if patronMusicaMP3.search(
                str(fichero)):  # Comprobamos si supuestamente es un fich mp3
            name_cancion = name_cancion.rstrip(
                ".mp3"
            )  # ahora al nombre le quitamos la extension que queda fea.
            try:
                print(
                    "file", os.path.basename(str(fichero)), "directory_1",
                    os.path.basename(str(self.ruta)), "dir_2:",
                    os.path.basename(
                        os.path.dirname(os.path.normpath(str(self.ruta)))))

                audioTag = EasyID3(str(fichero))
                audioTag['title'] = name_cancion
                audioTag['artist'] = parDir
                audioTag['album'] = directorio
                audioTag['composer'] = ""
                EasyID3.RegisterTextKey("album_artist", "TPE2")
                audioTag['album_artist'] = ""
                print(audioTag['title'], "nuevo")
                audioTag.save(v2_version=3)
                audioTag.save()
            except ID3NoHeaderError:
                audioTag = mutagen.File(str(fichero), easy=True)
                audioTag.add_tags()
                audioTag['title'] = name_cancion
                audioTag['album'] = directorio
                audioTag['artist'] = parDir
                print("No existe un tag previo")
                audioTag.save(v2_version=3)
                audioTag.save()
Example #7
0
 def __init__(self, location):
     """Initializes the class and generates ID3 tags for the mp3
     :param location: a string, the location of the mp3 that you want ID3 
         tags on
     """
     EasyID3.RegisterTextKey("comment", "COMM")
     self.location = location
     self.mp3 = EasyID3(self.location)
Example #8
0
 def __init__(self, info):
     from mutagen.mp3 import MP3 as mp3
     from mutagen.easyid3 import EasyID3
     from mutagen.id3 import ID3
     EasyID3.RegisterTextKey('description', "COMM")
     p = path + name
     audio = mp3(p, ID3=EasyID3)
     for key, value in info.items():
         try:
             audio[key] = value
         except:
             pass
     audio.save()
     self.audio = ID3(p)
     self.id = info['description']
Example #9
0
def writeMP3Tags(filename, tags, coverArtId):
    handle = MP3(filename, ID3=EasyID3)
    handle.delete()
    # label is not supported by easyID3, so we add it
    EasyID3.RegisterTextKey("label", "TPUB")
    # tracknumber and total tracks is one tag for ID3
    tags[
        'tracknumber'] = f'{str(tags["tracknumber"])}/{str(tags["totaltracks"])}'
    del tags['totaltracks']
    separator = config.get('DEFAULT', 'artist separator')
    for key, val in tags.items():
        if key == 'artist':
            # Concatenate artists
            artists = val[0]  # Main artist
            for artist in val[1:]:
                artists += separator + artist
            handle[key] = artists
        elif key == 'lyrics':
            if 'uslt' in val:  # unsynced lyrics
                handle.save()
                id3Handle = ID3(filename)
                id3Handle['USLT'] = USLT(encoding=3, text=val['uslt'])
                id3Handle.save(filename)
                handle.load(filename)  # Reload tags
        else:
            handle[key] = str(val)
    handle.save()
    # Cover art
    if coverArtId:
        ext = config.get('DEFAULT', 'album art embed format')
        image = getCoverArt(
            coverArtId,
            config.getint(
                'DEFAULT',
                'embed album art size'),  # TODO: write to temp folder?
            ext)
        id3Handle = ID3(filename)
        if ext == 'jpg':
            mime = 'image/jpeg'
        else:
            mime = 'image/png'
        id3Handle['APIC'] = APIC(
            encoding=3,  # 3 is for utf-8
            mime=mime,
            type=3,  # 3 is for the cover image
            data=image)
        id3Handle.save(filename)
    return True
Example #10
0
 def set_id3_tags(file, title, artist, album, comment):
     try:
         tag = EasyID3(file)
     except:
         tag = mutagen.File(file, easy=True)
         tag.add_tags()
     if title:
         tag['title'] = title
     if artist:
         tag['artist'] = artist
     if album:
         tag['album'] = album
     # if year:
     #     tag['date'] = year
     if comment:
         EasyID3.RegisterTextKey("comment", "COMM")
         tag['comment'] = comment
     tag.save(v2_version=3)
Example #11
0
def writeMP3Tags(filename, tags, imageUrl):
    handle = MP3(filename, ID3=EasyID3)
    handle.delete()
    # label is not supported by easyID3, so we add it
    EasyID3.RegisterTextKey("label", "TPUB")
    # tracknumber and total tracks is one tag for ID3
    tags['tracknumber'] = f'{str(tags["tracknumber"])}/{str(tags["totaltracks"])}'
    del tags['totaltracks']

    for key, val in tags.items():
        handle[key] = str(val)
    handle.save()
    if imageUrl:
        image = getCoverArt(imageUrl, filename, 1500) # TODO: write to temp folder?
        handle= MP3(filename)
        handle["APIC"] = mutagen.id3.APIC(
                                        encoding=3, # 3 is for utf-8
                                        mime='image/png',
                                        type=3, # 3 is for the cover image
                                        data=image)
        handle.save()
    return True
Example #12
0
    def _tag_mp3(self, file):
        """
        Tag Mp3 file only called from `track.tag()`
        """
        tagger = Tagger(self, '.mp3')
        tag = EasyMP3(file)
        EasyID3.RegisterTextKey('comment', 'COMM')
        tag.delete()

        for tag_obj in tagger.tag_map:
            tag[tag_obj.key] = str(tag_obj.value)
        tag.save()

        # image
        if cc.tag_cover and self.album.picture_url is not None:
            cover_data = self.get_cover_data()
            if cover_data:
                audio = MP3(file, ID3=ID3)
                audio.tags.add(
                    APIC(encoding=3,
                         mime='image/jpeg',
                         type=3,
                         desc=u'Cover',
                         data=cover_data))
                audio.save()
            else:
                log.warning(f'No Cover for {self}')

        # lyrics
        if cc.tag_lyrics:
            if self.lyrics != None:
                tag = ID3(file)
                tag[u"USLT::'eng'"] = (USLT(encoding=3,
                                            lang=u'eng',
                                            desc=u'desc',
                                            text=self.lyrics.lyrics_text))
                tag.save()
Example #13
0
 def add_metadata(self, path, link, genre):
     if os.path.isfile(path):
         fn = path.split('/')[-1]
         vi = fn.split('__')[0]
         vidinfo = re.sub(r"[\(\[].*?[\)\]]", "", vi)
         if '-' in vidinfo:
             artist = vidinfo.split('-')[0]
             fulltitle = vidinfo.split('-')[1]
             title = fulltitle.split('__')[0]
         else:
             title = vidinfo
             artist = ''
         if '?' in link:
             link = link.split('?')[0]
         try:
             song = EasyID3(path)
         except ID3NoHeaderError:
             song = File(path, easy=True)
         EasyID3.RegisterTextKey('comment', 'COMM')
         song['title'] = title
         song['artist'] = artist
         song['genre'] = genre
         song['comment'] = link
         song.save()
Example #14
0
def writeTags(filename, ext, trackInfo, albInfo):
    ''' Function to write tags to the file, be it FLAC or MP3.'''
    # retrieve tags
    try:
        genre = albInfo['genres']['data'][0]['name']
    except:
        genre = ''
    tags = {
        'title': trackInfo['title'],
        'discnumber': trackInfo['disk_number'],
        'tracknumber': trackInfo['track_position'],
        'album': trackInfo['album']['title'],
        'date': trackInfo['album']['release_date'],
        'artist': trackInfo['artist']['name'],
        'bpm': trackInfo['bpm'],
        'albumartist': albInfo['artist']['name'],
        'totaltracks': albInfo['nb_tracks'],
        'label': albInfo['label'],
        'genre': genre
    }
    # Download and load the image
    # cover_xl returns 1000px jpg link,
    # but 1500px png is available, so we modify url
    url = trackInfo['album']['cover_xl'].rsplit('/', 1)[0]
    image = getCoverArt(url, filename, 1500)
    if ext == '.flac':
        try:
            handle = mutagen.File(filename + ext)
        except mutagen.flac.FLACNoHeaderError as error:
            print(error)
            os.remove(filename + ext)
            return False
        handle.delete()  # delete pre-existing tags and pics
        handle.clear_pictures()
        if getSetting('embed album art') == 'True':
            pic = mutagen.flac.Picture()
            pic.encoding = 3
            pic.mime = 'image/png'
            pic.type = 3
            pic.data = image
            handle.add_picture(pic)

        for key, val in tags.items():
            handle[key] = str(val)
        handle.save()
        return True

    elif ext == '.mp3':
        handle = MP3(filename + ext, ID3=EasyID3)
        handle.delete()
        # label is not supported by easyID3, so we add it
        EasyID3.RegisterTextKey("label", "TPUB")
        # tracknumber and total tracks is one tag for ID3
        tags['tracknumber'] = (str(tags['tracknumber']) + '/' +
                               str(tags['totaltracks']))
        del tags['totaltracks']

        for key, val in tags.items():
            handle[key] = str(val)
        handle.save()
        if getSetting('embed album art') == 'True':
            handle = MP3(filename + ext)
            handle["APIC"] = mutagen.id3.APIC(
                encoding=3,  # 3 is for utf-8
                mime='image/png',
                type=3,  # 3 is for the cover image
                data=image)
            handle.save()
        return True
    else:
        print("Could not write tags. File extension not supported.")
        return None
Example #15
0
#coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import os
from os import path

from mutagen.easyid3 import EasyID3
EasyID3.RegisterTextKey('ALBUMARTIST', 'TPE2')
EasyID3.RegisterTextKey('ALBUMARTISTSORT', 'TSO2')

from mutagen.mp3 import EasyMP3 as MP3
from mutagen.easymp4 import EasyMP4 as MP4
from mutagen.flac import FLAC

from pypinyin import lazy_pinyin


def beginWithCJK(str):
    if u'\u4e00' <= str[0] <= u'\u9fff':
        return True
    else:
        return False


def CJKFirstLetters(str):
    pinyins = lazy_pinyin(str)
    firstLetters = ''
    for pinyin in pinyins:
        firstLetters += pinyin[0]
Example #16
0
 def __init__(self, container):
     self.container = container
     # fix #737 EasyID3 doesn't recognize subtitle and comment tags
     EasyID3.RegisterTextKey("comments", "COMM")
     EasyID3.RegisterTextKey("subtitle", "TIT3")
Example #17
0
                transcode_info['discnumber'] = [
                    u'%s/%s' % (transcode_info['discnumber'][0], totaldiscs)
                ]

    transcode_info.save()


# EasyID3 extensions for PTHbetter.

for key, frameid in {
        'albumartist': 'TPE2',
        'album artist': 'TPE2',
        'grouping': 'TIT1',
        'content group': 'TIT1',
}.iteritems():
    EasyID3.RegisterTextKey(key, frameid)


def comment_get(id3, _):
    return [comment.text for comment in id3['COMM'].text]


def comment_set(id3, _, value):
    id3.add(mutagen.id3.COMM(encoding=3, lang='eng', desc='', text=value))


def originaldate_get(id3, _):
    return [stamp.text for stamp in id3['TDOR'].text]


def originaldate_set(id3, _, value):
Example #18
0
	try:
		language = id3['language']
	except KeyError:
		language = 'eng'
	id3.add(mutagen.id3.USLT(encoding=3, lang=language, desc='desc', text=value[0]))

def lyrics_delete(id3, key):
	id3.delall('USLT')

def lyrics_list():
	return

EasyID3.RegisterKey('picture', getter=picture_get, setter=picture_set, deleter=picture_delete, lister = picture_list)
#EasyID3.RegisterKey('comments', getter=comments_get, setter=comments_set, deleter=comments_delete, lister = comments_list)
EasyID3.RegisterKey('lyrics', getter=lyrics_get, setter=lyrics_set, deleter=lyrics_delete, lister = lyrics_list)
EasyID3.RegisterTextKey('language', 'TLAN')

class IrreplaceableKeyError(Exception):
		def __init__(self, msg):
			self.msg = msg
		def __str__(self):
			return repr(self.msg)

class Song:
	#wiping TXXX wipes replaygain calc.
	def __init__(self, location,
					tagsToReplace=['album', 'artist', 'title', 'tracknumber', 'picture'],
					# future tags: comments/COMM, url/WXXX
					tagsToWipe=[]):
		try:
			self.tags = EasyID3(location)
Example #19
0
__author__ = 'Charlie'

import mutagen
from collections import defaultdict

# Monkey patch mutagen easyid3 to accept 'albumartist' as an mp3 tag (TPE2)
# Note this results in albumartist and performer being the same mp3 key
# so we map "performer" to a nonexistent mp3 tag entity
# Most software uses PTE2 as the albumartist key.
# M4a files work out of the box.
from mutagen.easyid3 import EasyID3

EasyID3.RegisterTextKey("albumartist", "TPE2")
EasyID3.RegisterTextKey("performer", "XXX")


class LibraryEntry(object):
    def __init__(self, filename):
        self.filename = filename
        self.etags = mutagen.File(filename, easy=True)
        self.mimetype = self.etags.mime[0]

    @property
    def tags(self):
        """returns a defaultdict of the etags. useful for checking for keys that don't exist"""
        tags = defaultdict(lambda: [])
        # Populate the self tags
        for k, v in self.etags.items():
            tags[k] = v
        return tags
Example #20
0
import argparse
import requests
import unicodedata
from mutagen.easyid3 import EasyID3
from mutagen.easymp4 import EasyMP4
from mutagen.id3 import ID3
import mutagen.id3._util


extra_id3_tags = [
    ('comments', 'COMM')
]


for k, v in extra_id3_tags:
    EasyID3.RegisterTextKey(k, v)


logger = logging.getLogger()


def load_mp3(filename):
    try:
        return EasyID3(filename)
    except mutagen.id3._util.ID3NoHeaderError:
        # Fix mp3 file no tag loading error, m4a has no this problem
        id3 = ID3()
        id3.save(filename)
        return EasyID3(filename)

Example #21
0
from gmusicapi import Mobileclient
import gMusicLogin

from tqdm import tqdm
import sys, os, time, requests

from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
import mutagen.id3

EasyID3.RegisterTextKey("albumartist", "TPE2")
EasyID3.RegisterTextKey("media", "TMED")

r_albumID = 'Bmzku73mo3yicub2vnes43wv52y'

api = Mobileclient()
try:
    api.login(gMusicLogin.getUser(), gMusicLogin.getPass(),
              Mobileclient.FROM_MAC_ADDRESS)
except:
    sys.exit("Login Failed")

while api.is_authenticated() == False:
    time.sleep(.1)


def removeNonASCII(text):
    return ''.join(i for i in text if ord(i) < 128)


def runMainBody():
Example #22
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
from .Utilities import *
from .Parameters import *
import dateutil.parser
from mutagen.easyid3 import EasyID3
from mutagen.flac import FLAC
import mutagen
import os
from os import path

EasyID3.RegisterTextKey("albumartist", "TPE2")


class Episode:
    def __init__(self, podcast, xmlEp=None, enclInd=0):
        self.podcast = podcast
        self.filePath = ''
        if xmlEp:
            # Get the podcast attributes
            self.title = xmlEp.title
            if 'href' in xmlEp.enclosures[enclInd]:
                self.url = xmlEp.enclosures[enclInd]['href']
            elif 'url' in xmlEp.enclosures[enclInd]:
                self.url = xmlEp.enclosures[enclInd]['url']
            else:
                self.url = ''
Example #23
0
from __future__ import print_function
from __future__ import unicode_literals
from multiprocessing.context import Process
import stat
from subprocess import Popen, PIPE
import os
from mutagen.easyid3 import EasyID3
import re  # Regular expression library
import time
from modules.common.utility import Utility
FFMPEG_CMD = ['ffmpeg']
EasyID3.RegisterTextKey('comment', 'COMM')


class Worker(Process, Utility):
    def __init__(self, main, id):
        Process.__init__(self)
        self.convertQueue = main.ConvertQueue
        self.name = "Converter " + str(id)
        self.isRunning = True
        self.dataTransport = main.dataTransport
        self.main = main
        self.params = main.params
        self.filter = main.params['filter']

    def set_id3(self, file, playlistData):

        fileData = self.GetDataFromFilename(str(file))
        tagFile = EasyID3(file)

        videoData = self.getdata('video', playlistData, fileData)
Example #24
0
 def __init__(self, location):
     self.spotify = spotipy.Spotify()
     self.location = location
     self.mp3 = EasyID3(self.location)
     EasyID3.RegisterTextKey("comment", "COMM")
Example #25
0
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any, AnyStr, Dict, Iterator, List, Optional, cast
from urllib.error import HTTPError

from moviepy.editor import AudioFileClip
from mutagen.easyid3 import EasyID3
from pytube import YouTube
from pytube.streams import Stream
from youtubesearchpython import VideosSearch

from dotify._model import Model, logger

logger = logging.getLogger("{0}.{1}".format(logger.name, __name__))

EasyID3.RegisterTextKey("albumcover", "APIC")

if TYPE_CHECKING is True:
    from dotify.models._artist import Artist


class TrackBase(Model):
    """`TrackBase` defines the interface of the `Track` class, which is subclassing it."""

    class Json(object):
        abstract = True

    def __str__(self) -> str:
        return "{0} - {1}".format(self.artist, self.name)

    @property