def game_telas_manager(): pygame.init() tela_menu = Menu() tela_dificuldade = Dificuldade() tela_creditos = Creditos() tela_loop = Loop() audio_comeco_jogo = Audio("pickup_3.wav", 0.5) audio_menu_fundo = Audio("garotadeipanema.ogg", 0.5) audio_menu_fundo.audio.play() decisao_menu = "tomar_decisao" fechar_jogo = False in_loop = True while in_loop: for event in pygame.event.get(): if event.type == pygame.QUIT: fechar_jogo = True in_loop = False if decisao_menu == "tomar_decisao": decisao_menu = tela_menu.game_menu() elif decisao_menu == "fechar_jogo": fechar_jogo = True in_loop = False elif decisao_menu == "menu_iniciar": audio_comeco_jogo.audio.play() audio_menu_fundo.audio.stop() retorno_tela_loop = tela_loop.game_loop() if retorno_tela_loop == "fechar_jogo": fechar_jogo = True in_loop = False elif decisao_menu == "menu_dificuldade": retorno_tela_dificuldade = tela_dificuldade.game_dificuldade() if retorno_tela_dificuldade == "fechar_jogo": fechar_jogo = True in_loop = False elif retorno_tela_dificuldade == "voltar": decisao_menu = "tomar_decisao" elif retorno_tela_dificuldade == "dificuldade_normal": decisao_menu = "menu_iniciar" elif retorno_tela_dificuldade == "dificuldade_dificil": decisao_menu = "menu_iniciar" elif decisao_menu == "menu_creditos": retorno_tela_creditos = tela_creditos.game_creditos() if retorno_tela_creditos == "fechar_jogo": fechar_jogo = True in_loop = False elif retorno_tela_creditos == "voltar": decisao_menu = "tomar_decisao" if fechar_jogo: return "fechar_jogo"
def move_right(self): print("You tried to move right") if (self.maze.can_move(self.player.x_coordinate, self.player.y_coordinate, 'right')): print("You moved right") self.player.move_right() self.print_player_status() return Audio('footsteps') else: print("You failed") return Audio('hiting a wall')
def setupMedia(self, item): duration = item.video.duration if item.video else item.audio.duration self.video_backend = item.video self.audio_backend = item.audio # 还没有播放过片段,建立子线程并初始化相应对象 if self.flag == 0: self.video = Video(item.video) self.durationChanged(duration) self.calthread = QThread() self.video.moveToThread(self.calthread) self.video.t_changed.connect(self.positionChanged) self.stop.connect(self.video.stop) self.pause.connect(self.video.pause) self.resume.connect(self.video.resume) self.video.finish.connect(self.processFinish) self.calthread.started.connect(self.video.work) self.set_video.connect(self.video.setClip) self.audioThread = QThread() if self.audio_backend: self.audio = Audio(clip=item.audio, fps=item.audio.fps, buffersize=int(1.0 / self.video.fps * item.audio.fps), nbytes=2) else: self.audio = Audio(clip=None, fps=0, buffersize=0, nbytes=0) self.audio.moveToThread(self.audioThread) self.audioThread.started.connect(self.audio.work) self.set_audio.connect(self.audio.setClip) # 已经播放过,此时视频线程与音频线程均存在,设置相应对象信息即可 else: v_fps = item.video.fps if item.video else 30 if item.video and item.audio: self.durationChanged(duration) self.set_video.emit(item.video) self.set_audio.emit(item.audio, item.audio.fps, int(1.0 / v_fps * item.audio.fps), 2) elif item.video and not item.audio: self.set_video.emit(item.video) self.set_audio.emit(None, 44100, 0, 2) self.durationChanged(duration) else: self.set_video.emit(item.video) self.durationChanged(item.audio.duration) self.set_audio.emit(item.audio, item.audio.fps, int(1.0 / v_fps * item.audio.fps), 2) self.state = State.READY self.fitState()
def passphrase(self): print "in speech" r = sr.Recognizer() print 'Please say your chosen passphrase AFTER the beep.' Audio().aud('../audio/Speak.wav') Audio().aud('../audio/now.wav') with sr.Microphone() as source: #audio = r.adjust_for_ambient_noise(source, duration = 1) #audio = r.dynamic_energy_threshold = True audio = r.listen(source) if audio: print "Audio caught, please wait - Processing." else: print "No audio caught." Speech().passphraseErr() try: list = r.recognize( audio, True) # generate a list of possible transcriptions print("Possible transcriptions:") for prediction in list: text = prediction["text"] confidence = prediction["confidence"] * 100.0 if "*" in text: print "Bad word detected, please retry." Speech().passphrase() break print("Detected speech: " + text.upper() + " with confidence level of: %.1f" % (confidence)) if confidence > 51: print "Matched " + text Verify().verification(str(text.lower())) break else: Audio().aud('../audio/Retry.wav') print 'Retry' # execfile('speech.py') Speech().passphrase() break except LookupError, e: print("Could not understand audio, retry..\n" + str(e)) Speech().passphraseErr()
def __init__(self, bucket_name, filepath, output_filepath): self.bucket_name = bucket_name self.storage_client = storage.Client() self.bucket = self.storage_client.get_bucket(self.bucket_name) self.filepath = filepath self.output_filepath = output_filepath self.audio = Audio()
def playRecipe(id): # Get the recipe we want recipes = Recipe.query.filter_by(id=id).first() ingredients = Ingredient.query.filter_by(recipe_id=id) method = Cook.query.filter_by(recipe_id=id) audio = Audio() # Generate audio files for selected recipe pathI = "./audio/" + str(id) + "/ing/" pathM = "./audio/" + str(id) + "/method/" path = "./audio/" + str(id) + "/" print(recipes) print(ingredients) print(method) jsonObj = { 'recipeName': recipes.name } for i, ing in enumerate(ingredients): print(ing.name) strIndex = str(i) jsonObj['ing'] = { i: ing.name } return jsonify(jsonObj)
def audio_extract_api(): if request.method == "POST": print("Reading data") data = request.form.to_dict() files = request.files.to_dict() # Process audio = Audio(data, files, mode='extract') audio.extract() # Response print("Building Response") mime = magic.Magic(mime=True) m = MultipartEncoder( fields={ 'messageFileName': audio.output_file_name, 'messageFileType': mime.from_file(audio.output_file_path), 'messageFile': (audio.output_file_name, open(audio.output_file_path, 'rb'), mime.from_file(audio.output_file_path)), 'containerFileName': audio.container_file_name, 'containerFilePath': audio.container_file_path, 'containerFile': (audio.container_file_name, open(audio.container_file_path, 'rb'), mime.from_file(audio.container_file_path)) }) return (m.to_string(), {'Content-Type': m.content_type}) else: return jsonify({'message': "Input file not appropriate"}), 400
def audio_embedding_api(): if request.method == "POST": print("Reading data") data = request.form.to_dict() files = request.files.to_dict() # Proesss audio = Audio(data, files, mode='embedding') # audio.embedding() # print("Counting PSNR") # psnr = audio_psnr(audio.container_file_path, audio.encrypted_file_path) psnr = 69 # Response print("Building Response") mime = magic.Magic(mime=True) open_file = open(audio.encrypted_file_path, 'rb') bytes_json = open_file.read() open_file.close() response_json = jsonify({ 'psnr': str(psnr), 'encryptedFileName': audio.encrypted_file_name, 'encryptedFileType': mime.from_file(audio.encrypted_file_path), 'encryptedFile': str(bytes_json) }) return response_json, 200 else: return jsonify({'message': "Input file not appropriate"}), 400
def load(self): """ load audio from local disk :return: """ rf = wave.open(self._stream_full_path, 'rb') # 声道数, 量化位数(byte), 采样频率, 采样点数, 压缩类型, 压缩类型的描述 (channels, sampling_with, sampling_freq, sampling_points, comp_type, comp_desc) = rf.getparams() # TODO: here we assume that sampling width is 2 bytes and audio channels equals to 1 assert sampling_with == 2 assert channels == 1 assert sampling_freq == 16000 audio_seq_str = rf.readframes(sampling_points) audio_seq = np.frombuffer(audio_seq_str, dtype=np.short) # assign loaded .wav object self._audio = Audio( channels=channels, sampling_with=sampling_with, sampling_freq=sampling_freq, sampling_points=sampling_points, comp_type=comp_type, comp_desc=comp_desc, audio_seq= audio_seq # numerical representation of input audio sequence ) rf.close()
def __init__(self): self.ftp = FTPCtrol() self.audio = Audio() self.camera = Camera() self.setup_pins()
def random_cents_fifths(): total_duration_seconds = 120 notes_per_second = 1.2 marimba = Marimba() audio = Audio(total_duration_seconds) total_duration_samples = audio.sample_rate * total_duration_seconds midi_numbers = marimba.get_midi_numbers(cents=True)[:-4000] ticks = int(total_duration_seconds * notes_per_second) for _ in range(ticks): print _, 'of', ticks start = np.random.randint(audio.n_samples - 100000) midi_number = np.random.choice(midi_numbers) sample = marimba.get_note(midi_number) audio.add(start, sample) max_delay = .3 * audio.sample_rate end_minus_padding = audio.n_samples - (max_delay * 15) if start < end_minus_padding: delay = audio.sample_rate * np.random.normal(.12, .017) for _ in range(4): start += delay echo_start = int(start) midi_number += 7.02 echo_sample = marimba.get_note(midi_number) audio.add(echo_start, echo_sample) audio.write_wav('random-uniform')
def make_music(): sr = 44100 denis_audio, _ = librosa.load('denis-curran-short.mp3', mono=True, sr=sr) cqt = np.abs(librosa.cqt(denis_audio, sr=sr)).T denis_pitches = np.argmax(cqt, 1) * (np.max(cqt, 1) > .7) audio = Audio(initial_audio=denis_audio) # audio._audio += denis_audio # audio.add(0, denis_audio) # audio = np.zeros([len(denis_audio), 2]) # audio = (audio.T + denis_audio).T marimba = Marimba() previous_notes = np.ones(marimba.n_notes) * -100 previous_note_i = -100 chord = random_chord() hop_length = 512 len_denis_pitches = len(denis_pitches) for i, p in enumerate(denis_pitches): print i, 'of', len_denis_pitches, p if p > 0 and i - previous_note_i > 3: if i - previous_note_i > 50: chord = random_chord() t = i * hop_length p = note_in_chord(chord, p) while p >= marimba.n_notes: p -= 12 if np.random.random() > .5: while p > 0 and i - previous_notes[p] < 10: p -= 12 if p < 0: continue else: while p < 60 and i - previous_notes[p] < 10: p += 12 if p >= 60: continue note = marimba.get_note(p) length = min(audio.n_samples - t, len(note)) pan = np.random.random() audio.add(t, note[:length], pan=pan) # audio[t:t + length, 0] += note[:length] * pan * .1 # audio[t:t + length, 1] += note[:length] * (1 - pan) * .1 previous_note_i = i previous_notes[p] = i audio.write_wav('denis-marimba')
def main(): # pygame setup pygame.display.set_caption("Breakout") CLOCK = pygame.time.Clock() AUDIO = Audio() play_intro_sequence(CLOCK, AUDIO) AUDIO.play_music_main() # Setup menus for the game op = Menu('Options', CLOCK) op.add_item('Borderless', callback=lambda: update_mode(pygame.NOFRAME)) op.add_item('Fullscreen', callback=lambda: update_mode(pygame.FULLSCREEN)) op.add_item('Windowed', callback=lambda: update_mode(0)) op.add_item('Back', callback='exit') mm = Menu('Main Menu', CLOCK) mm.add_item('New Game', callback=lambda: new_level(CLOCK)) mm.add_item('Level Select', callback=lambda: level_select(CLOCK)) mm.add_item('Stage Editor', callback=LevelEditor(CLOCK).activate) mm.add_item('Options', callback=op.activate) mm.add_item('Quit', callback='exit') # main game loop mm.activate()
def different_sections(): func_name = 'different_sections' print 'Running {}...'.format(func_name) marimba = Marimba() audio_duration_seconds = 120 audio = Audio(audio_duration_seconds) sections = Sections(32, len(audio)) scale_type = [0, 4, 7] root = 0 for section in sections: section.root = root scale = [(pc + root) % 12 for pc in scale_type] section.scale = [p for p in range(60, 73) if p % 12 in scale] root = (root + 1) % 12 max_start = len(audio) - 80000 n_notes = audio_duration_seconds * 5 for _ in range(n_notes): start = np.random.randint(0, max_start) scale = sections.get_by_sample_offset(start).scale midi_number = np.random.choice(scale) note = marimba.get_note(midi_number) audio.add(start, note) audio.write_wav(func_name) print 'Done running {}.'.format(func_name)
def __init__(self, access_token=''): self.Account = Account(access_token=access_token) self.Apps = Apps(access_token=access_token) self.Audio = Audio(access_token=access_token) self.Auth = Auth(access_token=access_token) self.Board = Board(access_token=access_token) self.Database = Database(access_token=access_token) self.Docs = Docs(access_token=access_token) self.Other = Other(access_token=access_token) self.Fave = Fave(access_token=access_token) self.Friends = Friends(access_token=access_token) self.Gifts = Gifts(access_token=access_token) self.Groups = Groups(access_token=access_token) self.Likes = Likes(access_token=access_token) self.Market = Market(access_token=access_token) self.Messages = Messages(access_token=access_token) self.Newsfeed = Newsfeed(access_token=access_token) self.Notes = Notes(access_token=access_token) self.Notifications = Notifications(access_token=access_token) self.Pages = Pages(access_token=access_token) self.Photos = Photos(access_token=access_token) self.Places = Places(access_token=access_token) self.Polls = Polls(access_token=access_token) self.Search = Search(access_token=access_token) self.Stats = Stats(access_token=access_token) self.Status = Status(access_token=access_token) self.Storage = Storage(access_token=access_token) self.Users = Users(access_token=access_token) self.Utils = Utils(access_token=access_token) self.Video = Video(access_token=access_token) self.Wall = Wall(access_token=access_token) self.Widgets = Widgets(access_token=access_token)
def multiple_random_tempos(): print 'Running multiple_random_tempos...' marimba = Marimba() audio = Audio(1200) quarter_duration_in_seconds = 1.0 n_parts = 40 lowest_harmonic = 2 n_harmonics = n_parts lowest_midi_note = 36.0 pitches = get_slice_of_harmonic_series(lowest_harmonic, n_harmonics, lowest_midi_note=lowest_midi_note) durations = random_from_range(2.0, 6.0, size=n_parts) print durations for pitch, duration in zip(pitches, durations): duration *= quarter_duration_in_seconds pulse(audio, marimba, pitch, duration, 0.75) audio.write_wav('multiple-random-tempos') print 'Done running multiple_random_tempos.'
def multiple_tempos_refactored(): print 'Running multiple_tempos_refactored...' marimba = Marimba() audio = Audio(120) quarter_duration_in_seconds = 1.2 n_parts = 23 lowest_harmonic = 1 n_harmonics = n_parts lowest_midi_note = 36.0 pitches = get_slice_of_harmonic_series(lowest_harmonic, n_harmonics, lowest_midi_note=lowest_midi_note) durations = np.linspace(1.5, .2, n_parts) random_mute_threshholds = [ n / (n_parts + 1) for n in np.linspace(n_parts, 1, n_parts) ] print random_mute_threshholds for pitch, duration, random_mute_threshhold in zip( pitches, durations, random_mute_threshholds): duration *= quarter_duration_in_seconds pulse(audio, marimba, pitch, duration, random_mute_threshhold) audio.write_wav('multiple-tempos-muting') print 'Done running multiple_tempos_refactored.'
def multiple_tempos(): print 'Running multiple_tempos...' marimba = Marimba() audio = Audio(120) pulse(audio, marimba, 41.0, 1.5) # 1 -- 0 pulse(audio, marimba, 48.02, 1.4) # 3 -- 702 pulse(audio, marimba, 53.0, 1.3) # 1 -- 0 pulse(audio, marimba, 56.86, 1.2) # 5 -- 386 pulse(audio, marimba, 60.02, 1.1) # 3 -- 702 pulse(audio, marimba, 62.69, 1.0) # 7 -- 969 pulse(audio, marimba, 65.0, 0.9) # 1 -- 0 pulse(audio, marimba, 67.04, 0.8) # 9 -- 204 pulse(audio, marimba, 68.86, 0.7) # 5 -- 386 pulse(audio, marimba, 70.51, 0.6) # 11 - 551 pulse(audio, marimba, 72.02, 0.5) # 3 -- 702 pulse(audio, marimba, 73.41, 0.4) # 13 -- 841 pulse(audio, marimba, 74.69, 0.3) # 7 -- 969 pulse(audio, marimba, 75.88, 0.2) # 15 -- 1088 # pulse(audio, marimba, 77.0, 0.1) # 1 -- 0 audio.write_wav('multiple-tempos') print 'Done running multiple_tempos.'
def eval_model(working_dir: str, model: DeepSpeakerModel): enable_deterministic() audio = Audio(working_dir) batcher = LazyTripletBatcher(working_dir, NUM_FRAMES, model) speakers_list = list(audio.speakers_to_utterances.keys()) num_negative_speakers = 99 num_speakers = len(speakers_list) y_pred = np.zeros(shape=(num_speakers, num_negative_speakers + 1)) # negatives + positive for i, positive_speaker in tqdm(enumerate(speakers_list), desc='test', total=num_speakers): # convention id[0] is anchor speaker, id[1] is positive, id[2:] are negative. input_data = batcher.get_speaker_verification_data( positive_speaker, num_negative_speakers) # batch size is not relevant. just making sure we don't push too much on the GPU. predictions = model.m.predict(input_data, batch_size=BATCH_SIZE) anchor_embedding = predictions[0] for j, other_than_anchor_embedding in enumerate( predictions[1:]): # positive + negatives y_pred[i][j] = batch_cosine_similarity( [anchor_embedding], [other_than_anchor_embedding])[0] # y_pred[i] = softmax(y_pred[i]) # could apply softmax here. y_true = np.zeros_like(y_pred) # positive is at index 0. y_true[:, 0] = 1.0 print(np.matrix(y_true)) print(np.matrix(y_pred)) print(np.min(y_pred), np.max(y_pred)) fm, tpr, acc, eer = evaluate(y_pred, y_true) return fm, tpr, acc, eer
def __init__(self, working_dir: str, max_length: int, model: DeepSpeakerModel): self.working_dir = working_dir self.audio = Audio(cache_dir=working_dir) logger.info(f'Picking audio from {working_dir}.') self.sp_to_utt_train = train_test_sp_to_utt(self.audio, is_test=False) self.sp_to_utt_test = train_test_sp_to_utt(self.audio, is_test=True) self.max_length = max_length self.model = model self.nb_per_speaker = 2 self.nb_speakers = 640 self.history_length = 4 self.history_every = 100 # batches. self.total_history_length = self.nb_speakers * self.nb_per_speaker * self.history_length # 25,600 self.metadata_train_speakers = Counter() self.metadata_output_file = os.path.join(self.working_dir, 'debug_batcher.json') self.history_embeddings_train = deque(maxlen=self.total_history_length) self.history_utterances_train = deque(maxlen=self.total_history_length) self.history_model_inputs_train = deque(maxlen=self.total_history_length) self.history_embeddings = None self.history_utterances = None self.history_model_inputs = None self.batch_count = 0 for _ in tqdm(range(self.history_length), desc='Initializing the batcher'): # init history. self.update_triplets_history()
def __init__(self): self.levels = list() self.controllers = set() self.currentLevel = None self.PC = None self.audio = Audio() self.title = ""
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((716, 793 + 60)) pygame.display.set_caption("Pacman Portal") self.bricks = Group() self.shields = Group() self.powerpills = Group() self.qpills = Group() self.maze = Maze(self.screen, self.bricks, self.shields, self.powerpills, self.qpills, brickfile='square', mazefile='images/pacmanportalmaze.txt', shieldfile='shield', powerpill='powerpill') self.increase = False self.scoreboard = Scorebord(self.screen, self) self.pacman = Pacman(self.screen, self.scoreboard, self) self.play_button = Button(self.screen, "PLAY GAME", 80 / 100) self.score_button = Button(self.screen, "HIGH SCORES", 90 / 100) self.menu = Menu() self.audio = Audio() self.fruit = Fruit(self.screen) self.blinky = Blinky(self.screen, self.pacman, self.scoreboard) self.inky = Inky(self.screen, self.pacman, self.scoreboard) self.pinky = Pinky(self.screen, self.pacman, self.scoreboard) self.clyde = Clyde(self.screen, self.pacman, self.scoreboard) self.oportal = Portal('o', self.pacman) self.bportal = Portal('b', self.pacman) self.active = False self.pause = False
def setUp(self) -> None: current_dir = os.path.dirname(os.path.abspath(__file__)) current_dir = Path(current_dir) config_path = current_dir / 'resources' / 'test_config.yaml' self.mel_path = current_dir / 'resources' self.cfg = Config.load(config_path) self.audio = Audio(self.cfg)
def et_experiment(pitches_per_halfstep=3, notes_per_second=2.5, duration_seconds=30): print 'Running et_experiment...' marimba = Marimba() audio = Audio(duration_seconds) max_start = len(audio) - 50000 min_note = 36.0 max_note = 96.0 n_halfsteps = max_note - min_note n_pitches = n_halfsteps * pitches_per_halfstep midi_notes = np.linspace(36, 96, n_pitches, endpoint=False) print midi_notes n_notes = int(duration_seconds * notes_per_second) for i in range(n_notes): print '\t', i, 'of', n_notes midi_note = np.random.choice(midi_notes) note = marimba.get_note(midi_note) start = np.random.randint(max_start) audio.add(start, note) audio.write_wav('et-experiment') print 'Done running et_experiment.'
def __init__(self): self.screen = pygame.display.get_surface() self.gamestate = StateMachine() self.data = None self.video = Video() self.audio = Audio(self) self.running = False self.all_maps_loaded = False self.force_bg_music = False self.clock = pygame.time.Clock() self.playtime = 0.0 self.dt = 0.0 self.key_timer = 0.0 self.state_timer = 0.0 self.debugfont = pygame.font.SysFont(DEBUGFONT, DEBUGFONTSIZE) self.key_input = None self.mouse_input = None self.show_debug = False self.debug_mode = False self.fps = FPS threading.Thread(target=self.load_all_maps).start()
def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 51000)) detecter = Detection() dp = Display() ad = Audio() thread = Thread(target=dp.start) thread.setDaemon(True) thread.start() state_before = 0 while True: motor_power, target_dist = detecter.detect() # 走行プログラムと送信 sock.sendall(motor_power.to_bytes(2, 'big') + target_dist.to_bytes(2, 'big')) byte_data = sock.recv(4) #print(byte_data) state = int.from_bytes(byte_data[:2], 'big') ad_flag = int.from_bytes(byte_data[2:], 'big') #print(state) if state != state_before: dp.changeImage(state) if ad_flag == 1: if state_before == 0: ad.play(0) elif state == 5: ad.play(1) elif state_before == 5: ad.play(2) state_before = state
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") play_button = Button(screen, "Play", 80 / 100) score_button = Button(screen, "High Scores", 90 / 100) audio = Audio() menu = Menu() stats = GameStats(ai_settings) sb = Scorebord(ai_settings, screen, stats) ship = Ship(ai_settings, screen) ralien = RAlien(ai_settings, screen) bullets = Group() abullets = Group() aliens = Group() death = Group() bunkers = Group() gf.create_fleet(ai_settings, screen, aliens) while True: pygame.time.Clock().tick(ai_settings.game_speed) gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, score_button, menu, audio, bunkers) if stats.game_active: ship.update(audio) ralien.update(audio) gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets, abullets, ralien, audio, death, bunkers) gf.update_aliens(ai_settings, screen, ship, aliens, abullets, bunkers) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, score_button, abullets, menu, ralien, audio, death, bunkers)
def __init__(self, fifo, lock, **kw): threading.Thread.__init__(self, **kw) self.fifo = fifo self.lock = lock self.audio = Audio(byte=True, seconds=1) self.sleep = 1 self.BS = 18
def onClick(): onClickSound = button.getOnclickSound() if not onClickSound: onClickSound = BUTTON_CLICK Audio(onClickSound).play() button.enable() button.runOnClickAction()
def process_audio(audio_file_path): try: track = Audio(audio_file_path) """printed_line = "[{genre}] {artist} - {album} - {title}".format( album=track.get_album(), artist=track.get_artist(), genre=track.get_genre(), title=track.get_title(), ) if len(printed_line) > 160: printed_line = "{cut_line}...".format(cut_line=printed_line[:157]) else: printed_line = printed_line.ljust(160) print(printed_line, end='\r')""" new_genre = guess_genre(track) if new_genre == track.get_genre(): return logger.info( "{artist} - {album} - {title}: {old_genre} -> {genre}".format( album=track.get_album(), artist=track.get_artist(), genre=new_genre or '[Empty]', old_genre=track.get_genre() or '[Empty]', title=track.get_title(), ), ) track.set_genre(new_genre) except Exception as error: logger.error(error)