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__
__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__
Related
If I run the below code in pycharm, I get this error:
--error--
C:\Python33\python.exe B:/Python/untitled3/working_test.py
'vim.VirtualMachine:vm-65063'
Traceback (most recent call last):
File "B:/Python/untitled3/working_test.py", line 47, in <module>
main()
File "B:/Python/untitled3/working_test.py", line 37, in main
filterspec = vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=source_machine))
TypeError: __init__() takes 1 positional argument but 2 were given
Process finished with exit code 1
--error--
I've tried using self, creating a class etc, but I just can't get my head around what I'm doing wrong. Any help is appreciated. I'm basically, trying to get task information on an entity (virtual machine) within vsphere.
Thanks!
import ssl
from pyVim import connect
from pyVmomi import vmodl, vim
def main():
try:
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
si = connect.SmartConnect(host='vcenter name',
user='user name',
pwd='password',
port=443,
sslContext=context)
if not si:
print("Could not connect to the specified host using specified "
"username and password")
return -1
content = si.RetrieveContent()
def getobject(vimtype, name):
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
for c in container.view:
if c.name == name:
obj = c
break
return obj
source_machine = getobject([vim.VirtualMachine], 'virtual machine name')
print(source_machine)
taskManager = content.taskManager
filterspec = vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=source_machine))
collector = taskManager.CreateCollectorForTasks(filterspec)
except vmodl.MethodFault as e:
print("Caught vmodl fault : {}".format(e.msg))
return -1
return 0
if __name__ == "__main__":
main()
thank you for the help.
i've adjusted this portion of the code and it's returned back without errors, but looking into now, why it only seems to be returning the query task itself instead of the tasks pertaining to the vm. I think it may have something to do with the tasks being at a vcenter level, but working throug it now.
source_machine = getobject([vim.VirtualMachine], 'virtual machine name)
taskManager = content.taskManager
filterspec = vim.TaskFilterSpec()
filterspec.entity = vim.TaskFilterSpec.ByEntity(entity=source_machine,recursion='all')
collector = taskManager.CreateCollectorForTasks(filterspec)
print(collector)
output returned:
C:\Python33\python.exe B:/Python/untitled3/working_test.py
'vim.TaskHistoryCollector:session[52b617f0-0f65-705c-7462-814d8b648fdd]52081175-cb98-a09f-f9f6-f6787f68d3b7'
Process finished with exit code 0
vim.TaskFilterSpec() accepts no positional arguments. A minimal reproduction of the exception can be had with:
>>> vim.TaskFilterSpec(vim.TaskFilterSpec.ByEntity(entity=vim.ManagedEntity('1')))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
The class constructor vim.TaskFilterSpec() wants to be invoked with a entity named parameter. In your example code above, this would mean altering line 37 to read:
filterspec = vim.TaskFilterSpec(entity=vim.TaskFilterSpec.ByEntity(entity=source_machine))
When invoked with a placebo ManagedEntity, this results in a filter-spec similar to:
>>> source_machine=vim.ManagedEntity('1')
>>> filterspec = vim.TaskFilterSpec(entity=vim.TaskFilterSpec.ByEntity(entity=source_machine))
>>> filterspec
(vim.TaskFilterSpec) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
entity = (vim.TaskFilterSpec.ByEntity) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
entity = 'vim.ManagedEntity:1',
recursion = <unset>
},
time = <unset>,
userName = <unset>,
activationId = (str) [],
state = (vim.TaskInfo.State) [],
alarm = <unset>,
scheduledTask = <unset>,
eventChainId = (int) [],
tag = (str) [],
parentTaskKey = (str) [],
rootTaskKey = (str) []
}
Below is the code I have been working on.
The very last line write_csv('twitter_gmail.csv', messages, append=True) throws a
[ec2-user#ip-172-31-46-164 ~]$ ./twitter_test16.sh
Traceback (most recent call last):
File "./twitter_test16.sh", line 53, in
write_csv('twitter_gmail.csv', messages, append=True)
NameError: name 'messages' is not defined
I have messages defined so I dont understand why it would do that.
import csv
import json
import oauth2 as oauth
import urllib
import sys
import requests
import time
CONSUMER_KEY = "
CONSUMER_SECRET = "
ACCESS_KEY = "
ACCESS_SECRET = "
class TwitterSearch:
def __init__(self, ckey=CONSUMER_KEY, csecret=CONSUMER_SECRET,
akey=ACCESS_KEY, asecret=ACCESS_SECRET,
query='https://api.twitter.com/1.1/search/tweets.{mode}?{query}'
):
consumer = oauth.Consumer(key=ckey, secret=csecret)
access_token = oauth.Token(key=akey, secret=asecret)
self.client = oauth.Client(consumer, access_token)
self.query = query
def search(self, q, mode='json', **queryargs):
queryargs['q'] = q
query = urllib.urlencode(queryargs)
return self.client.request(self.query.format(query=query, mode=mode))
def write_csv(fname, rows, header=None, append=False, **kwargs):
filemode = 'ab' if append else 'wb'
with open(fname, filemode) as outf:
out_csv = csv.writer(outf, **kwargs)
if header:
out_csv.writerow(header)
out_csv.writerows(rows)
def main():
ts = TwitterSearch()
response, data = ts.search('#gmail.com', result_type='recent')
js = json.loads(data)
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] \
for msg in js.get('statuses', []))
write_csv('twitter_gmail.csv', messages, append=True)
The previous line is missing a parenthesis.
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', [])
Should be:
messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
I'm surprised that it works when you change to print? Are you also changing the comprehension when you do that?
You asked why the line number of the error was after the bad syntax?
Try putting this in line one of a file and running it, and note the line of the SyntaxError.
a = (]
Then try this and check out the line number:
a = (
b = "some stuff"
Finally, try this:
a = (
b = "some stuff"
Think about when you would know that the programmer had made a python-illegal typo if you were reading the code and carrying it out via pen and paper.
Basically, a SyntaxError is raised as soon as it can be unambiguously determined that invalid syntax was used, which is often immediately after a statement where a mistake was made, not immediately at.
You'll frequently get line numbers on SyntaxErrors that are a line (or several lines if there's empty lines or a corner case) below the actual typo.
I'm currently trying to use the pjsip api pjsua in python and therefor studying this Hello World example: http://trac.pjsip.org/repos/wiki/Python_SIP/Hello_World
I copied the code over, integrated account configuration according to http://trac.pjsip.org/repos/wiki/Python_SIP/Accounts etc. But when I run the sample, I get the following output:
Traceback (most recent call last):
File "/home/dmeli/workspace/eit.cubiephone.sip_test/eit/cubiephone/sip_test/hello.py", line 48, in <module>
acc = lib.create_account(acc_cfg)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 2300, in create_account
err, acc_id = _pjsua.acc_add(acc_config._cvt_to_pjsua(), set_default)
File "/usr/local/lib/python2.7/dist-packages/pjsua.py", line 900, in _cvt_to_pjsua
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
AttributeError: '_pjsua.Transport_Config' object has no attribute '_cvt_to_pjsua'
Because I'm not really a python expert and never worked with PJSIP before, I can't really figure out the error. Too me, it looks like it's actually an error in the pjsip python wrapper. But what do I know?
Code:
lib = pj.Lib()
lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
transport = lib.create_transport(pj.TransportType.UDP)
lib.start()
acc_cfg = pj.AccountConfig("XXXXX", "XXXXXX", "XXXXXX")
acc_cfg.id = "sip:XXXXXXX#XXXXXXXX"
acc_cfg.reg_uri = "sip:XXXXXXXXX"
acc_cfg.proxy = [ "sip:XXXXXXXXX;lr" ]
acc = lib.create_account(acc_cfg)
# Make call
call = acc.make_call("XXXXXXXXXXX", MyCallCallback())
Line where the error happens in pjsua.py:
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
(rtp_transport_cfg doesn't seem to have a member _cvt_to_pjsua()??)
For further work correctly, look at the PJSIP api (pjsua.py) that he is waiting for the order and structure!!!
## start lib.
def start(self):
try:
self._start_lib()
self._start_acc()
except pj.Error:
print "Error starting lib."
def _bind(self):
try:
t = pj.TransportConfig()
t.bound_addr = '0.0.0.0'
t.port = 5060
acc_transport = "udp" # depend if you need.
if acc_transport == "tcp":
self.transport = self.lib.create_transport(pj.TransportType.TCP, t)
# or this pj.TransportConfig(0) is creating random port ...
#self.transport = self.lib.create_transport(pj.TransportType.TCP, pj.TransportConfig(0))
else:
self.transport = self.lib.create_transport(pj.TransportType.UDP, t)
#self.transport = self.lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0))
except pj.Error:
print "Error creating transport."
#you need create callbacks for app, to work incoming calls, check on the server that returns the error code 200, and such a way your program will know that you are logged on correctly
#from callback.acc_cb import acc_cb
#self.acc_t = self.lib.create_account_for_transport(self.transport, cb=acc_cb())
def _start_lib(self):
self.lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb))
self.lib.start()
self._bind()
#codecs.load_codecs()
def _start_acc(self):
#from callback.acc_cb import acc_cb
try:
proxy = "sip server ip" # or proxy = socket.gethostbyname(unicode("sip.serverdnsname.com")) is needed to import socket
login = "Atrotygma" # real username
password = "Atrotygma_password" # real username
lib.create_account(acc_config=pj.AccountConfig(proxy, login, password))
except Exception, e:
print "Error creating account", e
I am trying to open an existing .xls document with OpenOffice using the Python 2.7 win32com module. The following script runs perfectly through an interpreter:
from win32com import client
import time
import string
def pathnameToUrl( cPathname):
"""Convert a Windows or Linux pathname into an OOo URL."""
if len( cPathname ) > 1:
if cPathname[1:2] == ":":
cPathname = "/" + cPathname[0] + "|" + cPathname[2:]
cPathname = string.replace( cPathname, "\\", "/" )
cPathname = "file://" + cPathname
return cPathname
def PropertyValueArray(num):
'''Creates an openoffice property value array'''
l = []
for x in range(num):
_p = manager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
_p.Name = ''
_p.Value = ''
l.append(_p)
return l
wbcpath = r"C:\myexcelfile.xls"
manager = client.DispatchEx("com.sun.star.ServiceManager")
desktop = manager.CreateInstance("com.sun.star.frame.Desktop")
manager._FlagAsMethod("Bridge_GetStruct")
manager._FlagAsMethod("Bridge_GetValueObject")
p = PropertyValueArray(1)
p[0].Name = 'Hidden' # doc should run hidden
p[0].Value = True # doc should run hidden
doc = desktop.loadComponentFromURL(pathnameToUrl(wbcpath), "_blank", 0, p)
doc.store()
time.sleep(5)
doc.dispose()
When I try to schedule this under Windows Task Scheduler on Windows Server Standard 2007 SP2 if get the following error:
Traceback (most recent call last):
File "D:\report_polygon_count.py", line 216, in <module>
manager = client.DispatchEx("com.sun.star.ServiceManager")
File "C:\Python27\ArcGIS10.1\lib\site-packages\win32com\client\__init__.py", line 113, in DispatchEx
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
com_error: (-2146959355, 'Server execution failed', None, None)
I am sure the issue is that the application wants to open a window and it is begin rejected because there is no user logged in. I have attempted to run it as hidden to avoid this issue. Is there a way to get round this or is it too ambitious?
I am trying to get the profiles feed from my Google Apps domain using the gdata library supplied my Google for Python. This is my code
import atom
import gdata.auth
import gdata.contacts
import gdata.contacts.service
gd_client = gdata.contacts.service.ContactsService()
gd_client.email = 'name#domain.com'
gd_client.password = 'password'
gd_client.source = 'madeupgibberish'
gd_client.account_type = 'HOSTED'
gd_client.contact_list = 'domain.com'
gd_client.ProgrammaticLogin()
def PrintFeed(feed):
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.title.text)
max_results = raw_input(
'Enter max return: ')
feed_uri = gd_client.GetProfilesFeed()
query = gdata.contacts.service.ContactsQuery(feed_uri)
print(feed_uri)
query.max_results = max_results
#query.orderby='title'
feed = gd_client.GetContactsFeed(query.ToUri())
# Use the print feed method defined above.
PrintFeed(feed)
print(feed_uri)
#print feed
f = open('c:\\python27\\junk.xml', 'w')
f.write(str(feed))
f.close()
When I run this it returns:
C:\Python27\Lib\gdata-2.0.16>python contactAPI.py
Enter max return: 300
Traceback (most recent call last):
File "contactAPI.py", line 27, in <module>
feed_uri = gd_client.GetProfilesFeed()
File "build\bdist.win-amd64\egg\gdata\contacts\service.py", line 294, in GetProfilesFeed
File "build\bdist.win-amd64\egg\gdata\service.py", line 1108, in Get
gdata.service.RequestError: {'status': 403, 'body': 'Version 1.0 is not supported.', 'reason': 'Forbidden'}
I am able to use GetContactsFeed and other feeds, but I cannot get profiles. Any idea whats happening here or what I need to fix? Thank you in advance for your help.
The gdata.contacts.service uses the deprecated version of the API. You should use gdata.contacts.{client, data} instead}
Here is a sample getting users profiles.
import atom
import gdata.auth
import gdata.contacts
import gdata.contacts.client
email = 'admin#domain.com'
password = 'password'
domain = 'domain.com'
gd_client = gdata.contacts.client.ContactsClient(domain=domain)
gd_client.ClientLogin(email, password, 'madeupgibberish')
def PrintFeed(feed):
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.title.text)
feed_link = atom.data.Link(gd_client.GetFeedUri(kind='profiles'))
while feed_link:
profiles_feed = gd_client.GetProfilesFeed(uri=feed_link.href)
PrintFeed(profiles_feed)
feed_link = profiles_feed.GetNextLink()
The library's contact_sample.py and unshare_profiles.py work with the client, data files.