コード例 #1
0
    def _inspect_mp3(self):
        "Cracks open the mp3 file and determines what is inside."
        self._fileobj.seek(0)
        infoobj = MPEGInfo(self._fileobj)
        self._fileobj.seek(0)
        id3obj = ID3File(self._fileobj)

        self.album = id3obj.get('TALB').text[0] if 'TALB' in id3obj else None
        self.artist = id3obj.get('TPE1').text[0] if 'TPE1' in id3obj else None
        self.band = id3obj.get('TPE2').text[0] if 'TPE2' in id3obj else None
        self.bitrate = infoobj.bitrate
        try:
            self.disc = +id3obj.get('TPOS') if 'TPOS' in id3obj else None
        except:
            self.disc = None
        self.genre = id3obj.get('TCON').text[0] if 'TCON' in id3obj else None
        self.is_sketchy = infoobj.sketchy
        self.length = infoobj.length
        self.lossy = True
        self.name = id3obj.get('TIT2').text[0] if 'TIT2' in id3obj else None
        self.samplerate = infoobj.sample_rate
        try:
            self.track = +id3obj.get('TRCK') if 'TRCK' in id3obj else None
        except:
            self.track = None
        self.year = int(id3obj['TDRC'].text[0].year) if 'TDRC' in id3obj else None

        self.artwork = []
        for apic in id3obj.getall('APIC'):
            # We have a picture!  Extract it onto its own AssetFile.
            self.artwork.append({'data': apic.data, 'mimetype': apic.mime})
コード例 #2
0
ファイル: test_mp3.py プロジェクト: mars-trueplus/mutagen
 def test_xing_unknown_framecount(self):
     frame = (
         b'\xff\xfb\xe4\x0c\x00\x0f\xf0\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
         b'\x00\x00\x00\x00Info\x00\x00\x00\x02\x00\xb4V@\x00\xb4R\x80\x00'
         b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
     fileobj = cBytesIO(frame)
     info = MPEGInfo(fileobj)
     assert info.bitrate == 320000
     assert info.length > 0
コード例 #3
0
    def test_length(self):
        # http://code.google.com/p/mutagen/issues/detail?id=125
        # easyid3, normal id3 and mpeg loading without tags should skip
        # the tags and get the right offset of the first frame
        easy = self.mp3.info
        noneasy = MP3(self.filename).info
        nonid3 = MPEGInfo(open(self.filename, "rb"))

        self.failUnlessEqual(easy.length, noneasy.length)
        self.failUnlessEqual(noneasy.length, nonid3.length)
コード例 #4
0
ファイル: mp3.py プロジェクト: ComradeDOS/vksaver
def get_bitrate(url):
    response = urlopen(url)
    buff = response.read(10)
    header = unpack('!3sBBBBBBB', buff)
    if header[0] == 'ID3':
        response.read(get_tags_len(header[-4:]) - 10)
        buff = response.read(32)
    else:
        buff += response.read(22)
    try:
        bitrate = MPEGInfo(StringIO(buff)).bitrate
    except Exception, exc:
        print exc
        try:
            bitrate = MPEGInfo(StringIO(buff +
                                        response.read(512 - 32))).bitrate
        except Exception, exc:
            print exc
            bitrate = 0
コード例 #5
0
ファイル: test_mp3.py プロジェクト: mars-trueplus/mutagen
    def test_length(self):
        # https://github.com/quodlibet/mutagen/issues/125
        # easyid3, normal id3 and mpeg loading without tags should skip
        # the tags and get the right offset of the first frame
        easy = self.mp3.info
        noneasy = MP3(self.filename).info
        with open(self.filename, "rb") as h:
            nonid3 = MPEGInfo(h)

        self.failUnlessEqual(easy.length, noneasy.length)
        self.failUnlessEqual(noneasy.length, nonid3.length)
def parsed_show_page(show_page_url):
    """
    Takes a Sound Portraits episode and finds out some salient information
    This entails downloading the episode to get duration data, so it is _slow_
    :param str show_page_url:
    :returns tuple: Data about this Sound Portraits episode, None if no MP3
    """
    r = requests.get(show_page_url)
    bs = BeautifulSoup(r.text, 'lxml')

    title = html.unescape(bs.title.contents[0].split(':')[0]).strip()

    if show_page_url in air_dict:
        premiere = air_dict[show_page_url]

    else:
        premiere = sub_string(r.text, '<!-- Start premiere info -->',
                              '<!-- Start premiere info -->').strip()
        premiere = sub_string(premiere, 'Premiered ', ', on').strip()
        premiere = datetime.strptime(premiere, '%B %d, %Y')

    body = sub_string(r.text, '<!-- Start body text -->',
                      '<!--End body text -->').strip()
    body = ' '.join(body.split())
    body = body.replace(' </p> <p> ', '\n')
    body = body.replace('</p> <p>', '\n')
    body = body.replace('<p>', '')
    body = BeautifulSoup(html.unescape(body), 'lxml').text.strip()

    if show_page_url[-1] == '/':
        audio_page_url = '{}audio.php'.format(show_page_url)
    else:
        audio_page_url = '{}/audio.php'.format(show_page_url)

    try:
        r = requests.get(audio_page_url)
        bs = BeautifulSoup(r.text, 'lxml')
        flashvars = bs.find('param', {'name': 'FlashVars'})['value']
        soundfile = sub_string(flashvars, 'soundFile=', '.mp3') + '.mp3'
        soundfile = soundfile.replace('%2F', '/').replace('%3A', ':')

        r = requests.get(soundfile)
        temp = NamedTemporaryFile()
        temp.write(r.content)
        duration = MPEGInfo(temp).length
        size = os.stat(temp.name).st_size
        temp.close()

    except:
        # If we can't find the sound file page, forget it.
        return None

    return (premiere, title, body, soundfile, duration, size)
コード例 #7
0
async def get_mp3_file_duration(path: str) -> int:
    if not path:
        return 0

    try:
        async with async_open(path, 'rb') as afp:
            data = await afp.read()

        return MPEGInfo(BytesIO(data)).length
    except Exception as err:
        logger.warning(f'Error on read mp3 file: {err}')

    return 0
コード例 #8
0
ファイル: common.py プロジェクト: GUAN-YE/hd_api_djs
def get_duration(url):
    "返回音频时长"
    try:
        f = urllib.urlopen(url)
        data = f.read()
        f.close()
        f = StringIO(data)
        info = MPEGInfo(f)
        duration = math.ceil(info.length)
        f.close()
        return duration
    except:
        return 0
コード例 #9
0
ファイル: common.py プロジェクト: JiaLin-Leung/hdkt_test
def get_duration(url):
    """
    返回音频时长
    :param url: 绝对路径
    :return:
    """
    try:
        if url:
            with urllib.request.urlopen(url) as response:
                data = response.read()
                f = BytesIO(data)
                info = MPEGInfo(f)
                duration = math.ceil(info.length)
                f.close()
        else:
            duration = 0
        return duration
    except Exception as e:
        logging.error(e)
    return 0
コード例 #10
0
 def test_not_real_file(self):
     filename = os.path.join("tests", "data", "silence-44-s-v1.mp3")
     fileobj = cBytesIO(open(filename, "rb").read(20))
     MPEGInfo(fileobj)
コード例 #11
0
    def do_update_file_info(self, file):
        info = FileExtensionInfo()

        # strip file:// to get absolute path
        filename = urllib.unquote(file.get_uri()[7:])

        # mp3 handling
        if file.is_mime_type('audio/mpeg'):
            # attempt to read ID3 tag
            try:
                audio = EasyID3(filename)
                # sometimes the audio variable will not have one of these items defined, that's why
                # there is this long try / except attempt
                try:
                    info.title = audio["title"][0]
                except:
                    pass
                try:
                    info.album = audio["album"][0]
                except:
                    pass
                try:
                    info.artist = audio["artist"][0]
                except:
                    pass
                try:
                    info.tracknumber = audio["tracknumber"][0]
                except:
                    pass
                try:
                    info.genre = audio["genre"][0]
                except:
                    pass
                try:
                    info.date = audio["date"][0]
                except:
                    pass
            except:
                pass

            # try to read MP3 information (bitrate, length, samplerate)
            try:
                mpfile = open(filename)
                mpinfo = MPEGInfo(mpfile)
                info.bitrate = str(mpinfo.bitrate / 1000) + " Kbps"
                info.samplerate = str(mpinfo.sample_rate) + " Hz"
                # [SabreWolfy] added consistent formatting of times in format hh:mm:ss
                # [SabreWolfy[ to allow for correct column sorting by length
                mp3length = "%02i:%02i:%02i" % ((int(mpinfo.length / 3600)),
                                                (int(mpinfo.length / 60 % 60)),
                                                (int(mpinfo.length % 60)))
                mpfile.close()
                info.length = mp3length
            except:
                try:
                    mpfile.close()
                except:
                    pass

        # image handling
        elif file.is_mime_type('image/jpeg') or file.is_mime_type(
                'image/png') or file.is_mime_type(
                    'image/gif') or file.is_mime_type('image/bmp'):
            # EXIF handling routines
            try:
                metadata = pyexiv2.ImageMetadata(filename)
                metadata.read()
                try:
                    exif_datetimeoriginal = metadata[
                        'Exif.Photo.DateTimeOriginal']
                    info.exif_datetime_original = str(
                        exif_datetimeoriginal.raw_value)
                except:
                    pass
                try:
                    exif_imagesoftware = metadata['Exif.Image.Software']
                    info.exif_software = str(exif_imagesoftware.raw_value)
                except:
                    pass
                try:
                    exif_photoflash = metadata['Exif.Photo.Flash']
                    info.exif_flash = str(exif_photoflash.raw_value)
                except:
                    pass
                try:
                    exif_rating = metadata['Xmp.xmp.Rating']
                    info.exif_rating = str(exif_rating.raw_value)
                except:
                    pass
            except:
                pass
            # try read image info directly
            try:
                im = Image.open(filename)
                info.pixeldimensions = str(im.size[0]) + 'x' + str(im.size[1])
            except error as e:
                print e
                pass

        # video/flac handling
        elif file.is_mime_type('video/x-msvideo') | file.is_mime_type(
                'video/mpeg'
        ) | file.is_mime_type('video/x-ms-wmv') | file.is_mime_type(
                'video/mp4'
        ) | file.is_mime_type('audio/x-flac') | file.is_mime_type(
                'video/x-flv') | file.is_mime_type(
                    'video/x-matroska') | file.is_mime_type('audio/x-wav'):
            try:
                metadata = kaa.metadata.parse(filename)
                try:
                    info.length = "%02i:%02i:%02i" % (
                        (int(metadata.length / 3600)),
                        (int(metadata.length / 60 % 60)),
                        (int(metadata.length % 60)))
                except:
                    pass
                try:
                    info.pixeldimensions = str(
                        metadata.video[0].width) + 'x' + str(
                            metadata.video[0].height)
                except:
                    pass
                try:
                    info.bitrate = str(round(metadata.audio[0].bitrate / 1000))
                except:
                    pass
                try:
                    info.samplerate = str(int(
                        metadata.audio[0].samplerate)) + ' Hz'
                except:
                    pass
                try:
                    info.title = metadata.title
                except:
                    pass
                try:
                    info.artist = metadata.artist
                except:
                    pass
                try:
                    info.genre = metadata.genre
                except:
                    pass
                try:
                    info.tracknumber = metadata.trackno
                except:
                    pass
                try:
                    info.date = metadata.userdate
                except:
                    pass
                try:
                    info.album = metadata.album
                except:
                    pass
            except:
                pass

        # pdf handling
        elif file.is_mime_type('application/pdf'):
            try:
                f = open(filename, "rb")
                pdf = PdfFileReader(f)
                try:
                    info.title = pdf.getDocumentInfo().title
                except:
                    pass
                try:
                    info.artist = pdf.getDocumentInfo().author
                except:
                    pass
                f.close()
            except:
                pass

        self.set_file_attributes(file, info)

        del info
コード例 #12
0
	def update_file_info(self, file):
		# set defaults to blank
		file.add_string_attribute('title', '')
		file.add_string_attribute('album', '')
		file.add_string_attribute('artist', '')
		file.add_string_attribute('tracknumber', '')
		file.add_string_attribute('genre', '')
		file.add_string_attribute('date', '')
		file.add_string_attribute('bitrate', '')
		file.add_string_attribute('samplerate', '')
		file.add_string_attribute('length', '')
		file.add_string_attribute('exif_datetime_original', '')
		file.add_string_attribute('exif_software', '')
		file.add_string_attribute('exif_flash', '')
		file.add_string_attribute('exif_pixeldimensions', '')
		file.add_string_attribute('exif_rating','')
		file.add_string_attribute('pixeldimensions', '')

		if file.get_uri_scheme() != 'file':
			return

		# strip file:// to get absolute path
		filename = urllib.unquote(file.get_uri()[7:])
		
		# mp3 handling
		if file.is_mime_type('audio/mpeg'):
			# attempt to read ID3 tag
			try:
				audio = EasyID3(filename)
				# sometimes the audio variable will not have one of these items defined, that's why
				# there is this long try / except attempt
				try: file.add_string_attribute('title', audio["title"][0])
				except: file.add_string_attribute('title', "[n/a]")
				try: file.add_string_attribute('album', audio["album"][0])
				except: file.add_string_attribute('album', "[n/a]")
				try: file.add_string_attribute('artist', audio["artist"][0])
				except: file.add_string_attribute('artist', "[n/a]")
				try: file.add_string_attribute('tracknumber', audio["tracknumber"][0])
				except: file.add_string_attribute('tracknumber', "[n/a]")
				try: file.add_string_attribute('genre', audio["genre"][0])
				except: file.add_string_attribute('genre', "[n/a]")
				try: file.add_string_attribute('date', audio["date"][0])
				except: file.add_string_attribute('date', "[n/a]")
			except:
				# [SabreWolfy] some files have no ID3 tag and will throw this exception:
				file.add_string_attribute('title', "[no ID3]")
				file.add_string_attribute('album', "[no ID3]")
				file.add_string_attribute('artist', "[no ID3]")
				file.add_string_attribute('tracknumber', "[no ID3]")
				file.add_string_attribute('genre', "[no ID3]")
				file.add_string_attribute('date', "[no ID3]")
				
			# try to read MP3 information (bitrate, length, samplerate)
			try:
				mpfile = open (filename)
				mpinfo = MPEGInfo (mpfile)
				file.add_string_attribute('bitrate', str(mpinfo.bitrate/1000) + " Kbps")
				file.add_string_attribute('samplerate', str(mpinfo.sample_rate) + " Hz")
				# [SabreWolfy] added consistent formatting of times in format hh:mm:ss
				# [SabreWolfy[ to allow for correct column sorting by length
				mp3length = "%02i:%02i:%02i" % ((int(mpinfo.length/3600)), (int(mpinfo.length/60%60)), (int(mpinfo.length%60)))
				mpfile.close()
				file.add_string_attribute('length', mp3length)
			except:
				file.add_string_attribute('bitrate', "[n/a]")
				file.add_string_attribute('length', "[n/a]")
				file.add_string_attribute('samplerate', "[n/a]")
				try:
					mpfile.close()
				except:	pass
	
		# image handling
		if file.is_mime_type('image/jpeg') or file.is_mime_type('image/png') or file.is_mime_type('image/gif') or file.is_mime_type('image/bmp'):
			# EXIF handling routines
			try:
				metadata = pyexiv2.ImageMetadata(filename)
				metadata.read()
				try:
					exif_datetimeoriginal = metadata['Exif.Photo.DateTimeOriginal']
					file.add_string_attribute('exif_datetime_original',str(exif_datetimeoriginal.raw_value))
				except:
					file.add_string_attribute('exif_datetime_original',"")
				try:
					exif_imagesoftware = metadata['Exif.Image.Software']
					file.add_string_attribute('exif_software',str(exif_imagesoftware.raw_value))
				except:
					file.add_string_attribute('exif_software',"")
				try:
					exif_photoflash = metadata['Exif.Photo.Flash']
					file.add_string_attribute('exif_flash',str(exif_photoflash.raw_value))
				except:
					file.add_string_attribute('exif_flash',"")
				try:
					exif_pixelydimension = metadata['Exif.Photo.PixelYDimension']
					exif_pixelxdimension = metadata['Exif.Photo.PixelXDimension']
					file.add_string_attribute('exif_pixeldimensions',str(exif_pixelydimension.raw_value)+'x'+str(exif_pixelxdimension.raw_value))
				except:
					file.add_string_attribute('exif_pixeldimensions',"")
				try:
					exif_rating = metadata['Xmp.xmp.Rating']
					stars = ""
					for i in range(1,6):
						if i <= int(exif_rating.raw_value):
							stars += u"\u2605"
						else:
							stars += u"\u2606"
					file.add_string_attribute('exif_rating',stars)
				except:
					file.add_string_attribute('exif_rating',u"\u2606\u2606\u2606\u2606\u2606")
			except:
				# no exif data?
				file.add_string_attribute('exif_datetime_original',"")
				file.add_string_attribute('exif_software',"")
				file.add_string_attribute('exif_flash',"")
				file.add_string_attribute('exif_pixeldimensions',"")
				file.add_string_attribute('exif_rating',u"\u2606\u2606\u2606\u2606\u2606")
			# try read image info directly
			try:
				im = Image.open(filename)
				file.add_string_attribute('pixeldimensions',str(im.size[0])+'x'+str(im.size[1]))
			except:
				file.add_string_attribute('pixeldimensions',"[image read error]")

		# video/flac handling
		if file.is_mime_type('video/x-msvideo') | file.is_mime_type('video/mpeg') | file.is_mime_type('video/x-ms-wmv') | file.is_mime_type('video/mp4') | file.is_mime_type('audio/x-flac') | file.is_mime_type('video/x-flv') | file.is_mime_type('video/x-matroska') | file.is_mime_type('audio/x-wav'):
			try:
				info=kaa.metadata.parse(filename)
				try: file.add_string_attribute('length',"%02i:%02i:%02i" % ((int(info.length/3600)), (int(info.length/60%60)), (int(info.length%60))))
				except: file.add_string_attribute('length','[n/a]')
				try: file.add_string_attribute('pixeldimensions', str(info.video[0].width) + 'x'+ str(info.video[0].height))
				except: file.add_string_attribute('pixeldimensions','[n/a]')
				try: file.add_string_attribute('bitrate',str(round(info.audio[0].bitrate/1000)))
				except: file.add_string_attribute('bitrate','[n/a]')
				try: file.add_string_attribute('samplerate',str(int(info.audio[0].samplerate))+' Hz')
				except: file.add_string_attribute('samplerate','[n/a]')
				try: file.add_string_attribute('title', info.title)
				except: file.add_string_attribute('title', '[n/a]')
				try: file.add_string_attribute('artist', info.artist)
				except: file.add_string_attribute('artist', '[n/a]')
				try: file.add_string_attribute('genre', info.genre)
				except: file.add_string_attribute('genre', '[n/a]')
				try: file.add_string_attribute('tracknumber',info.trackno)
				except: file.add_string_attribute('tracknumber', '[n/a]')
				try: file.add_string_attribute('date',info.userdate)
				except: file.add_string_attribute('date', '[n/a]')					
				try: file.add_string_attribute('album',info.album)
				except: file.add_string_attribute('album', '[n/a]')
			except:
				file.add_string_attribute('length','error')
				file.add_string_attribute('pixeldimensions','error')
				file.add_string_attribute('bitrate','error')
				file.add_string_attribute('samplerate','error')
				file.add_string_attribute('title','error')
				file.add_string_attribute('artist','error')
				file.add_string_attribute('genre','error')
				file.add_string_attribute('track','error')
				file.add_string_attribute('date','error')
				file.add_string_attribute('album','error')
		# pdf handling
		if file.is_mime_type('application/pdf'):
			try:
				f = open(filename, "rb")
				pdf = PdfFileReader(f)
				try: file.add_string_attribute('title', pdf.getDocumentInfo().title)
				except: file.add_string_attribute('title', "[n/a]")
				try: file.add_string_attribute('artist', pdf.getDocumentInfo().author)
				except: file.add_string_attribute('artist', "[n/a]")
				f.close()
			except:
				file.add_string_attribute('title', "[no info]")
				file.add_string_attribute('artist', "[no info]")
					
		self.get_columns()
コード例 #13
0
    def get_property_pages(self, files):
        # files: list of NemoVFSFile
        if len(files) != 1:
            return
        
        file = files[0]
        if file.get_uri_scheme() != 'file':
            return
        
        filename = urllib.unquote(file.get_uri()[7:])
        
        #GUI
        locale.setlocale(locale.LC_ALL, '')
        _ = gettext.gettext
        self.property_label = Gtk.Label(_('Audio'))
        self.property_label.show()
        
        self.builder = Gtk.Builder()
        self.builder.add_from_file("/usr/share/nemo-python/extensions/nemo-audio-tab.glade")
        
        #connect signals to python methods
        self.builder.connect_signals(self)
        
        #connect gtk objects to python variables
        for obj in self.builder.get_objects():
            if issubclass(type(obj), Gtk.Buildable):
                name = Gtk.Buildable.get_name(obj)
                setattr(self, name, obj)
        
        # set defaults to blank to prevent nonetype errors
        file.add_string_attribute('title', '')
        file.add_string_attribute('album', '')
        file.add_string_attribute('artist', '')
        file.add_string_attribute('albumartist', '')
        file.add_string_attribute('tracknumber', '')
        file.add_string_attribute('genre', '')
        file.add_string_attribute('date', '')
        file.add_string_attribute('bitrate', '')
        file.add_string_attribute('samplerate', '')
        file.add_string_attribute('length', '')
        file.add_string_attribute('encodedby', '')
        file.add_string_attribute('copyright', '')
        
        no_info = _("No Info")
        mutaFile = mutagen.File(filename)

        #MP3
        if file.is_mime_type('audio/mpeg'):
            # attempt to read ID3 tag
            try:
                audio = EasyID3(filename)
                # sometimes the audio variable will not have one of these items defined, that's why
                # there is this long try / except attempt
                try: file.add_string_attribute('title', audio["title"][0])
                except: file.add_string_attribute('title', no_info)
                try: file.add_string_attribute('album', audio["album"][0])
                except: file.add_string_attribute('album', no_info)
                try: file.add_string_attribute('artist', audio["artist"][0])
                except: file.add_string_attribute('artist', no_info)
                try: file.add_string_attribute('albumartist', audio["performer"][0])
                except: file.add_string_attribute('albumartist', no_info)
                try: file.add_string_attribute('tracknumber', audio["tracknumber"][0])
                except: file.add_string_attribute('tracknumber', no_info)
                try: file.add_string_attribute('genre', audio["genre"][0])
                except: file.add_string_attribute('genre', no_info)
                try: file.add_string_attribute('date', audio["date"][0])
                except: file.add_string_attribute('date', no_info)
                try: file.add_string_attribute('encodedby', audio["encodedby"][0])
                except: file.add_string_attribute('encodedby', no_info)
                try: file.add_string_attribute('copyright', audio["copyright"][0])
                except: file.add_string_attribute('copyright', no_info)
            except:
                # [SabreWolfy] some files have no ID3 tag and will throw this exception:
                file.add_string_attribute('title', no_info)
                file.add_string_attribute('album', no_info)
                file.add_string_attribute('artist', no_info)
                file.add_string_attribute('albumartist', no_info)
                file.add_string_attribute('tracknumber', no_info)
                file.add_string_attribute('genre', no_info)
                file.add_string_attribute('date', no_info)
                file.add_string_attribute('encodedby', no_info)
                file.add_string_attribute('copyright', no_info)
                
                # try to read MP3 information (bitrate, length, samplerate)
            try:
                mpinfo = MPEGInfo (filename)
                file.add_string_attribute('bitrate', str(mpinfo.bitrate/1000) + " Kbps")

                file.add_string_attribute('samplerate', str(mpinfo.sample_rate) + " Hz")
                # [SabreWolfy] added consistent formatting of times in format hh:mm:ss
                mp3length = "%02i:%02i:%02i" % ((int(mpinfo.length/3600)), (int(mpinfo.length/60%60)), (int(mpinfo.length%60)))
                file.add_string_attribute('length', mp3length)
            except:
                file.add_string_attribute('bitrate', no_info)
                file.add_string_attribute('length', no_info)
                file.add_string_attribute('samplerate', no_info)

        #FLAC
        if file.is_mime_type('audio/flac'):
            try:
                audio = FLAC(filename)
                # sometimes the audio variable will not have one of these items defined, that's why
                # there is this long try / except attempt
                try: file.add_string_attribute('title', audio["title"][0])
                except: file.add_string_attribute('title', no_info)
                try: file.add_string_attribute('album', audio["album"][0])
                except: file.add_string_attribute('album', no_info)
                try: file.add_string_attribute('artist', audio["artist"][0])
                except: file.add_string_attribute('artist', no_info)
                try: file.add_string_attribute('albumartist', audio["albumartist"][0]) # this tag is different then mp3s
                except: file.add_string_attribute('albumartist', no_info)
                try: file.add_string_attribute('tracknumber', audio["tracknumber"][0])
                except: file.add_string_attribute('tracknumber', no_info)
                try: file.add_string_attribute('genre', audio["genre"][0])
                except: file.add_string_attribute('genre', no_info)
                try: file.add_string_attribute('date', audio["date"][0])
                except: file.add_string_attribute('date', no_info)
                try: file.add_string_attribute('encodedby', audio["encoded-by"][0]) # this tag is different then mp3s
                except: file.add_string_attribute('encodedby', no_info)
                try: file.add_string_attribute('copyright', audio["copyright"][0])
                except: file.add_string_attribute('copyright', no_info)
            except:
                # [SabreWolfy] some files have no ID3 tag and will throw this exception:
                file.add_string_attribute('title', no_info)
                file.add_string_attribute('album', no_info)
                file.add_string_attribute('artist', no_info)
                file.add_string_attribute('albumartist', no_info)
                file.add_string_attribute('tracknumber', no_info)
                file.add_string_attribute('genre', no_info)
                file.add_string_attribute('date', no_info)
                file.add_string_attribute('encodedby', no_info)
                file.add_string_attribute('copyright', no_info)
                
                # try to read the FLAC information (length, samplerate)
            try:
                fcinfo = StreamInfo (filename)
                
                file.add_string_attribute('samplerate', str(fcinfo.sample_rate) + " Hz")
                
                # [SabreWolfy] added consistent formatting of times in format hh:mm:ss
                flaclength = "%02i:%02i:%02i" % ((int(mutaFile.info.length/3600)), (int(mutaFile.info.length/60%60)), (int(mutaFile.info.length%60)))
                file.add_string_attribute('length', flaclength)
                file.add_string_attribute('bitrate', no_info) # flac doesn't really have a bitrate
            except:
                file.add_string_attribute('bitrate', no_info)
                file.add_string_attribute('length', no_info)
                file.add_string_attribute('samplerate', no_info)

        self.builder.get_object("title_text").set_label(file.get_string_attribute('title'))
        self.builder.get_object("album_text").set_label(file.get_string_attribute('album'))
        self.builder.get_object("album_artist_text").set_label(file.get_string_attribute('albumartist'))
        self.builder.get_object("artist_text").set_label(file.get_string_attribute('artist'))
        self.builder.get_object("genre_text").set_label(file.get_string_attribute('genre'))
        self.builder.get_object("year_text").set_label(file.get_string_attribute('date'))
        self.builder.get_object("track_number_text").set_label(file.get_string_attribute('tracknumber'))
        self.builder.get_object("sample_rate_text").set_label(file.get_string_attribute('samplerate'))
        self.builder.get_object("length_number").set_label(file.get_string_attribute('length'))
        self.builder.get_object("bitrate_number").set_label(file.get_string_attribute('bitrate'))
        self.builder.get_object("encoded_by_text").set_label(file.get_string_attribute('encodedby'))
        self.builder.get_object("copyright_text").set_label(file.get_string_attribute('copyright'))

        if file.is_mime_type('audio/mpeg') or file.is_mime_type('audio/flac'):
            return Nemo.PropertyPage(name="NemoPython::audio", label=self.property_label, page=self.mainWindow),
コード例 #14
0
    def update_file_info(self, file):
        # set defaults to blank
        file.add_string_attribute('title', '')
        file.add_string_attribute('description', '')
        file.add_string_attribute('album', '')
        file.add_string_attribute('creator', '')
        file.add_string_attribute('tracknumber', '')
        file.add_string_attribute('genre', '')
        file.add_string_attribute('date', '')
        file.add_string_attribute('bitrate', '')
        file.add_string_attribute('samplerate', '')
        file.add_string_attribute('length', '')
        file.add_string_attribute('datetime_original', '')
        file.add_string_attribute('exposure_time', '')
        file.add_string_attribute('fnumber', '')
        file.add_string_attribute('focal_length', '')
        file.add_string_attribute('gps_altitude', '')
        file.add_string_attribute('gps_latitude', '')
        file.add_string_attribute('gps_longitude', '')
        file.add_string_attribute('iso_speed', '')
        file.add_string_attribute('get_orientation', '')
        file.add_string_attribute('model', '')
        file.add_string_attribute('resolution_unit', '')
        file.add_string_attribute('xresolution', '')
        file.add_string_attribute('yresolution', '')
        file.add_string_attribute('shutter_speed_value', '')
        file.add_string_attribute('aperture_value', '')
        file.add_string_attribute('brightness_value', '')
        file.add_string_attribute('exposure_bias_value', '')
        file.add_string_attribute('max_aperture_value', '')
        file.add_string_attribute('metering_mode', '')
        file.add_string_attribute('light_source', '')
        file.add_string_attribute('flash', '')
        file.add_string_attribute('exposure_mode', '')
        file.add_string_attribute('gain_control', '')
        file.add_string_attribute('width', '')
        file.add_string_attribute('height', '')
        file.add_string_attribute('pages', '')

        if file.get_uri_scheme() != 'file':
            return

        # strip file:// to get absolute path
        filename = urllib.parse.unquote_plus(file.get_uri()[7:])

        # mp3 handling
        if file.is_mime_type('audio/mpeg'):
            # attempt to read ID3 tag
            try:
                audio = EasyID3(filename)
                # sometimes the audio variable will not have one of these items
                # defined, that's why there is this long try / except attempt
                try:
                    if 'title' in audio.keys():
                        file.add_string_attribute('title', audio['title'][0])
                    else:
                        file.add_string_attribute('title', '')
                except Exception:
                    file.add_string_attribute('title', _('Error'))
                try:
                    file.add_string_attribute('album', audio['album'][0])
                except Exception:
                    file.add_string_attribute('album', _('Error'))
                try:
                    file.add_string_attribute('creator', audio['artist'][0])
                except Exception:
                    file.add_string_attribute('creator', _('Error'))
                try:
                    file.add_string_attribute('tracknumber',
                                              audio['tracknumber'][0])
                except Exception:
                    file.add_string_attribute('tracknumber', _('Error'))
                try:
                    file.add_string_attribute('genre', audio['genre'][0])
                except Exception:
                    file.add_string_attribute('genre', _('Error'))
                try:
                    file.add_string_attribute('date', audio['date'][0])
                except Exception:
                    file.add_string_attribute('date', _('Error'))
            except Exception:
                # [SabreWolfy] some files have no ID3 tag and will throw this
                # exception:
                file.add_string_attribute('title', '')
                file.add_string_attribute('description', '')
                file.add_string_attribute('album', '')
                file.add_string_attribute('creator', '')
                file.add_string_attribute('tracknumber', '')
                file.add_string_attribute('genre', '')
                file.add_string_attribute('date', '')
            # try to read MP3 information (bitrate, length, samplerate)
            try:
                mpfile = open(filename)
                mpinfo = MPEGInfo(mpfile)
                file.add_string_attribute('bitrate',
                                          str(mpinfo.bitrate / 1000) + ' Kbps')
                file.add_string_attribute('samplerate',
                                          str(mpinfo.sample_rate) + ' Hz')
                # [SabreWolfy] added consistent formatting of times in format
                # hh:mm:ss
                # [SabreWolfy[ to allow for correct column sorting by length
                mp3length = '%02i:%02i:%02i' % ((int(mpinfo.length / 3600)),
                                                (int(mpinfo.length / 60 % 60)),
                                                (int(mpinfo.length % 60)))
                mpfile.close()
                file.add_string_attribute('length', mp3length)
            except Exception:
                file.add_string_attribute('bitrate', _('Error'))
                file.add_string_attribute('length', _('Error'))
                file.add_string_attribute('samplerate', _('Error'))
                try:
                    mpfile.close()
                except Exception:
                    pass

        # image handling
        if file.get_mime_type().split('/')[0] in ('image'):
            # EXIF handling routines
            try:
                metadata = GExiv2.Metadata(filename)
                try:
                    file.add_string_attribute(
                        'datetime_original',
                        metadata.get_tag_string('Exif.Image.DateTime'))
                except Exception:
                    file.add_string_attribute('datetime_original', '')
                try:
                    file.add_string_attribute(
                        'creator', metadata.get_tag_string('Xmp.dc.creator'))
                except Exception:
                    file.add_string_attribute('creator', '')
                try:
                    file.add_string_attribute(
                        'description',
                        metadata.get_tag_string('Exif.Image.ImageDescription'))
                except Exception:
                    file.add_string_attribute('description', '')
                try:
                    x = str(metadata.get_tag_string('Xmp.dc.title'))
                    file.add_string_attribute('title', x[17:])
                except Exception:
                    file.add_string_attribute('title', '')
                try:
                    file.add_string_attribute('exposure_time',
                                              metadata.get_exposure_time())
                except Exception:
                    file.add_string_attribute('exposure_time', '')
                try:
                    file.add_string_attribute('fnumber',
                                              metadata.get_fnumber())
                except Exception:
                    file.add_string_attribute('fnumber', '')
                try:
                    file.add_string_attribute('focal_length',
                                              metadata.get_focal_length())
                except Exception:
                    file.add_string_attribute('focal_length', '')
                try:
                    file.add_string_attribute('gps_altitude',
                                              metadata.get_gps_altitude())
                except Exception:
                    file.add_string_attribute('gps_altitude', '')
                try:
                    file.add_string_attribute('gps_latitude',
                                              metadata.get_gps_latitude())
                except Exception:
                    file.add_string_attribute('gps_latitude', '')
                try:
                    file.add_string_attribute('gps_longitude',
                                              metadata.get_gps_longitude())
                except Exception:
                    file.add_string_attribute('gps_longitude', '')
                try:
                    file.add_string_attribute('iso_speed',
                                              metadata.get_iso_speed())
                except Exception:
                    file.add_string_attribute('iso_speed', '')
                file.add_string_attribute('orientation',
                                          get_orientation(metadata))
                try:
                    file.add_string_attribute(
                        'model', metadata.get_tag_string('Exif.Image.Model'))
                except Exception:
                    file.add_string_attribute('model', '')
                file.add_string_attribute('resolution_unit',
                                          get_resolution_unit(metadata))
                try:
                    file.add_string_attribute(
                        'xresolution',
                        metadata.get_tag_string('Exif.Image.XResolution'))
                except Exception:
                    file.add_string_attribute('xresolution', '')
                try:
                    file.add_string_attribute(
                        'yresolution',
                        metadata.get_tag_string('Exif.Image.YResolution'))
                except Exception:
                    file.add_string_attribute('yresolution', '')
                try:
                    file.add_string_attribute(
                        'shutter_speed_value',
                        metadata.get_tag_string(
                            'Exif.Photo.ShutterSpeedValue'))
                except Exception:
                    file.add_string_attribute('shutter_speed_value', '')
                try:
                    file.add_string_attribute(
                        'aperture_value',
                        metadata.get_tag_string('Exif.Photo.ApertureValue'))
                except Exception:
                    file.add_string_attribute('aperture_value', '')
                try:
                    file.add_string_attribute(
                        'brightness_value',
                        metadata.get_tag_string('Exif.Photo.BrightnessValue'))
                except Exception:
                    file.add_string_attribute('brightness_value', '')
                try:
                    file.add_string_attribute(
                        'brightness_value',
                        metadata.get_tag_string('Exif.Photo.BrightnessValue'))
                except Exception:
                    file.add_string_attribute('brightness_value', '')
                try:
                    file.add_string_attribute(
                        'exposure_bias_value',
                        metadata.get_tag_string(
                            'Exif.Photo.ExposureBiasValue'))
                except Exception:
                    file.add_string_attribute('exposure_bias_value', '')
                try:
                    file.add_string_attribute(
                        'max_aperture_value',
                        metadata.get_tag_string('Exif.Photo.MaxApertureValue'))
                except Exception:
                    file.add_string_attribute('max_aperture_value', '')
                file.add_string_attribute('metering_mode',
                                          get_metering_mode(metadata))
                file.add_string_attribute('light_source',
                                          get_light_source(metadata))
                file.add_string_attribute('flash', get_flash(metadata))
                file.add_string_attribute('exposure_mode',
                                          get_exposure_mode(metadata))
                file.add_string_attribute('gain_control',
                                          get_gain_control(metadata))
            except Exception:
                file.add_string_attribute('datetime_original', '')
                file.add_string_attribute('creator', '')
                file.add_string_attribute('title', '')
                file.add_string_attribute('description', '')
                file.add_string_attribute('exposure_time', '')
                file.add_string_attribute('fnumber', '')
                file.add_string_attribute('focal_length', '')
                file.add_string_attribute('gps_altitude', '')
                file.add_string_attribute('gps_latitude', '')
                file.add_string_attribute('gps_longitude', '')
                file.add_string_attribute('iso_speed', '')
                file.add_string_attribute('get_orientation', '')
                file.add_string_attribute('model', '')
                file.add_string_attribute('resolution_unit', '')
                file.add_string_attribute('xresolution', '')
                file.add_string_attribute('yresolution', '')
                file.add_string_attribute('shutter_speed_value', '')
                file.add_string_attribute('aperture_value', '')
                file.add_string_attribute('brightness_value', '')
                file.add_string_attribute('exposure_bias_value', '')
                file.add_string_attribute('max_aperture_value', '')
                file.add_string_attribute('metering_mode', '')
                file.add_string_attribute('light_source', '')
                file.add_string_attribute('flash', '')
                file.add_string_attribute('exposure_mode', '')
                file.add_string_attribute('gain_control', '')
            try:
                im = Image.open(filename)
                try:
                    file.add_string_attribute('width', str(im.size[0]))
                except Exception:
                    file.add_string_attribute('width', _('Error'))
                try:
                    file.add_string_attribute('height', str(im.size[1]))
                except Exception:
                    file.add_string_attribute('height', _('Error'))
            except Exception:
                file.add_string_attribute('width', '')
                file.add_string_attribute('height', '')

        # video/flac handling
        if file.is_mime_type('video/x-msvideo') or\
                file.is_mime_type('video/mpeg') or\
                file.is_mime_type('video/x-ms-wmv') or\
                file.is_mime_type('video/mp4') or\
                file.is_mime_type('audio/x-flac') or\
                file.is_mime_type('video/x-flv') or\
                file.is_mime_type('video/x-matroska') or\
                file.is_mime_type('audio/x-wav'):
            metadata = MediaInfo(filename)
            file.add_string_attribute('format', metadata.get_format())
            file.add_string_attribute('duration',
                                      metadata.get_duration_string())
            file.add_string_attribute('overall_bitrate',
                                      metadata.get_overallbitrate())
            file.add_string_attribute('frame_count', metadata.get_framecount())
            file.add_string_attribute('video_format',
                                      metadata.get_videoformat())
            file.add_string_attribute('width', metadata.get_width())
            file.add_string_attribute('height', metadata.get_height())
            file.add_string_attribute('bit_depth', metadata.get_bitdepth())
            file.add_string_attribute('audio_format',
                                      metadata.get_audioformat())
            file.add_string_attribute('title', metadata.get_title())
            file.add_string_attribute('description',
                                      metadata.get_description())
        # pdf handling
        if file.is_mime_type('application/pdf'):
            try:
                f = open(filename, 'rb')
                pdf = PdfFileReader(f)
                info = pdf.getDocumentInfo()
                try:
                    file.add_string_attribute(
                        'title', info.title if info.title is not None else '')
                except Exception:
                    file.add_string_attribute('title', _('Error'))
                try:
                    file.add_string_attribute(
                        'description',
                        info.subject if info.subject is not None else '')
                except Exception:
                    file.add_string_attribute('description', _('Error'))
                try:
                    file.add_string_attribute(
                        'creator',
                        info.author if info.author is not None else '')
                except Exception:
                    file.add_string_attribute('creator', _('Error'))
                try:
                    file.add_string_attribute('pages', str(pdf.getNumPages()))
                except Exception:
                    file.add_string_attribute('pages', _('Error'))
                if pdf.getNumPages() > 0:
                    try:
                        width = abs(
                            pdf.getPage(0).mediaBox.upperRight[0] -
                            pdf.getPage(0).mediaBox.lowerLeft[0])
                        file.add_string_attribute(
                            'width',
                            str(int(float(width) * math.sqrt(2.0) / 4.0)))
                    except Exception:
                        file.add_string_attribute('width', '')
                    try:
                        height = abs(
                            pdf.getPage(0).mediaBox.upperRight[1] -
                            pdf.getPage(0).mediaBox.lowerLeft[1])
                        file.add_string_attribute(
                            'height',
                            str(int(float(height) * math.sqrt(2.0) / 4.0)))
                    except Exception:
                        file.add_string_attribute('height', '')
                else:
                    file.add_string_attribute('width', '')
                    file.add_string_attribute('height', '')
                f.close()
            except Exception:
                file.add_string_attribute('title', _('Error'))
                file.add_string_attribute('description', _('Error'))
                file.add_string_attribute('creator', _('Error'))
                file.add_string_attribute('pages', _('Error'))
                file.add_string_attribute('width', _('Error'))
                file.add_string_attribute('height', _('Error'))
        self.get_columns()
コード例 #15
0
ファイル: bsc_v2.py プロジェクト: mvanaken/nautilus-columns
    def update_file_info(self, file, **kwargs):
        if file.get_uri_scheme() != 'file':
            return

        # Set defaults to blank, else values are showing 'unknown' instead.
        [file.add_string_attribute(column.get('name'), '') for column in COLUMN_DEFINITIONS]

        # strip file:// to get absolute path
        filename = urllib.parse.unquote_plus(file.get_uri()[7:])

        ################
        # mp3 handling #
        ################
        if file.is_mime_type('audio/mpeg'):
            # attempt to read ID3 tag
            try:
                audio = EasyID3(filename)
                map_audio(file, audio, 'title')
                map_audio(file, audio, 'album')
                map_audio(file, audio, 'artist')
                map_audio(file, audio, 'tracknumber')
                map_audio(file, audio, 'genre')
                map_audio(file, audio, 'date')
            except Exception:
                pass

            # try to read MP3 information (bitrate, length, samplerate)
            with open(filename) as mpfile:
                try:
                    mpinfo = MPEGInfo(mpfile)
                    map_any(file, mpinfo, 'bitrate',    f=lambda m: m.bitrate / 1000, c=lambda v: v + ' Kbps')
                    map_any(file, mpinfo, 'samplerate', f=lambda m: m.sample_rate,    c=lambda v: v + ' Hz')
                    map_any(file, mpinfo, 'length',     f=lambda m: m.length,         c=secToTimeFormat)
                except Exception:
                    pass

        ##################
        # image handling #
        ##################
        if file.get_mime_type().split('/')[0] in ('image'):
            try:
                metadata = GExiv2.Metadata(filename)
            except Exception:
                metadata = GExiv2.Metadata()

            map_exif(file, metadata, 'aperture_value', 'Exif.Photo.ApertureValue')
            map_exif(file, metadata, 'artist', 'Exif.Image.Artist')
            map_exif(file, metadata, 'brightness_value', 'Exif.Photo.BrightnessValue')
            map_exif(file, metadata, 'datetime_original', 'Exif.Image.DateTime')
            map_exif(file, metadata, 'exposure_bias_value', 'Exif.Photo.ExposureBiasValue')
            map_exif(file, metadata, 'exposure_mode', 'Exif.Photo.ExposureMode', c=lambda v: convert(EXPOSURE_MODE, v))
            map_exif(file, metadata, 'exposure_time', f=lambda m,t: m.get_exposure_time())
            map_exif(file, metadata, 'flash', 'Exif.Photo.Flash', c=lambda v: convert(FLASH, v))
            map_exif(file, metadata, 'fnumber',       f=lambda m,t: m.get_fnumber())
            map_exif(file, metadata, 'focal_length',  f=lambda m,t: m.get_focal_length())
            map_exif(file, metadata, 'gain_control', 'Exif.Photo.GainControl', c=lambda v: convert(GAIN_CONTROL, v))
            map_exif(file, metadata, 'gps_altitude',  f=lambda m,t: m.get_gps_altitude())
            map_exif(file, metadata, 'gps_latitude',  f=lambda m,t: m.get_gps_latitude())
            map_exif(file, metadata, 'gps_longitude', f=lambda m,t: m.get_gps_longitude())
            map_exif(file, metadata, 'iso_speed',     f=lambda m,t: m.get_iso_speed())
            map_exif(file, metadata, 'light_source', 'Exif.Photo.LightSource', c=lambda v: convert(LIGHT_SOURCE, v))
            map_exif(file, metadata, 'max_aperture_value', 'Exif.Photo.MaxApertureValue')
            map_exif(file, metadata, 'metering_mode', 'Exif.Photo.MeteringMode', c=lambda v: convert(METERING_MODE, v))
            map_exif(file, metadata, 'model', 'Exif.Image.Model')
            map_exif(file, metadata, 'orientation',   f=lambda m,t:m.get_orientation(), c=lambda v: convert(ORIENTATION, v))
            map_exif(file, metadata, 'resolution_unit', 'Exif.Image.ResolutionUnit', c=lambda v: convert(RESOLUTION_UNIT, v))
            map_exif(file, metadata, 'shutter_speed_value', 'Exif.Photo.ShutterSpeedValue')
            map_exif(file, metadata, 'title', 'Exif.Image.ImageDescription')
            map_exif(file, metadata, 'xresolution', 'Exif.Image.XResolution')
            map_exif(file, metadata, 'yresolution', 'Exif.Image.YResolution')

            try:
                im = Image.open(filename)
                map_any(file, im, 'width', f=lambda i: i.size[0])
                map_any(file, im, 'height', f=lambda i: i.size[1])
            except Exception:
                pass

        #######################
        # video/flac handling #
        #######################
        if file.is_mime_type('video/x-msvideo') or\
                file.is_mime_type('video/mpeg') or\
                file.is_mime_type('video/x-ms-wmv') or\
                file.is_mime_type('audio/x-ms-wma') or\
                file.is_mime_type('video/mp4') or\
                file.is_mime_type('audio/x-flac') or\
                file.is_mime_type('video/x-flv') or\
                file.is_mime_type('video/x-matroska') or\
                file.is_mime_type('audio/x-wav'):
            try:
                mediainfo = MediaInfo(filename)
                map_mediainfo(file, mediainfo, 'format', 'Format')
                map_mediainfo(file, mediainfo, 'duration', 'Duration', c=secToTimeFormat)
                map_mediainfo(file, mediainfo, 'overall_bitrate', 'OverallBitRate')
                map_mediainfo(file, mediainfo, 'frame_count', 'FrameCount')
                map_mediainfo(file, mediainfo, 'video_format', 'VideoFormat')
                map_mediainfo(file, mediainfo, 'width', 'Width')
                map_mediainfo(file, mediainfo, 'height', 'Height')
                map_mediainfo(file, mediainfo, 'bit_depth', 'BitDepth')
                map_mediainfo(file, mediainfo, 'audio_format', 'AudioFormat')
            except Exception:
                pass

        ################
        # pdf handling #
        ################
        if file.is_mime_type('application/pdf'):
            try:
                with open(filename, 'rb') as f:
                    pdf = PdfFileReader(f)
                    map_any(file, pdf, 'pages', f=lambda i:i.getNumPages())

                    info = pdf.getDocumentInfo()
                    map_any(file, info, 'title', f=lambda i:i.title)
                    map_any(file, info, 'artist', f=lambda i:i.author)

                    if pdf.getNumPages() > 0:
                        bbox = pdf.getPage(0).mediaBox
                        map_any(file, bbox, 'width', f=lambda b: self.points_from_bbox(b, 0), c=self.points_to_mm)
                        map_any(file, bbox, 'height', f=lambda b: self.points_from_bbox(b, 1), c=self.points_to_mm)
            except Exception:
                pass