Sets the mp3 file metadata using the Python module Mutagen
963493
def set_metadata(track, filename, album=None):
    
    logger.info('Setting tags...')
    global arguments
    artwork_url = track['artwork_url']
    user = track['user']
    if not artwork_url:
        artwork_url = user['avatar_url']
    artwork_url = artwork_url.replace('large', 't500x500')
    response = requests.get(artwork_url, stream=True)
    with tempfile.NamedTemporaryFile() as out_file:
        shutil.copyfileobj(response.raw, out_file)
        out_file.seek(0)

        track_created = track['created_at']
        track_date = datetime.strptime(track_created, "%Y/%m/%d %H:%M:%S %z")
        debug_extract_dates = '{0} {1}'.format(track_created, track_date)
        logger.debug('Extracting date: {0}'.format(debug_extract_dates))
        track['date'] = track_date.strftime("%Y-%m-%d %H::%M::%S")

        track['artist'] = user['username']
        if arguments['--extract-artist']:
            for dash in [' - ', ' − ', ' – ', ' — ', ' ― ']:
                if dash in track['title']:
                    artist_title = track['title'].split(dash)
                    track['artist'] = artist_title[0].strip()
                    track['title'] = artist_title[1].strip()
                    break

        audio = mutagen.File(filename, easy=True)
        audio['title'] = track['title']
        audio['artist'] = track['artist']
        if album: audio['album'] = album
        if track['genre']: audio['genre'] = track['genre']
        if track['permalink_url']: audio['website'] = track['permalink_url']
        if track['date']: audio['date'] = track['date']
        audio.save()

        a = mutagen.File(filename)
        if track['description']:
            if a.__class__ == mutagen.flac.FLAC:
                a['description'] = track['description']
            elif a.__class__ == mutagen.mp3.MP3:
                a['COMM'] = mutagen.id3.COMM(
                    encoding=3, lang=u'ENG', text=track['description']
                )
        if artwork_url:
            if a.__class__ == mutagen.flac.FLAC:
                p = mutagen.flac.Picture()
                p.data = out_file.read()
                p.width = 500
                p.height = 500
                p.type = mutagen.id3.PictureType.COVER_FRONT
                a.add_picture(p)
            elif a.__class__ == mutagen.mp3.MP3:
                a['APIC'] = mutagen.id3.APIC(
                    encoding=3, mime='image/jpeg', type=3,
                    desc='Cover', data=out_file.read()
                )
        a.save()
1201947
def add_metadata(file_name, title, artist, album):
    
    
    tags = EasyMP3(file_name)
    if title: 
        tags["title"] = title
    if artist:     
        tags["artist"] = artist
    if album:
        tags["album"] = album
    tags.save()

    return file_name
549289
def libvlc_audio_set_track(p_mi, i_track):
    '''
    '''
    f = _Cfunctions.get('libvlc_audio_set_track', None) or \
        _Cfunction('libvlc_audio_set_track', ((1,), (1,),), None,
                    ctypes.c_int, MediaPlayer, ctypes.c_int)
    return f(p_mi, i_track)
782734
def do_file_update_metadata(client, args):
    """"""
    client.update_file_metadata(args.uri, filename=args.filename,
                                description=args.description, mtime=args.mtime,
                                privacy=args.privacy)
    return True
334715
def update_metadata(session, path=DATA_PATH):
    """"""
    with open(os.path.join(path, 'games.json')) as handle:
        games = json.loads(handle.read())
     
    for key, data in get_metadata(session, games).items():
        with open(os.path.join(path, '{}.json'.format(key)), 'w') as handle:
           handle.write(json.dumps(data, indent=2))
987465
def _update_media_data(self):
        
        # Use different query URL based on selected source
        if self._input_func in self._netaudio_func_list:
            try:
                root = self.get_status_xml(self._urls.netaudiostatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "szLine":
                    if (self._title != html.unescape(child[1].text) if (
                            child[1].text is not None) else None or
                            self._artist != html.unescape(child[2].text) if (
                                child[2].text is not None) else None or
                            self._album != html.unescape(child[4].text) if (
                                child[4].text is not None) else None):
                        # Refresh cover with a new time stamp for media URL
                        # when track is changing
                        self._image_url = (ALBUM_COVERS_URL.format(
                            host=self._host, port=self._receiver_port,
                            time=int(time.time())))
                        # On track change assume device is PLAYING
                        self._state = STATE_PLAYING
                    self._title = html.unescape(child[1].text) if (
                        child[1].text is not None) else None
                    self._artist = html.unescape(child[2].text) if (
                        child[2].text is not None) else None
                    self._album = html.unescape(child[4].text)if (
                        child[4].text is not None) else None
                    self._band = None
                    self._frequency = None
                    self._station = None

        elif self._input_func == "Tuner" or self._input_func == "TUNER":
            try:
                root = self.get_status_xml(self._urls.tunerstatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "Band":
                    self._band = child[0].text
                elif child.tag == "Frequency":
                    self._frequency = child[0].text

            self._title = None
            self._artist = None
            self._album = None
            self._station = None

            # Assume Tuner is always PLAYING
            self._state = STATE_PLAYING

            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        elif self._input_func == "HD Radio" or self._input_func == "HDRADIO":
            try:
                root = self.get_status_xml(self._urls.hdtunerstatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "Artist":
                    self._artist = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Title":
                    self._title = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Album":
                    self._album = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Band":
                    self._band = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Frequency":
                    self._frequency = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "StationNameSh":
                    self._station = html.unescape(child[0].text) if (
                        child[0].text is not None) else None

            # Assume Tuner is always PLAYING
            self._state = STATE_PLAYING

            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        # No behavior implemented, so reset all variables for that source
        else:
            self._band = None
            self._frequency = None
            self._title = None
            self._artist = None
            self._album = None
            self._station = None
            # Assume PLAYING_DEVICE is always PLAYING
            self._state = STATE_PLAYING
            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        # Test if image URL is accessable
        if self._image_available is None and self._image_url is not None:
            try:
                imgres = requests.get(self._image_url, timeout=self.timeout)
            except requests.exceptions.RequestException:
                # No result set image URL to None
                self._image_url = None
            else:
                if imgres.status_code == 200:
                    self._image_available = True
                else:
                    _LOGGER.info('No album art available for your receiver')
                    # No image available. Save this status.
                    self._image_available = False
                    #  Set image URL to None.
                    self._image_url = None
        # Already tested that image URL is not accessible
        elif self._image_available is False:
            self._image_url = None

        # Finished
        return True
982517
def _add_meta(xs, sample=None, config=None):
    
    out = []
    for x in xs:
        if not isinstance(x["path"], six.string_types) or not os.path.exists(x["path"]):
            raise ValueError("Unexpected path for upload: %s" % x)
        x["mtime"] = shared.get_file_timestamp(x["path"])
        if sample:
            sample_name = dd.get_sample_name(sample)
            if "sample" not in x:
                x["sample"] = sample_name
            elif x["sample"] != sample_name:
                x["run"] = sample_name
        if config:
            fc_name = config.get("fc_name") or "project"
            fc_date = config.get("fc_date") or datetime.datetime.now().strftime("%Y-%m-%d")
            x["run"] = "%s_%s" % (fc_date, fc_name)
        out.append(x)
    return out
1288162
def generate_fileattr_metadata(local_path, metadata):
    # type: (blobxfer.models.upload.LocalPath, dict) -> dict
    
    if blobxfer.util.on_windows():
        global _FILEATTR_WARNED_ON_WINDOWS
        if not _FILEATTR_WARNED_ON_WINDOWS:
            _FILEATTR_WARNED_ON_WINDOWS = True
            logger.warning(
                'file attributes store/restore on Windows is not '
                'supported yet')
        return None
    else:
        md = {
            _JSON_KEY_FILE_ATTRIBUTES: {
                _JSON_KEY_FILE_ATTRIBUTES_POSIX: {
                    _JSON_KEY_FILE_ATTRIBUTES_MODE: local_path.mode,
                    _JSON_KEY_FILE_ATTRIBUTES_UID: local_path.uid,
                    _JSON_KEY_FILE_ATTRIBUTES_GID: local_path.gid,
                }
            }
        }
        return blobxfer.util.merge_dict(metadata, md)
233675
def add_metadata_to_archive(self, metadata, meta_path):
        '''
        
        '''
        archive_path = self.get_full_archive_path(meta_path.lstrip('/'))
        write_data_to_file(metadata, archive_path)
39443
def metadata(self, filename):
        '''
        
        '''
        meta = self.get_metadata(filename)
        # Fix backend mime misdetection
        meta['mime'] = meta.get('mime') or files.mime(filename, self.DEFAULT_MIME)
        return meta
685282
def media(self, uri):
        """"""
        try:
            local_path, _ = urllib.request.urlretrieve(uri)
            metadata = mutagen.File(local_path, easy=True)
            if metadata.tags:
                self._tags = metadata.tags
            title = self._tags.get(TAG_TITLE, [])
            self._manager[ATTR_TITLE] = title[0] if len(title) else ''
            artist = self._tags.get(TAG_ARTIST, [])
            self._manager[ATTR_ARTIST] = artist[0] if len(artist) else ''
            album = self._tags.get(TAG_ALBUM, [])
            self._manager[ATTR_ALBUM] = album[0] if len(album) else ''
            local_uri = 'file://{}'.format(local_path)

        # urllib.error.HTTPError
        except Exception:  # pylint: disable=broad-except
            local_uri = uri
        self._player.set_state(Gst.State.NULL)
        self._player.set_property(PROP_URI, local_uri)
        self._player.set_state(Gst.State.PLAYING)
        self.state = STATE_PLAYING
        self._manager[ATTR_URI] = uri
        self._manager[ATTR_DURATION] = self._duration()
        self._manager[ATTR_VOLUME] = self._player.get_property(PROP_VOLUME)
        _LOGGER.info('playing %s (as %s)', uri, local_uri)
780218
def setMetadata(doc, m):
    """"""
    if doc.isClosed or doc.isEncrypted:
        raise ValueError("operation on closed or encrypted document")
    if type(m) is not dict:
        raise ValueError("arg2 must be a dictionary")
    for k in m.keys():
        if not k in ("author", "producer", "creator", "title", "format",
                     "encryption", "creationDate", "modDate", "subject",
                     "keywords"):
            raise ValueError("invalid dictionary key: " + k)
    d = "<</Author"
    d += getPDFstr(m.get("author", "none"))
    d += "/CreationDate"
    d += getPDFstr(m.get("creationDate", "none"))
    d += "/Creator"
    d += getPDFstr(m.get("creator", "none"))
    d += "/Keywords"
    d += getPDFstr(m.get("keywords", "none"))
    d += "/ModDate"
    d += getPDFstr(m.get("modDate", "none"))
    d += "/Producer"
    d += getPDFstr(m.get("producer", "none"))
    d += "/Subject"
    d += getPDFstr(m.get("subject", "none"))
    d += "/Title"
    d += getPDFstr(m.get("title", "none"))
    d += ">>"
    doc._setMetadata(d)
    doc.initData()
    return
618395
def get_and_update_package_metadata():
    
    global setup_arguments
    global METADATA_FILENAME

    if not os.path.exists('.git') and os.path.exists(METADATA_FILENAME):
        with open(METADATA_FILENAME) as fh:
            metadata = json.load(fh)
    else:
        git = Git(version=setup_arguments['version'])
        metadata = {
            'version': git.version,
            'long_description': 'Tool to pip install missing imports and more',
            'git_hash': git.hash,
            'git_origin': git.origin,
            'git_branch': git.branch
        }
        for readme_file in ['README.rst', 'README.md', 'README.txt']:
            if os.path.exists(readme_file):
                with open(readme_file) as file_handle:
                    metadata['long_description'] = file_handle.read()
                break
        with open(METADATA_FILENAME, 'w') as fh:
            json.dump(metadata, fh)
    return metadata
275976
def suggest_filename(metadata):
	

	if 'title' in metadata and 'track_number' in metadata:  # Music Manager.
		suggested_filename = f"{metadata['track_number']:0>2} {metadata['title']}"
	elif 'title' in metadata and 'trackNumber' in metadata:  # Mobile.
		suggested_filename = f"{metadata['trackNumber']:0>2} {metadata['title']}"
	elif 'title' in metadata and 'tracknumber' in metadata:  # audio-metadata/mutagen.
		track_number = _split_number_field(
			list_to_single_value(
				metadata['tracknumber']
			)
		)
		title = list_to_single_value(metadata['title'])

		suggested_filename = f"{track_number:0>2} {title}"
	else:
		suggested_filename = f"00 {list_to_single_value(metadata.get('title', ['']))}"

	return _replace_invalid_characters(suggested_filename)
68857
def add_metadata_defaults(md):
    
    defaults = {"batch": None,
                "phenotype": ""}
    for k, v in defaults.items():
        if k not in md:
            md[k] = v
    return md
1010283
def save(self):
        
        # Possibly save the tags to ID3v2.3.
        kwargs = {}
        if self.id3v23:
            id3 = self.mgfile
            if hasattr(id3, 'tags'):
                # In case this is an MP3 object, not an ID3 object.
                id3 = id3.tags
            id3.update_to_v23()
            kwargs['v2_version'] = 3

        mutagen_call('save', self.path, self.mgfile.save, **kwargs)
880503
def set_metadata(self, queue, metadata, clear=False):
        
        return self._manager.set_metadata(queue, metadata, clear=clear)