Exemple #1
0
def parseId3Tags():
    app.logger.info('Parsing ID3 tags...')
    songs = Song.query.filter(Song.id3_parsed.is_(False)).limit(50).all()
    app.logger.info('{} songs found to parse...'.format(len(songs)))

    # app.logger.info(EasyID3.valid_keys.keys())
    # app.logger.info(EasyMP4Tags.List)
    for song in songs:

        # get tag info
        info = {}
        if song.path_name.lower().endswith('mp3'):
            meta = MP3(song.abs_path)
            # app.logger.debug(meta.tags)
            try:
                info['song_title'] = meta.tags['TIT2'].text[0]
            except KeyError:
                info['song_title'] = song.path_name
            try:
                trck = meta.tags['TRCK'].text[0]
                if '/' in trck:
                    info['track_number'], info['total_tracks'] = trck.split(
                        '/')
                else:
                    info['track_number'] = trck
                    info['total_tracks'] = None
            except KeyError:
                info['track_number'] = 1
                info['total_tracks'] = 1
            try:
                info['track_number'] = int(info['track_number'])
            except (ValueError, TypeError):
                info['track_number'] = None
            try:
                info['total_tracks'] = int(info['total_tracks'])
            except (ValueError, TypeError):
                info['total_tracks'] = None
            try:
                info['artist_name'] = meta.tags['TPE1'].text[0]
            except KeyError:
                info['artist_name'] = 'unknown artist'
            try:
                info['album_name'] = meta.tags['TALB'].text[0]
            except KeyError:
                info['album_name'] = 'unknown album'
            info['disc_number'] = int(meta.tags['TPOS'].text[0].split('/')
                                      [0]) if 'TPOS' in meta else 1
            info['total_discs'] = int(
                meta.tags['TPOS'].text[0].split('/')[1]
            ) if 'TPOS' in meta and '/' in meta.tags['TPOS'].text[0] else 1
            info['year'] = int(
                meta.tags['TDRC'].text[0].year) if 'TDRC' in meta else None
        elif song.path_name.lower().endswith('m4a'):
            meta = MP4(song.abs_path)
            info['song_title'] = meta[u'\xa9nam'][0]
            info['track_number'] = int(meta[u'trkn'][0][0])
            info['total_tracks'] = int(meta[u'trkn'][0][1])
            info['artist_name'] = meta[u'\xa9ART'][0]
            info['album_name'] = meta[u'\xa9alb'][0]
            info['disc_number'] = int(
                meta[u'disk'][0][0]) if u'disk' in meta else 1
            info['total_discs'] = int(
                meta[u'disk'][0][1]) if u'disk' in meta else 1
            info['year'] = int(
                meta[u'\xa9day'][0]) if u'\xa9day' in meta else None
        else:
            raise Exception('Unknown extension {}'.format(song.path_name))
        app.logger.debug(info)

        # artist info
        artist = Artist.query.filter_by(
            name_id=info['artist_name'].lower().strip()).first()
        if not artist:
            artist = Artist(info['artist_name'])
            db.session.add(artist)
            db.session.commit()
            app.logger.info('{} <= {}'.format(artist, info['artist_name']))
        song.artist_id = artist.id

        # album info
        album = Album.query.filter_by(
            name_id=info['album_name'].lower().strip(), artist=artist).first()
        if not album:
            album = Album(info['album_name'], artist)
            album.disc_number = info['disc_number']
            album.total_discs = info['total_discs']
            album.total_tracks = info['total_tracks']
            album.year = info['year']
            db.session.add(album)
            db.session.commit()
            app.logger.info('{} <= {}'.format(album, info['album_name']))
        song.album_id = album.id

        # song info
        song.name = info['song_title']
        song.track_number = info['track_number']
        song.id3_parsed = True

    db.session.commit()

    app.logger.info('Parsed {} ID3 tags...'.format(len(songs)))
    return len(songs)
Exemple #2
0
 def test_shrink(self):
     self.audio.clear()
     self.audio.save()
     audio = MP4(self.audio.filename)
     self.failIf(audio.tags)
Exemple #3
0
 def setUp(self):
     self.audio = MP4(self.original)
Exemple #4
0
 def test_module_delete(self):
     delete(self.filename)
     audio = MP4(self.audio.filename)
     self.failIf(audio.tags)
     self.faad()
Exemple #5
0
 def test_set_init_padding_large(self):
     if self.audio.tags is None:
         self.audio.add_tags()
     self.audio.save(padding=lambda x: 5000)
     self.assertEqual(MP4(self.audio.filename)._padding, 5000)
Exemple #6
0
 def setUp(self):
     self.filename = get_temp_copy(self.original)
     self.audio = MP4(self.filename)
Exemple #7
0
 def __init__(self, filename):
     _AbstractWrapper.__init__(self)
     self.audio = MP4(filename)
Exemple #8
0
# add cover
subprocess.call(["/usr/local/bin/MP4Box", "-itags", "output.mp4", "cover=cover1.jpg", "output.mp4"])


audio.save()

# convert chapters to quicktime format
subprocess.call(["mp4chaps", "--convert", "--chapter-qt", "output.mp4"])

# clean up
#os.remove("chapters")
#os.remove("output_MP3WRAP.mp3")

# create tags, rename file
audio = MP4("output.mp4")
audio["\xa9nam"] = [album_title]
audio["\xa9ART"] = [artist]
audio["\xa9gen"] = ["Audiobook"]
audio["covr"] = ["../cover.jpg"]
audio.save()

os.rename("output.mp4", "../%s - %s.m4b" % (album_title, artist))
os.chdir("../")
uid = pwd.getpwnam("keith").pw_uid
gid = grp.getgrnam("users").gr_gid
path = 'output'
os.chown(path, uid, gid)# output dir
os.chown("%s - %s.m4b" % (album_title, artist), uid, gid)
os.chmod("%s - %s.m4b" % (album_title, artist), 0o755)
Exemple #9
0
 def setUp(self):
     fd, self.filename = mkstemp(suffix='.m4a')
     os.close(fd)
     shutil.copy(self.original, self.filename)
     self.audio = MP4(self.filename)
    def writeTags(self, mp4Path, artwork=True, thumbnail=False):
        self.log.info("Tagging file: %s." % mp4Path)
        ext = os.path.splitext(mp4Path)[1][1:]
        if ext not in valid_output_extensions:
            self.log.error("File is not the correct format.")
            sys.exit()

        video = MP4(mp4Path)
        try:
            video.delete()
        except IOError:
            self.log.debug(
                "Unable to clear original tags, attempting to proceed.")

        video["\xa9nam"] = self.title  # Movie title
        video["desc"] = self.shortdescription  # Short description
        video["ldes"] = self.description  # Long description
        video["\xa9day"] = self.date  # Year
        video["stik"] = [9]  # Movie iTunes category
        if self.HD is not None:
            video["hdvd"] = self.HD
        if self.genre is not None:
            genre = None
            for g in self.genre:
                if genre is None:
                    genre = g['name']
                    break
                # else:
                # genre += ", " + g['name']
            video["\xa9gen"] = genre  # Genre(s)
        video[
            "----:com.apple.iTunes:iTunMOVI"] = self.xml  # XML - see xmlTags method
        rating = self.rating()
        if rating is not None:
            video["----:com.apple.iTunes:iTunEXTC"] = rating

        if artwork:
            path = self.getArtwork(mp4Path)
            if path is not None:
                cover = open(path, 'rb').read()
                if path.endswith('png'):
                    video["covr"] = [MP4Cover(cover, MP4Cover.FORMAT_PNG)
                                     ]  # png poster
                else:
                    video["covr"] = [MP4Cover(cover, MP4Cover.FORMAT_JPEG)
                                     ]  # jpeg poster
        if self.original:
            video["\xa9too"] = "MDH:" + os.path.basename(self.original)
        else:
            video["\xa9too"] = "MDH:" + os.path.basename(mp4Path)

        for i in range(3):
            try:
                self.log.info("Trying to write tags.")
                video.save()
                self.log.info("Tags written successfully.")
                break
            except IOError as e:
                self.log.info("Exception: %s" % e)
                self.log.exception(
                    "There was a problem writing the tags. Retrying.")
                time.sleep(5)
def trigger_library_scan():
  def prettify_time(time, round_to="minutes"):

    if round_to == "minutes":
      time_hours = math.floor(time/3600)
      time = time - time_hours*3600

      time_minutes = round(time/60)

      if time_hours == 0:
        time_string = f"{time_minutes} min"
      else:
        time_string = f"{time_hours} hr {time_minutes} min"

    elif round_to == "hours":
      time_string = f"{round(time/3600)} hr"

    return time_string

  with open("db/library.json", "r") as f:
    library_old = json.load(f)
  
  return_message_books_added = []

  audiobook_authors_path = "/mnt/plexmedia/Audiobooks"

  audiobook_dict = {}

  author_dirpath, author_dirnames, author_filenames = next(os.walk(audiobook_authors_path))
  author_dirnames.sort()

  for author_dirname in author_dirnames:
  # for author_dirname in [author_dirnames[1]]:

    audiobook_dict[author_dirname] = {}

    audiobook_book_path = os.path.join(author_dirpath, author_dirname)
    book_dirpath, book_dirnames, book_filenames = next(os.walk(audiobook_book_path))
    book_dirnames.sort()

    for book_dirname in book_dirnames:

      # If the book DOESN'T already exist in the library, then display the newly added book
      if not ((author_dirname in library_old) and (book_dirname in library_old[author_dirname])):
        return_message_books_added.append(f"{author_dirname}/{book_dirname}")

      book_length_seconds = 0
      book_file_size_bytes = 0
      book_tracks = {}

      audiobook_track_path = os.path.join(book_dirpath, book_dirname)
      track_dirpath, track_dirnames, track_filenames = next(os.walk(audiobook_track_path))
      track_filenames.sort()

      track_number = 1

      for track_filename in track_filenames:
        track_full_path = os.path.join(track_dirpath, track_filename)
        
        if(track_full_path.endswith(".mp3") or track_full_path.endswith(".m4a") or track_full_path.endswith(".m4b")):
          book_file_size_bytes += os.path.getsize(track_full_path)
        
        try:
          # Attempt to read the track length from the old library JSON
          track_length_seconds = library_old[author_dirname][book_dirname]["tracks"][track_filename]["track_length_seconds"]
        except:
          # If the track length didn't exist in the old library JSON, then read the track length directly
          try:
            if(track_full_path.endswith(".mp3")):
              track_length_seconds = round(MP3(track_full_path).info.length)
            elif(track_full_path.endswith(".m4a")):
              track_length_seconds = round(MP4(track_full_path).info.length)
            elif(track_full_path.endswith(".m4b")):
              track_length_seconds = round(MP4(track_full_path).info.length)
            else:
              track_length_seconds = 0

          except:
            track_length_seconds = 0


        book_length_seconds += track_length_seconds

        book_tracks[track_filename] = {}
        book_tracks[track_filename]["track_length"] = prettify_time(track_length_seconds)
        book_tracks[track_filename]["track_length_seconds"] = track_length_seconds
        book_tracks[track_filename]["track_number"] = track_number
        
        track_number += 1

      title_search = re.search('(\d\d\d\d) - (.*) \((.*)\)', book_dirname)

      year = int(title_search.group(1))
      book_title = title_search.group(2)
      narrator = title_search.group(3)

      audiobook_dict[author_dirname][book_dirname] = {
        "year": year,
        "book_title": book_title,
        "narrator": narrator,
        "book_length": prettify_time(book_length_seconds, round_to="hours"),
        "book_length_seconds": book_length_seconds,
        "book_file_size_bytes": book_file_size_bytes,
        "book_file_size_MB": round(book_file_size_bytes/1024/1024),
        "tracks": book_tracks,
      }

      # Get book cover

      cover_image_file = f"../audiobook-player-frontend/static/cover_images/{author_dirname}_{book_dirname}.jpg"

      # Check if the cover file DOESN'T exist
      if not (os.path.isfile(cover_image_file)):
        open_library_search_url = f"http://openlibrary.org/search.json?author={urllib.parse.quote(author_dirname)}&title={urllib.parse.quote(book_title)}"
        print(f"Searching for book: {open_library_search_url}")
        response = requests.get(open_library_search_url)
        response_body = response.json()

        download_generic_cover_image = False

        if(response_body["numFound"] > 0):
          cover_edition_key_found = False

          for book_result in response_body["docs"]:
            if("cover_edition_key" in book_result):
              print("Found cover edition key")
              cover_edition_key_found = True

              open_library_cover_edition_key = book_result["cover_edition_key"]
              open_library_cover_url = f"http://covers.openlibrary.org/b/olid/{open_library_cover_edition_key}-L.jpg"
              print(f"Searching for cover image: {open_library_cover_url}")

              image_response = requests.get(open_library_cover_url)

              with open(cover_image_file, 'wb') as f:
                f.write(image_response.content)

              break

          if(cover_edition_key_found == False):
            download_generic_cover_image = True
            print("Cover edition key not found, skipping")
            
        else:
          download_generic_cover_image = True
          print(f"No results found for: {open_library_search_url}")

        if(download_generic_cover_image):
          print("Downloading generic cover image")
          print()

          with open(cover_image_file, 'wb') as f:
            f.write(requests.get("https://memegenerator.net/img/images/16143029/generic-book-cover.jpg").content)


  with open("db/library.json", "w") as f:
    f.write(json.dumps(audiobook_dict, indent = 2))

    # return return_message
    return render_template(
      'scan_complete.html',
      return_message_books_added=return_message_books_added,
      # return_message_books_added=["hello there", "this is a test", "testing123"]
    )
Exemple #12
0
def detect_file_codec(path):
    """
    Try to detect codec for file
    """

    if not os.path.isfile(path):
        return None

    name, extension = os.path.splitext(path)

    if extension in ('.m4a', 'caf'):
        from mutagen.mp4 import MP4
        try:
            codec = MP4(path).info.codec
            if codec == 'alac':
                return codec
            elif codec[:4] == 'mp4a':
                return 'aac'
        except Exception as e:
            raise ValueError('Error detecting file {} codec: {}'.format(
                path, e))

    if extension == '.aif':
        from mutagen.aiff import AIFF
        try:
            AIFF(path).info
            return 'aif'
        except Exception as e:
            raise ValueError('Error opening {} as aif: {}'.format(path, e))

    if extension == '.flac':
        from mutagen.flac import FLAC
        try:
            FLAC(path).info
            return 'flac'
        except Exception as e:
            raise ValueError('Error opening {} as flac: {}'.format(path, e))

    if extension == '.mp3':
        from mutagen.mp3 import MP3
        try:
            MP3(path).info
            return 'mp3'
        except Exception as e:
            raise ValueError('Error opening {} as mp3: {}'.format(path, e))

    if extension == '.opus':
        from mutagen.oggopus import OggOpus
        try:
            OggOpus(path).info
            return 'opus'
        except Exception as e:
            raise ValueError('Error opening {} as mp3: {}'.format(path, e))

    if extension == '.ogg':
        from mutagen.oggvorbis import OggVorbis
        try:
            OggVorbis(path).info
            return 'vorbis'
        except Exception as e:
            raise ValueError('Error opening {} as ogg vorbis: {}'.format(
                path, e))

    if extension == '.wv':
        from mutagen.wavpack import WavPack
        try:
            WavPack(path).info
            return 'wavpack'
        except Exception as e:
            raise ValueError('Error opening {} as wavpack: {}'.format(path, e))

    return None
Exemple #13
0
def mp3_tag(absolute_song_fp, song):
    '''tag mp3 with metdata'''
    default_path = os.path.dirname(os.path.realpath(__file__))
    no_cover_art = [
        '/img/no_album_art.png', '', '/web-client/images/empty_album.png',
        '/web-client/images/empty_album.png'
    ]
    song['coverart'] = song['coverart'].replace('"', '')
    ## Seeing if the try except clause below will fix the url error when no album art is available
    # if song['coverart'] not in no_cover_art:
    #     r = urllib2.urlopen(song['coverart'])
    #     picture_type = song['coverart'].split('.')[-1]
    #     cover_art_path = default_path + '\\' + 'coverart' + '.' + picture_type
    #     temp_art = open(cover_art_path, 'wb')
    #     temp_art.write(r.read())
    #     temp_art.close()
    # else:
    try:
        r = urllib2.urlopen(song['coverart'])
        picture_type = song['coverart'].split('.')[-1]
        cover_art_path = default_path + '\\' + 'coverart' + '.' + picture_type
        temp_art = open(cover_art_path, 'wb')
        temp_art.write(r.read())
        temp_art.close()
    except:
        song['coverart'] = None
    if SONG_QUALITY == '.m4a':
        try:
            audio = MP4(absolute_song_fp)
            if song['coverart']:
                with open(cover_art_path, 'rb') as f:
                    audio['covr'] = [
                        MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_PNG)
                    ]
                os.remove(cover_art_path)  # delete coverart
            audio["\xa9nam"] = unicode(song['song'])
            audio["\xa9ART"] = unicode(song['artist'])
            audio["\xa9alb"] = unicode(song['album'])
            audio.save()
        except:
            print "\nUnexpected error:", sys.exc_info()[0]
            pass
    if SONG_QUALITY == '.mp3':
        try:
            audio = MP3(absolute_song_fp)
            if song['coverart']:
                audio.tags.add(
                    APIC(
                        encoding=3,  # 3 is for utf-8
                        mime='image/' +
                        picture_type,  # image/jpeg or image/png
                        type=3,  # 3 is for the cover image
                        desc=u'Cover',
                        data=open(cover_art_path, 'rb').read()))
                os.remove(cover_art_path)  # delete coverart
            audio.tags.add(TIT2(encoding=3, text=unicode(song['song'])))
            audio.tags.add(TPE1(encoding=3, text=unicode(song['artist'])))
            audio.tags.add(TALB(encoding=3, text=unicode(song['album'])))
            audio.save(mp3, v1=2, v2_version=3)
        except:
            print "\nUnexpected error:", sys.exc_info()[0]
            pass
    print ""
Exemple #14
0
    def TagTrack(self, folder, export=''):
        '''
            'Tag' a song's trackdata with the infomation given in folder

            Call once all download tasks is finished

            Suppports MP3,M4A(ALAC/MP4),FLAC
        '''

        export = export if export else self.output
        folder = str(folder)
        audio = [f for f in os.listdir(folder) if f.split('.')[-1].lower() in ['mp3', 'm4a', 'flac','ogg']]
        if not audio:
            logger.error('Supported audio file is missing,Cannot continue formatting!')
            return     
        audio = audio[-1]
        audio = self.GenerateDownloadPath(filename=audio, folder=folder)
        format = audio.split('.')[-1].lower()
        # Locate audio file,uses last match
        track = self.GenerateDownloadPath(filename='track.json', folder=folder)
        # Locate track file
        cover = self.GenerateDownloadPath(filename='cover.jpg', folder=folder)
        # Locate cover image

        track = json.loads(open(track, encoding='utf-8').read())
        tHelper = TrackHelper(track)

        def write_keys(song):
            # Write trackdatas
            song['title'] = tHelper.TrackName
            song['artist'] = tHelper.Artists if tHelper.Artists else 'Various Artists'
            song['album'] = tHelper.AlbumName if tHelper.AlbumName else 'Unknown'
            song['tracknumber'] = str(tHelper.TrackNumber)
            song['date'] = str(tHelper.TrackPublishTime)
            song.save()

        if format == 'm4a':
            # Process m4a files: Apple’s MP4 (aka M4A, M4B, M4P)
            song = easymp4.EasyMP4(audio)
            write_keys(song)
            if os.path.exists(cover):
                song = MP4(audio)
                # Write cover image
                song['covr'] = [MP4Cover(open(cover, 'rb').read())]
                song.save()
        elif format == 'mp3':
            # Process mp3 files: MPEG audio stream information and tags
            song = EasyMP3(audio)
            write_keys(song)
            if os.path.exists(cover):
                song = ID3(audio)
                # Write cover image
                song.add(APIC(encoding=3, mime='image/jpeg', type=3,
                              desc='Cover', data=open(cover, 'rb').read()))
                song.save()
        elif format == 'flac':
            # Process FLAC files:Free Lossless Audio Codec
            song = FLAC(audio)
            write_keys(song)
            if os.path.exists(cover):
                pic = Picture()
                pic.data = open(cover, 'rb').read()
                pic.mime = 'image/jpeg'
                song.add_picture(pic)
                song.save()
        elif format == 'ogg':
            # Process OGG files:Ogg Encapsulation Format
            song = OggVorbis(audio)
            write_keys(song)
            if os.path.exists(cover):
                pic = Picture()
                pic.data = open(cover, 'rb').read()
                pic.mime = 'image/jpeg'
                song["metadata_block_picture"] = [base64.b64encode(pic.write()).decode('ascii')]
                song.save()
        # Rename & move file
        savename = tHelper.Title + '.' + format
        try:
            path = self.GenerateDownloadPath(filename=savename, folder=export)
            shutil.copy(audio, path)
            logger.debug('Exported audio to path %s' % path[-truncate_length:])
            return path
        except Exception as e:
            raise Exception('While copying audio file:%s' % e)
Exemple #15
0
def read_tags(path, genre_separator):
    from mutagen.id3 import ID3
    from mutagen.mp3 import MP3
    from mutagen.mp4 import MP4

    try:
        audio = MP4(path)
        tags = {
            'title': str(audio['\xa9nam'][0]),
            'artist': str(audio['\xa9ART'][0]),
            'album': str(audio['\xa9alb'][0]),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'aART' in audio:
            tags['albumartist'] = str(audio['aART'][0])
        if '\xa9gen' in audio:
            tags['genres'] = []
            for g in audio['\xa9gen']:
                tags['genres'].append(str(g))
        #_LOGGER.debug('MP4 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except:
        pass

    try:
        audio = MP3(path)
        tags = {
            'title': str(audio['TIT2']),
            'artist': str(audio['TPE1']),
            'album': str(audio['TALB']),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'TPE2' in audio:
            tags['albumartist'] = str(audio['TPE2'])
        if 'TCON' in audio:
            tags['genres'] = str(audio['TCON']).split(genre_separator)
        #_LOGGER.debug('MP3 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except Exception as e:
        #print("EX:%s" % str(e))
        pass

    try:
        audio = ID3(path)
        tags = {
            'title': str(audio['TIT2']),
            'artist': str(audio['TPE1']),
            'album': str(audio['TALB']),
            'duration': 0,
            'albumartist': None,
            'genres': None
        }
        if 'TPE2' in audio:
            tags['albumartist'] = str(audio['TPE2'])
        if 'TCON' in audio:
            tags['genres'] = str(audio['TCON']).split(genre_separator)
        #_LOGGER.debug('ID3 File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags
    except:
        pass

    audio = get_ogg_or_flac(path)
    if audio:
        tags = {
            'title': str(audio['TITLE'][0]),
            'artist': str(audio['ARTIST'][0]),
            'album': str(audio['ALBUM'][0]),
            'duration': int(audio.info.length),
            'albumartist': None,
            'genres': None
        }
        if 'ALBUMARTIST' in audio:
            tags['albumartist'] = str(audio['ALBUMARTIST'][0])
        if 'GENRE' in audio:
            tags['genres'] = []
            for g in audio['GENRE']:
                tags['genres'].append(str(g))
        #_LOGGER.debug('OGG File: %s Meta: %s' % (path, json.dumps(tags)))
        return tags

    _LOGGER.debug('File:%s Meta:NONE' % path)
    return None
def applyData(filePath):
	global data, artwork
	tagged_file= MP4(filePath)
	genres=[]
	if 'genres' in data:
		for genre in data['genres']:
			genres.append(genre['name'])
		tagged_file['\xa9gen'] = genres
	if 'overview' in data:
		tagged_file['ldes'] = data['overview']
		tagged_file['desc'] = data['overview']
	if 'title' in data:
		tagged_file['\xa9alb'] = data['title']
		tagged_file['aART'] = data['title']
		tagged_file['\xa9nam'] = data['title']
	elif 'original_title' in data:
		tagged_file['\xa9alb'] = data['original_title']
		tagged_file['aART'] = data['original_title']
		tagged_file['\xa9nam'] = data['original_title']

	if 'season_number' in data:
		tagged_file['tvsn'] = [data['season_number']]
	if 'episode_number' in data:
		tagged_file['tves'] = [data['episode_number']]
	if artwork != "":
		
		with open(artwork, "rb") as f:
			tagged_file["covr"] = [
				MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
			]
	if 'air_date' in data:
		tagged_file['\xa9day'] = data['air_date'][:4]
	if 'name' in data:
		tagged_file['\xa9nam'] = data['name']
	if 'original_name' in data:
		tagged_file['tvsh'] = data['original_name']
		tagged_file['\xa9alb'] = data['original_name']
		tagged_file['\xa9ART'] = data['original_name']
		tagged_file['aART'] = data['original_name']
	if 'release_date' in data:
		tagged_file['\xa9day'] = data['release_date'][:4]
	vid = cv2.VideoCapture(filePath)
	width = vid.get(cv2.CAP_PROP_FRAME_WIDTH)

	if width > 1919 and width < 3839:
		tagged_file['hdvd'] = [2]
	elif width < 1919 and width > 1279:
		tagged_file['hdvd'] = [1]
	elif width > 3839:
		tagged_file['hdvd'] = [3]
	else:
		tagged_file['hdvd'] = [0]

	if isTV:
		cast_crew_data = getCastandCrew(data['id'], "tv")
	else:
		cast_crew_data = getCastandCrew(data['id'], "movie")
	cast = []
	directors = []
	screenwriters = []
	producers = []
	producer_re = re.compile("Producer$")
	for cast_member in cast_crew_data['cast']:
		cast.append(cast_member['name'])

	for crew_members in cast_crew_data['crew']:
		if crew_members['job'] == "Director":
			directors.append(crew_members['name'])
		if crew_members['department'] == "Writing":
			screenwriters.append(crew_members['name'])
		if producer_re.search(crew_members['job']):
			producers.append(crew_members['name'])

	xml_str = "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
	xml_str += "<plist version=\"1.0\">\n"
	xml_str += "<dict>"
	xml_str += generateXML(cast, "cast")
	xml_str += generateXML(directors, "directors")
	xml_str += generateXML(screenwriters, "screenwriters")
	xml_str += generateXML(producers, "producers")
	xml_str += "</dict>"
	xml_str += "</plist>"

	tagged_file['----:com.apple.iTunes:iTunMOVI'] = str.encode(xml_str)

	rating = getClassification(data['id'])
	tagged_file['----:com.apple.iTunes:iTunEXTC'] = str.encode(
		"b'mpaa|" + rating + "|300|")

	if isTV:
		tagged_file['stik'] = [10]
	else:
		tagged_file['stik'] = [9]
	tagged_file.save()
Exemple #17
0
import sys

if len(sys.argv) > 1:
    path = sys.argv[1]
    pathlist = path.split('\\')
    imagepath = ''
    for sec in pathlist[:-1]:
        imagepath = imagepath + sec + '\\'
    imagepath = imagepath + 'Folder.jpg'
else:
    print('No argument')
    raw_input()
    sys.exit()

if path[-3:] == 'm4a':
    file = MP4(path)
    try:
        artwork = file.tags['covr'][0]
    except:
        print('Cover Not Found')
        raw_input()
        sys.exit()
elif path[-3:] == 'mp3':
    file = File(path)
    try:
        artwork = file.tags['APIC:'].data
    except:
        print('Cover Not Found')
        raw_input()
        sys.exit()
else:
Exemple #18
0
            #	AllInfo['coverPath'] = REPCover+"/"+os.path.basename(path)+".jpg"
            #else:
            AllInfo['coverPath'] = 'images/defaultcover.png'

            # insertion des infos en tables
            InsertSQLAudio(AllInfo)

        # -----------------------------------------
        # insertion des fichiers MP4 en table
        # -----------------------------------------
        elif ".M4A" in filename or ".m4a" in filename:

            i = i + 1

            # recuperation des infos via Mutagen
            MutaMP4 = MP4(path + "/" + filename)
            AllInfo = {'Duree': MutaMP4.info.length}

            if '\xa9ART' in MutaMP4.keys():
                AllInfo['Artist'] = MutaMP4['\xa9ART'][0]
            else:
                AllInfo['Artist'] = "Unknown"

            if '\xa9alb' in MutaMP4.keys():
                AllInfo['Album'] = MutaMP4['\xa9alb'][0]
            else:
                AllInfo['Album'] = "Unknown"

            if '\xa9nam' in MutaMP4.keys():
                AllInfo['Titre'] = MutaMP4['\xa9nam'][0]
            else:
Exemple #19
0
 def test_delete(self):
     self.audio.delete()
     audio = MP4(self.audio.filename)
     self.failIf(audio.tags)
     self.faad()
Exemple #20
0
 def __init__(self, filename):
     from mutagen.mp4 import MP4
     self._movie = MP4(filename)