Ejemplo n.º 1
0
 def post(self, account, account_id):
     if account.account_id != account_id:
         return {
             "status": "failed",
             "message": get_request_message(request, "UNAUTHORIZED")
         }, 401
     results = []
     for file_data in request.files:
         file = request.files[file_data]
         if file and allowed_file(file.filename):
             filename = secure_filename(file.filename).replace("_", " ")
             new_filename = hashlib.sha1(
                 (filename + str(datetime.datetime.now().timestamp())
                  ).encode()).hexdigest() + "." + file.filename.rsplit(
                      '.', 1)[1].lower()
             file.save(os.path.join(ACCOUNT_SONGS_DIRECTORY, new_filename))
             audio_file_metadata = audio_metadata.load(
                 ACCOUNT_SONGS_DIRECTORY + "/" + new_filename)
             new_account_song = AccountSong(
                 account_id, filename,
                 strftime("%M:%S",
                          gmtime(audio_file_metadata.streaminfo.duration)),
                 new_filename,
                 datetime.datetime.today().strftime("%Y-%m-%d"))
             database.session.add(new_account_song)
             database.session.commit()
             result = account_song_schema.dump(new_account_song).data
             results.append(result)
     if not results:
         return {
             "status": "failed",
             "message": get_request_message(request, "NO_FILES_SELECTED")
         }, 400
     return {"status": "success", "data": results}, 201
Ejemplo n.º 2
0
def generate_client_id(song):
    if not isinstance(song, audio_metadata.Format):
        song = audio_metadata.load(song)

    md5sum = None
    if isinstance(song, audio_metadata.FLAC):
        md5sum = unhexlify(song.streaminfo.md5)
    else:
        m = md5()

        audio_size = song.streaminfo._size
        with open(song.filepath, 'rb') as f:
            f.seek(song.streaminfo._start)

            # Speed up by reading in chunks
            read = 0
            while True:
                read_size = min(audio_size - read, 65536)
                if not read_size:
                    break

                read += read_size
                data = f.read(read_size)
                m.update(data)

        md5sum = m.digest()

    client_id = b64encode(md5sum).rstrip(b'=').decode('ascii')

    return client_id
Ejemplo n.º 3
0
 def supportedFormat(self, inFilename, outFilename):
     metadata = audio_metadata.load(inFilename)
     if metadata.streaminfo.duration <= MIDIView.maxDuration:
         self.correctDuration(inFilename, metadata, outFilename)
     else:
         raise ValueError(
             f"File exceeds maximum duration, {MIDIView.maxDuration}")
Ejemplo n.º 4
0
def meta_test(path):
    am = audio_metadata.load(path)
    print('path: ' + path.replace('media/', '') + ' | name: ' +
          am.tags.get('title')[0])
    db = DB_Song_Interface
    db.create_single_song(db,
                          am.tags.get('title')[0], path.replace('media/', ''))
def read_metadata(path):
    """
    :param path: path object, e.g. os.path.expanduser('~/Music/Lieder_HighResolutionAudio')
    :return: [{"success": , "name": , "artist": , "path:"}, {...}
    """
    parsed_songs = []
    for filepath in pathlib.Path(path).glob('**/*'):
        if filepath.is_file():
            try:
                filepath = filepath.absolute()
                metadata = audio_metadata.load(filepath)
                song_info = {
                    "success": True,
                    "name": metadata["tags"]["title"][0],
                    "artist": metadata["tags"]["artist"][0],
                    "path": filepath
                }
                # print(metadata["tags"]["genre"])
            except KeyError:
                print("no Metadata found for song:", filepath)
                songinfo = {"success": False, "path": filepath}

            parsed_songs.append(song_info)

    print(parsed_songs)
    return parsed_songs
Ejemplo n.º 6
0
def get_files(path):
    """Get files from a specified path.
    
    """
    # Get all files in the path
    filelist = os.listdir(path)

    # Filter file types
    filelist = [
        file for file in filelist if file.endswith(('.mp3', '.wav', '.ogg'))
    ]

    # Create files object
    files = []
    for filename in filelist:
        metadata = audio_metadata.load(os.path.join(path, filename))
        files.append({
            "name":
            filename,
            "size":
            "{:02}".format(round(metadata.filesize / 1048576, 2)),
            "duration":
            sec2min(metadata.streaminfo.duration),
            "metadata":
            metadata,
        })

    return files
Ejemplo n.º 7
0
def readMusic(file_path):
    """Guarda en un diccionario toda la informacion del archivo,
    lo agrega al archivo pickle de musica  """

    for file in readTags("music"):
        if file["file_name"] == file_path:  # Se determina si el archivo ya es existente
            return None
    #
    tags = {"file_name": file_path, "album": ["Unknown"], "artist": ["Unknown"], "date": ["Unknown"],
            "title": [file_path], "genre": ["Unknown"]}  # Diccionario con la informacion a guardar

    song_data = audio_metadata.load(file_path)  # Carga metadata de la musica con la funcion audio_metadata.load

    keys = [x for x in song_data.tags]
    values = [x for x in song_data.tags.values()]
    meta_data = dict(zip(keys, values))  # Lo convierte en diccionario para facilitar su manejo

    for x in tags.keys():
        if x in meta_data:
            tags[x] = meta_data[x]  # Guarda solo la metadata que nos interesa

    saveTags(modify(tags), 'music')

    allSongs = readTags('music')
    print("Se añadio recientemente: ")
    print("--------------------------------------------")
    print("--------------------------------------------")
    for x in allSongs[2:0:-1]:  # Se muestra la musica añadida recientemente
        print("Name: ", x["title"], sep="  ")
        print("Data:")
        print(x["artist"], x["album"], x["date"], sep="\n")
        print("--------------------------------------------")
        print("--------------------------------------------")
Ejemplo n.º 8
0
def partition(files):
    '''
    groups files based on metadata and returns the groupings
    '''
    partitions = {}
    for file in files:
        besttag = "UnknownType"
        try:
            meta = audio_metadata.load(file)
            tags = meta["tags"]
            #print(tags)
            key = None
            if ("album" in tags): key = "album"
            elif ("artist" in tags): key = "artist"
            elif ("genre" in tags): key = "genre"
            besttag = tags[key][0] if key is not None else "Unknown"
        except:
            pass

        #file-friendly
        besttag = slugify(besttag)

        partitions[besttag] = partitions[besttag] + [
            file
        ] if besttag in partitions else [file]

    return partitions
Ejemplo n.º 9
0
 def generate(self, ctx, dirpath, filename, filepath):
     try:
         amd = audio_metadata.load(filepath)
         if not hasattr(amd, 'tags'):
             raise AttributeException("attribute tags missing")
         if not hasattr(amd.tags, 'artist'):
             raise AttributeException("attribute artist missing")
         if not hasattr(amd.tags, 'title'):
             raise AttributeException("attribute title missing")
         new_filename = ('-'.join(amd.tags.artist) + '_' + '-'.join(amd.tags.title)).strip() + os.path.splitext(filename)[1]
         new_filename = clean_windows_filename(new_filename)
         line = new_filename + ' | ' + filepath + '\n'
         ctx.ofs.write(line)
         dest_filepath = os.path.join(ctx.destpath, new_filename)
         if os.path.exists(dest_filepath):
             if os.stat(filepath).st_size <= os.stat(dest_filepath).st_size:
                 return
         shutil.copyfile(filepath, dest_filepath)
     except audio_metadata.AudioMetadataException as e:
         self.error(filepath, e)
     except ValueError as e:
         self.error(filepath, e)
     except AttributeException as e:
         self.error(filepath, e)
     except OSError as e:
         self.error(filepath, e)
     except Exception as e:
         self.error(filepath, e)
     except:
         self.error(filepath, traceback.format_exc())
Ejemplo n.º 10
0
 def handler(self, data, addr):
     print(f"Inbound request from {addr[0]} on UDP port {addr[1]}")
     song = random.choice(self.music)
     m = am.load(f"/home/monster/music/{song}")
     title = f'TITLE({m["tags"]["artist"][0]} - {m["tags"]["title"][0]})'
     try:
         self.socket.sendto(title.encode(), (addr[0], addr[1]))
     except (socket.error, socket.timeout, OSError) as error:
         print(error)
         return False
     with open(f"/home/monster/music/{song}", "rb") as f:
         while True:
             data = f.read(20000)
             if not data:
                 print("Done with stream")
                 try:
                     self.socket.sendto(data, (addr[0], addr[1]))
                     self.socket.sendto(b"DONE", (addr[0], addr[1]))
                 except (socket.error, socket.timeout) as error:
                     return False
                 break
             try:
                 self.socket.sendto(data, (addr[0], addr[1]))
             except (socket.error, socket.timeout) as error:
                 print(error)
                 self.socket.close()
                 return error
     f.close()
     return True
Ejemplo n.º 11
0
def get_album_art(song):
    if not isinstance(song, audio_metadata.Format):
        song = audio_metadata.load(song)

    album_art = next(
        (picture.data for picture in song.pictures if picture.type == 3), None)

    return album_art
Ejemplo n.º 12
0
def extractor(audio, output, file):
    album_art_dir = '{}/album-art'.format(output)
    music_info = []
    id = 0

    if os.path.exists(album_art_dir):
        pass
    else:
        os.makedirs(album_art_dir)
    for music in glob.glob("{}/*.flac".format(audio)):
        tmp_music = {
            "id": "",
            "title": "",
            "album": "",
            "artist": "",
            "genre": "",
            "date": "",
            "filepath": "",
            "filesize": "",
            "albumart": ""
        }
        file_ = os.path.join(audio, music)
        meta_data = audio_metadata.load(file_)
        img = meta_data["pictures"]
        for pic in img:
            if pic.type == 3:
                album_art_path = os.path.join(album_art_dir, f"{str(id)}.jpg")
                with open(album_art_path, 'wb') as f:
                    f.write(pic.data)

        tmp_music["id"] = str(id)
        tmp_music["title"] = meta_data["tags"]["title"][0] if meta_data[
            "tags"].get("title") else "Track {}".format(id)
        tmp_music["album"] = meta_data["tags"]["album"][0] if meta_data[
            "tags"].get("album") else "Unknown"
        tmp_music["artist"] = meta_data["tags"]["artist"][0] if meta_data[
            "tags"].get("artist") else "Unknown"
        tmp_music["genre"] = meta_data["tags"]["genre"][0] if meta_data[
            "tags"].get("genre") else "Unknown"
        tmp_music["date"] = meta_data["tags"]["date"][0] if meta_data[
            "tags"].get("date") else "Unknown"
        tmp_music["filepath"] = meta_data["filepath"] if meta_data.get(
            "filepath") else "Unknown"
        tmp_music["filesize"] = meta_data["filesize"] if meta_data.get(
            "filesize") else "Unknown"
        try:
            tmp_music["albumart"] = album_art_path
        except KeyError:
            tmp_music["albumart"] = "Unknown"

        music_info.append(tmp_music)
        id += 1

    print(music_info)
    with open(f'{output}/{file}.json', "w") as outFile:
        json.dump(music_info, outFile)
        print("file saved as {}.json...".format(file))
        outFile.close()
Ejemplo n.º 13
0
def sample_recognize(filename):
    """
    Transcribe a short audio file using synchronous speech recognition
    Args:
      local_file_path Path to local audio file, e.g. /path/audio.wav
    """

    if (filename.endswith(".MOV")):  #or .avi, .mpeg, whatever.
        mp3_filename = filename[:-4] + ".mp3"
        flac_filename = filename[:-4] + ".flac"
        monoFlac_filename = "mono" + flac_filename

        #subprocess.call(['ffmpeg', '-i', filename, mp3_filename])
        #subprocess.call(['ffmpeg', '-i', mp3_filename, '-f', 'flac', flac_filename])
        #subprocess.call(['ffmpeg', '-i', flac_filename, '-ac', '1', monoFlac_filename])

        os.system("ffmpeg -i " + filename + " " + mp3_filename +
                  " &> /dev/null")
        os.system("ffmpeg -i " + mp3_filename + " -f flac " + flac_filename +
                  " &> /dev/null")
        os.system("ffmpeg -i " + flac_filename + " -ac 1 " +
                  monoFlac_filename + " &> /dev/null")
    else:
        pass

    if (filename.endswith(".flac") and filename[0:4] == "mono"):
        metadata = audio_metadata.load(filename)
        sample_frequency = metadata['streaminfo']['sample_rate']
    else:
        sample_frequency = 44100

    client = speech_v1.SpeechClient()

    # The language of the supplied audio
    language_code = "en-US"

    # Sample rate in Hertz of the audio data sent
    sample_rate_hertz = sample_frequency

    # Encoding of audio data sent. This sample sets this explicitly.
    # This field is optional for FLAC and WAV audio formats.
    #encoding = enums.RecognitionConfig.AudioEncoding.MP3
    config = {
        "language_code": language_code,
        "sample_rate_hertz": sample_rate_hertz,
        "encoding": "FLAC",
    }
    with io.open(monoFlac_filename, "rb") as f:
        content = f.read()
    audio = {"content": content}

    response = client.recognize(config, audio)
    for result in response.results:
        # First alternative is the most probable result
        alternative = result.alternatives[0]

        return "{}".format(alternative.transcript)
Ejemplo n.º 14
0
def albumInfo(mfile):
    #get file path and album\title\artist info into single dict format
    vdext = ['.flac','.mp3','.wav','.wma','.m4a']
    ext = mfile[mfile.rfind('.'):]#file extension
    if ext in vdext:
        alinfo = {
            'path':None,
            'pic':None,
            'title':None,
            'album':None,
            'artist':None
        }
        if ext == '.wma' or ext == '.m4a':
            fa = mutagen.File(mfile)
            if ext == '.wma':
                alinfo['path'] = mfile
                if 'Title' in fa:
                    alinfo['title'] = str(fa['Title'][0])
                if 'WM/AlbumTitle' in fa:
                    alinfo['album'] = str(fa['WM/AlbumTitle'][0])
                if 'WM/AlbumArtist' in fa:
                    alinfo['artist'] = str(fa['WM/AlbumArtist'][0])
                pass
            else:
                alinfo['path'] = mfile
                if '©ART' in fa:
                    alinfo['artist'] = fa['©ART'][0]
                if '©nam' in fa:
                    alinfo['title'] = fa['©nam'][0]
                if '©alb' in fa:
                    alinfo['album'] = fa['©alb'][0]
                #'covr' is album art
                pass
        else:
            try:
                fa = audio_metadata.load(mfile)
                if 'filepath' in fa:
                    alinfo['path'] = fa['filepath']
                else:
                    alinfo['path'] = mfile
                if 'pictures' in fa:
                    if len(fa['pictures'])>0:
                         alinfo['pic'] = fa['pictures']
                tgs = fa['tags']
                #print(tgs)
                if 'title' in tgs:
                    alinfo['title'] = tgs['title'][0]
                if 'album' in tgs:
                    alinfo['album'] = tgs['album'][0]
                if 'artist' in tgs:
                    alinfo['artist'] = tgs['artist'][0]
            except:
                print(sys.exc_info())
                return None
        return alinfo
    else:
        return None
Ejemplo n.º 15
0
def add_genre_to_dataset(genreID, genreFilesPath, copy=True):
    genre_id, genre = _create_Raga_ID_ditionary()
    files_list = librosa.util.find_files(
        platform_details.get_platform_path(genreFilesPath))
    artists = []
    fileIDs = []
    for i in range(len(files_list)):
        meta = audio_metadata.load(files_list[i])
        if meta['tags'].__contains__('artist'):
            artist = meta['tags'].artist
        else:
            artist = ''
        artists.append(artist)
        fileIDs.append(
            str(genreID).zfill(3) + str(0).zfill(3) + str(i + 1).zfill(3))
    if genre.keys().__contains__(genreID):
        gen = genre[genreID]
    else:
        try:
            meta = audio_metadata.load(files_list[0])
            gen = meta['tags'].genre
        except:
            raise Exception("Add genre name to the 'v4_genre_ids' first")

    ### assigning artist ID := 0 for now, will edit the code later
    ### TODO: add get_artist() and get_artist_id()
    metadata_path = os.path.join(copy_base, 'metadata.csv')

    if copy:
        with open(metadata_path, 'a', encoding='utf8') as f:
            for i in range(len(files_list)):
                copy_dest = os.path.join(copy_base, fileIDs[i])
                try:
                    os.mkdir(copy_dest)
                except:
                    pass
                new_path = shutil.copy2(files_list[i], copy_dest)
                new_path = new_path.strip(copy_base)
                f.write(
                    f"{new_path},{artists[i]},{gen},{gen.lower()},{fileIDs[i]}\n"
                )
                print(f"file {i + 1} of {len(files_list)} copied!!")
 def store_song_file(self, file):
     filename = secure_filename(file.filename).replace("_", " ")
     new_filename = hashlib.sha1(
         (filename + str(datetime.datetime.now().timestamp())).encode()
     ).hexdigest() + "." + file.filename.rsplit('.', 1)[1].lower()
     file.save(os.path.join(SONGS_DIRECTORY, new_filename))
     audio_file_metadata = audio_metadata.load(SONGS_DIRECTORY + "/" + new_filename)
     return { 
         "name": new_filename,
         "duration": strftime("%M:%S", gmtime(audio_file_metadata.streaminfo.duration))
     }
Ejemplo n.º 17
0
def generate_client_id(song):
	def _hash_data(m, f, audio_size):
		# Speed up by reading in chunks
		read = 0
		read_size = min(audio_size - read, 65536)
		while read_size > 0:
			data = f.read(read_size)
			m.update(data)

			read += read_size
			read_size = min(audio_size - read, 65536)

		return m.digest()

	if not isinstance(song, audio_metadata.Format):  # pragma: nobranch
		song = audio_metadata.load(song)

	md5sum = None
	if isinstance(song, audio_metadata.FLAC):
		md5sum = unhexlify(song.streaminfo.md5)
	else:
		m = md5()
		if isinstance(song, audio_metadata.MP3):
			if '_id3' in song and isinstance(song._id3, audio_metadata.ID3v2):
				audio_start = song._id3._size
			else:
				audio_start = 0

			audio_size = song.streaminfo._end - audio_start
			with open(song.filepath, 'rb') as f:
				f.seek(audio_start, os.SEEK_SET)
				md5sum = _hash_data(m, f, audio_size)
		elif isinstance(song, audio_metadata.OggVorbis):
			f = DataReader(song.filepath)
			f.seek(song.streaminfo._start)

			while True:
				page = audio_metadata.OggPage.parse(f)
				if page.position:
					break

			audio_start = f.tell()
			audio_size = song.streaminfo._size
			md5sum = _hash_data(m, f, audio_size)
		else:
			audio_size = song.streaminfo._size
			with open(song.filepath, 'rb') as f:
				f.seek(song.streaminfo._start)
				md5sum = _hash_data(m, f, audio_size)

	client_id = b64encode(md5sum).rstrip(b'=').decode('ascii')

	return client_id
Ejemplo n.º 18
0
def get_item_tags(item):
    if isinstance(item, (str, os.PathLike)):
        try:
            tags = audio_metadata.load(item).tags
        except AudioMetadataException:
            tags = None
    elif isinstance(item, audio_metadata.Format):
        tags = item.tags
    else:
        tags = item

    return tags
Ejemplo n.º 19
0
    def __attrs_post_init__(self):
        super().__attrs_post_init__()

        inlined = {
            'title': 'jumper-uploader-title-42',
            'ClientId': self.track.client_id,
            'ClientTotalSongCount': str(self.total_song_count),
            'CurrentTotalUploadedCount': str(self.total_uploaded_count),
            'CurrentUploadingTrackArtist': self.track.artist,
            'CurrentUploadingTrack': self.track.title,
            'ServerId': self.server_track_id,
            'SyncNow': 'true',
            'TrackBitRate': str(self.track.original_bit_rate),
            'TrackDoNotRematch': 'false',
            'UploaderId': self.uploader_id,
        }

        if not isinstance(self.song, audio_metadata.Format):
            self.song = audio_metadata.load(self.song)

        album_art = self.external_art or get_album_art(self.song)

        if album_art:
            inlined['AlbumArt'] = b64encode(album_art).decode()

        self._data.update({
            'clientId': 'Jumper Uploader',
            'createSessionRequest': {
                'fields': [{
                    'external': {
                        'filename': os.path.basename(self.song.filepath),
                        'name': os.path.abspath(self.song.filepath),
                        'put': {},
                        # Size seems to be sent when uploading MP3, but not FLAC.
                        # In fact, uploading FLAC directly fails when this is given.
                        # Leaving it out works for everything.
                        # 'size': self.track.estimated_size
                    }
                }]
            },
            'protocolVersion': '0.8',
        })

        for field, value in inlined.items():
            self._data['createSessionRequest']['fields'].append(
                {'inlined': {
                    'content': value,
                    'name': field,
                }})

        self._url = ScottyAgentPost.base_url
Ejemplo n.º 20
0
    def Mostrar_info(self, info):
        filename = filedialog.askopenfilename(filetypes=[('WAV Files',
                                                          '*.wav')])
        self.archivo = list(filename)
        wav = ''.join(self.archivo)
        propiedades = audio_metadata.load(wav)

        Ruta1 = "Ruta: " + str(propiedades["filepath"])
        Ruta = self.formato(Ruta1)
        AudioFormat = "AudioFormat: " + str(
            propiedades["streaminfo"]['audio_format'])
        Bit_depth = "Bit_depth: " + str(propiedades["streaminfo"]['bit_depth'])
        Sample_rate = "Sample_rate: " + str(
            propiedades["streaminfo"]['sample_rate'])

        self.informacion = Ruta + '\n' + AudioFormat + '\n' + Bit_depth + '\n' + Sample_rate
        info.config(text=self.informacion)
Ejemplo n.º 21
0
    def load_songs(self):
        song_metadata = []
        try:
            for filename in os.listdir(self.path):
                _, extension = os.path.splitext(filename)
                if extension in self.supported_extensions:
                    try:
                        metadata = audio_metadata.load(
                            f"{self.path}/{filename}")
                        song_metadata.append(metadata)
                    except audio_metadata.exceptions.UnsupportedFormat:
                        print(f"Filerror opening {filename}")
                    except PermissionError:
                        print("Denied access")
        except PermissionError:
            print("Denied access")
        except Exception as e:
            print("Unknown exception while opening the folder. ", str(e))

        self.song_metadata = song_metadata
Ejemplo n.º 22
0
def collect_file_meta_data(file_name, parent_id=-1):
    '''
    takes in a audio file and computes necesary metadata

    Parameters
    ----------
    file_name : String
        path to the specified file
    parent_id : INT, optional
        This should be genreated in previous steps/known. The default is -1 showing an error.

    Returns
    -------
    file_id : INT
    parent_id : INT
    size_bytes : FLOAT
    file_duration : FLOAT
    checksum : FLOAT
    blob_storage_url : STRING
        Location of file in Blob
    sample_rate : FLOAT

    '''

    file_id = get_unique_id()
    file_extension = os.path.splitext(file_name)
    blob_storage_url = str(
        str(parent_id) + "/" + str(file_id) + file_extension[1])

    # Using the audio_metadata import
    metadata = audio_metadata.load(file_name)

    # Store indiviual file data into dataframe
    size_bytes = metadata['filesize']
    bitrate = metadata['streaminfo'].bitrate
    file_duration = metadata['streaminfo'].duration
    sample_rate = metadata['streaminfo'].sample_rate
    checksum = ""  #metadata['streaminfo'].md5

    return (file_id, parent_id, size_bytes, file_duration, checksum,
            blob_storage_url, sample_rate)
Ejemplo n.º 23
0
def get_album_art(song):
	if not isinstance(song, audio_metadata.Format):  # pragma: nobranch
		song = audio_metadata.load(song)

	# Google's Music manager uses this album art selection algorithm:
	# * If picture(s) of type 'front cover' are found, use the first one of those in the list.
	# * If picture(s) of type 'other' are found, use the first one of those in the list.
	# * If picture(s) of type 'back cover' are found, use the first one of those in the list.
	for picture_type in [3, 0, 4]:
		album_art = next(
			(
				picture.data
				for picture in song.pictures
				if picture.type == picture_type
			),
			None
		)

		if album_art is not None:
			break

	return album_art
Ejemplo n.º 24
0
def get_meta(music):
    try:
        metadata = audio_metadata.load(music)
    except Exception as e:
        print(e)
    duration = None
    artist = None
    title = None
    try:
        artist = str(metadata['tags']['artist'][0])
    except:
        pass
    try:
        title = str(metadata['tags']['title'][0])
    except:
        pass
    try:
        duration = str(metadata['streaminfo']['duration'])
    except:
        pass
    print(artist, duration, title)
    return {"artist": artist, "duration": duration, "title": title}
Ejemplo n.º 25
0
def zAudio(audioFile):
    zCh = audio_metadata.load(audioFile)
    print(zCh)
Ejemplo n.º 26
0
def fileSaver(audio, audioFileType, audioFileId):
    file_name = audio.filename
    file_duration = 0
    host, paticipant, title, author, narrator = '', '', '', '', ''

    file_path = os.path.join(app.config['UPLOAD_FOLDER'],
                             secure_filename(file_name))
    audio.save(file_path)
    metadata = audio_metadata.load(file_path)
    print(metadata)
    if 'streaminfo' in metadata:
        streaminfo = metadata['streaminfo']
        if 'duration' in streaminfo:
            file_duration = streaminfo['duration']

    if "tags" in metadata:
        tags = metadata['tags']
        if "title" in tags:
            title = str(tags["title"])
        if "albumartist" in tags:
            author = str(tags["albumartist"])
        if "artist" in tags:
            narrator = str(tags["artist"])
    ''' Here implement code for get metaData of Podcast
        but currently this type of files is not available (you can provide.)
        so i have used defalut(empty) values. thanks'''

    if audioFileType == "Song":
        if audioFileId:
            update_song = Song.query.filter_by(id=audioFileId).first()
            if file_name:
                update_song.name = file_name
            if file_duration > 0:
                update_song.duration = file_duration
            db.session.commit()
        else:
            song = Song(name=file_name, duration=file_duration)
            db.session.add(song)
            db.session.commit()
    elif audioFileType == "Podcast":
        if audioFileId:
            update_podcast = Podcast.query.filter_by(id=audioFileId).first()
            if file_name:
                update_podcast.name = file_name
            if file_duration > 0:
                update_podcast.duration = file_duration
            if host != '':
                update_podcast.host = host
            if file_name != '':
                update_podcast.paticipant = paticipant
            db.session.commit()
        else:
            podcast = Podcast(name=file_name,
                              duration=file_duration,
                              host=host,
                              paticipant=paticipant)
            db.session.add(podcast)
            db.session.commit()
    elif audioFileType == "Audiobook":
        if audioFileId:
            update_audiobook = Audiobook.query.filter_by(
                id=audioFileId).first()
            if file_name:
                update_audiobook.title = title
            if file_duration > 0:
                update_audiobook.duration = file_duration
            if host != '':
                update_audiobook.author = author
            if file_name != '':
                update_audiobook.narrator = narrator
            db.session.commit()
        else:
            audiobook = Audiobook(title=title,
                                  duration=file_duration,
                                  author=author,
                                  narrator=narrator)
            db.session.add(audiobook)
            db.session.commit()
Ejemplo n.º 27
0
def getMetadata(fileName):
    try:
        metadata = audio_metadata.load(fileName)
    except audio_metadata.exceptions.UnsupportedFormat:
        return None
    return metadata
Ejemplo n.º 28
0
    def upload(self, song, *, album_art_path=None, no_sample=False):
        """Upload a song to a Google Music library.

		Parameters:
			song (os.PathLike or str or audio_metadata.Format):
				The path to an audio file or
				an instance of :class:`audio_metadata.Format`.
			album_art_path (os.PathLike or str, Optional):
				The relative filename or absolute filepath to external album art.
			no_sample(bool, Optional):
				Don't generate an audio sample from song;
				send empty audio sample.
				Default: Create an audio sample using ffmpeg/avconv.

		Returns:
			dict: A result dict with keys: ``'filepath'``, ``'success'``, ``'reason'``, and ``'song_id'`` (if successful).
		"""

        if not isinstance(song, audio_metadata.Format):
            try:
                song = audio_metadata.load(song)
            except audio_metadata.UnsupportedFormat:
                raise ValueError("'song' must be FLAC, MP3, or WAV.")

        if album_art_path:
            album_art_path = Path(album_art_path).resolve()

            if album_art_path.is_file():
                with album_art_path.open('rb') as image_file:
                    external_art = image_file.read()
            else:
                external_art = None
        else:
            external_art = None

        result = {'filepath': Path(song.filepath)}

        track_info = mm_calls.Metadata.get_track_info(song)
        response = self._call(mm_calls.Metadata, self.uploader_id,
                              [track_info])

        metadata_response = response.body.metadata_response

        if metadata_response.signed_challenge_info:  # Sample requested.
            sample_request = metadata_response.signed_challenge_info[0]

            try:
                track_sample = mm_calls.Sample.generate_sample(
                    song,
                    track_info,
                    sample_request,
                    external_art=external_art,
                    no_sample=no_sample,
                )
                response = self._call(mm_calls.Sample, self.uploader_id,
                                      [track_sample])
                track_sample_response = response.body.sample_response.track_sample_response[
                    0]
            except (OSError, ValueError, subprocess.CalledProcessError):
                raise  # TODO
        else:
            track_sample_response = metadata_response.track_sample_response[0]

        response_code = track_sample_response.response_code

        if response_code == upload_pb2.TrackSampleResponse.MATCHED:
            result.update({
                'success': True,
                'reason': 'Matched',
                'song_id': track_sample_response.server_track_id,
            })
        elif response_code == upload_pb2.TrackSampleResponse.UPLOAD_REQUESTED:
            server_track_id = track_sample_response.server_track_id

            self._call(mm_calls.UploadState, self.uploader_id, 'START')

            attempts = 0
            should_retry = True

            while should_retry and attempts <= 10:
                try:
                    # Call with tenacity.retry_with to disable automatic retries.
                    response = self._call.retry_with(
                        stop=stop_after_attempt(1))(
                            self,
                            mm_calls.ScottyAgentPost,
                            self.uploader_id,
                            server_track_id,
                            track_info,
                            song,
                            external_art=external_art,
                            total_song_count=1,
                            total_uploaded_count=0,
                        )
                except requests.RequestException as e:
                    should_retry = True
                    reason = e.response
                else:
                    session_response = response.body

                    if 'sessionStatus' in session_response:
                        break

                    try:
                        # WHY, GOOGLE?! WHY???????????
                        status_code = session_response['errorMessage'][
                            'additionalInfo'][
                                'uploader_service.GoogleRupioAdditionalInfo'][
                                    'completionInfo']['customerSpecificInfo'][
                                        'ResponseCode']
                    except KeyError:
                        status_code = None

                    if status_code == 503:  # Upload server still syncing.
                        should_retry = True
                        reason = "Server syncing"
                    elif status_code == 200:  # Song is already uploaded.
                        should_retry = False
                        reason = "Already uploaded"
                    elif status_code == 404:  # Rejected.
                        should_retry = False
                        reason = "Rejected"
                    else:
                        should_retry = True
                        reason = "Unkown error"
                finally:
                    attempts += 1
                    time.sleep(2)  # Give the server time to sync.
            else:
                result.update({
                    'success':
                    False,
                    'reason':
                    f'Could not get upload session: {reason}',
                })

            if 'success' not in result:
                transfer = session_response['sessionStatus'][
                    'externalFieldTransfers'][0]

                upload_url = transfer['putInfo']['url']
                content_type = transfer.get('content_type', 'audio/mpeg')
                original_content_type = track_info.original_content_type

                transcode = (isinstance(song, audio_metadata.WAV)
                             or original_content_type != locker_pb2.Track.MP3)

                if (transcode
                        or original_content_type == locker_pb2.Track.MP3):
                    if transcode:
                        audio_file = transcode_to_mp3(song, quality='320k')
                    else:
                        with open(song.filepath, 'rb') as f:
                            audio_file = f.read()

                    # Google Music allows a maximum file size of 300 MiB.
                    if len(audio_file) >= 300 * 1024 * 1024:
                        result.update({
                            'success':
                            False,
                            'reason':
                            'Maximum allowed file size is 300 MiB.',
                        })
                    else:
                        upload_response = self._call(
                            mm_calls.ScottyAgentPut,
                            upload_url,
                            audio_file,
                            content_type=content_type,
                        ).body

                        if upload_response.get('sessionStatus',
                                               {}).get('state'):
                            result.update({
                                'success':
                                True,
                                'reason':
                                'Uploaded',
                                'song_id':
                                track_sample_response.server_track_id,
                            })
                        else:
                            result.update({
                                'success': False,
                                'reason':
                                upload_response,  # TODO: Better error details.
                            })
                else:
                    # Do not upload files if transcode option set to False.
                    result.update({
                        'success':
                        False,
                        'reason':
                        'Transcoding disabled for file type.',
                    })

                self._call(mm_calls.UploadState, self.uploader_id, 'STOPPED')
        else:
            response_codes = upload_pb2._TRACKSAMPLERESPONSE.enum_types[0]
            response_type = response_codes.values_by_number[
                track_sample_response.response_code].name

            reason = response_type

            result.update({'success': False, 'reason': f'{reason}'})

            if response_type == 'ALREADY_EXISTS':
                result['song_id'] = track_sample_response.server_track_id

        return result
Ejemplo n.º 29
0
    os.system('cls' if os.name == 'nt' else 'clear')


try:
    pid = os.popen('wmic process get description, processid').read()
    pid = int(pid[pid.index("Music.UI.exe") + 12:pid.index("Music.UI.exe") +
                  45])
    print(pid)
    p = psutil.Process(pid)
    print(p)
    openHandles = p.open_files()
    matching = [s for s in openHandles if "\Music" in str(s)]
    music = str(matching[0])
    info = music[music.index("path=") + 6:music.index(", fd") - 1]
    info = info.replace('\\\\', '/')
    metadata = audio_metadata.load(info)
    infoTemp = info
    metadata = audio_metadata.load(info)
    RPC.update(state=metadata.tags['artist'][0],
               details=metadata.tags['title'][0],
               large_image="groove",
               small_image="mad",
               large_text="Groove Music",
               small_text="madge",
               end=int(time()) + int(metadata.streaminfo['duration']))
except ValueError:
    print("Groove Music not running")
except IndexError:
    RPC.update(state="Idle",
               details="Idle",
               large_image="groove",
Ejemplo n.º 30
0
def test_load_pathobj():
    for fp in test_filepaths:
        audio_metadata.load(fp)