Chexz
Chexz

Reputation: 29

Spotify voice assistant attribute error __enter__

Hi there so I wanted to make a spotify voice assistant so I found a video on youtube and the guy just went through his code and how it works and left the source code on his github so I used that and configured it to work on my settings but i'm getting an attribute error enter with one of his lines and theres 3 files "main.py" "setup.txt" and "pepper.py" but the problem is in main so im gonna drop the code down below

main.py:

import pandas as pd
from speech_recognition import Microphone, Recognizer, UnknownValueError
import spotipy as sp
from spotipy.oauth2 import SpotifyOAuth

from pepper import *

# Set variables from setup.txt
setup = pd.read_csv(r'C:\Users\Yousif\Documents\Python spotify\setup.txt', sep='=', index_col=0, squeeze=True, header=None)
client_id = setup['client_id']
client_secret = setup['client_secret']
device_name = setup['device_name']
redirect_uri = setup['redirect_uri']
scope = setup['scope']
username = setup['username']

# Connecting to the Spotify account
auth_manager = SpotifyOAuth(
    client_id=client_id,
    client_secret=client_secret,
    redirect_uri=redirect_uri,
    scope=scope,
    username=username)
spotify = sp.Spotify(auth_manager=auth_manager)

# Selecting device to play from
devices = spotify.devices()
deviceID = None
for d in devices['devices']:
    d['name'] = d['name'].replace('’', '\'')
    if d['name'] == device_name:
        deviceID = d['id']
        break

# Setup microphone and speech recognizer
r = Recognizer()
m = None
input_mic = 'Voicemod Virtual Audio Device (WDM)'  # Use whatever is your desired input
for i, microphone_name in enumerate(Microphone.list_microphone_names()):
    if microphone_name == input_mic:
        m = Microphone(device_index=i)

while True:
    """
    Commands will be entered in the specific format explained here:
     - the first word will be one of: 'album', 'artist', 'play'
     - then the name of whatever item is wanted
    """
    with m as source:
        r.adjust_for_ambient_noise(source=source)
        audio = r.listen(source=source)

    command = None
    try:
        command = r.recognize_google(audio_data=audio).lower()
    except UnknownValueError:
        continue

    print(command)
    words = command.split()
    if len(words) <= 1:
        print('Could not understand. Try again')
        continue

    name = ' '.join(words[1:])
    try:
        if words[0] == 'album':
            uri = get_album_uri(spotify=spotify, name=name)
            play_album(spotify=spotify, device_id=deviceID, uri=uri)
        elif words[0] == 'artist':
            uri = get_artist_uri(spotify=spotify, name=name)
            play_artist(spotify=spotify, device_id=deviceID, uri=uri)
        elif words[0] == 'play':
            uri = get_track_uri(spotify=spotify, name=name)
            play_track(spotify=spotify, device_id=deviceID, uri=uri)
        else:
            print('Specify either "album", "artist" or "play". Try Again')
    except InvalidSearchError:
        print('InvalidSearchError. Try Again')

the exact error is:

Traceback (most recent call last):
  File "c:/Users/Yousif/Documents/Python spotify/main.py", line 49, in <module>
    with m as source:
AttributeError: __enter__

Upvotes: 0

Views: 62

Answers (1)

mauro
mauro

Reputation: 51

__enter__ is a python method that allows you to implement objects that can be used easily with the with statement. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):

class DatabaseConnection(object):

    def __enter__(self):
        # make a database connection and return it
        ...
        return self.dbconn

    def __exit__(self, exc_type, exc_val, exc_tb):
        # make sure the dbconnection gets closed
        self.dbconn.close()
        ...

The error here is caused because m = None, and None cannot be used in a with statement.

>>> with None as a:
...     print(a)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __enter__

Upvotes: 1

Related Questions