AttributeError when using googletrans module - python

I am writing code to make a translator using GUI. My program runs but when I try to translate text it throws the error AttributeError: 'NoneType' object has no attribute 'group'
My code
from tkinter import*
from tkinter import ttk
from googletrans import Translator,LANGUAGES
def change(text="type",src="English",dest="Hindi"):
text1=text
src1=src
dest1=dest
trans = Translator()
trans1 = trans.translate(text,src=src1,dest=dest1)
return trans1.text
def data():
s =comb_sor.get()
d =comb_dest.get()
msg = Sor_txt.get(1.0,END)
textget = change(text=msg,src=s,dest=d)
dest_txt.delete(1.0,END)
dest_txt.insert(END,textget)
root = Tk()
root.title("Translater")
root.geometry("500x800")
root.config(bg="#FFE1F3")
lab_txt=Label(root,text="Translator", font=("Time New Roman",40,"bold"),fg="#478C5C")
lab_txt.place(x=100,y=40,height=50,width=300)
frame=Frame(root).pack(side=BOTTOM)
lab_txt=Label(root,text="Source Text", font=("Time New Roman",20,"bold"),fg="#FFFF8A",bg="#FDA172")
lab_txt.place(x=100,y=100,height=20,width=300)
Sor_txt =Text(frame,font=("Time New Roman",20,"bold"),wrap=WORD)
Sor_txt.place(x=10,y=130,height=150,width=480)
list_text = list(LANGUAGES.values())
comb_sor = ttk.Combobox(frame,value=list_text)
comb_sor.place(x=10,y=300,height=20,width=100)
comb_sor.set("English")
button_change = Button(frame,text="Translate",relief=RAISED,command=data)
button_change.place(x=120,y=300,height=40,width=100)
comb_dest = ttk.Combobox(frame,value=list_text)
comb_dest.place(x=230,y=300,height=20,width=100)
comb_dest.set("English")
lab_txt=Label(root,text="Dest Text", font=("Time New Roman",20,"bold"),fg="#2E2EFF")
lab_txt.place(x=100,y=360,height=50,width=300)
dest_txt=Text(frame,font=("Time New Roman",20,"bold"),wrap=WORD)
dest_txt.place(x=10,y=400,height=150,width=480)
root.mainloop()
The error and stack trace
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\praful pawar\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\praful pawar\AppData\Local\Temp\ipykernel_9920\1422625581.py", line 19, in data
textget = change(text=msg,src=s,dest=d)
File "C:\Users\praful pawar\AppData\Local\Temp\ipykernel_9920\1422625581.py", line 10, in change
trans1 = trans.translate(text,src=src1,dest=dest1)
File "C:\Users\praful pawar\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 182, in translate
data = self._translate(text, dest, src, kwargs)
File "C:\Users\praful pawar\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\client.py", line 78, in _translate
token = self.token_acquirer.do(text)
File "C:\Users\praful pawar\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 194, in do
self._update()
File "C:\Users\praful pawar\AppData\Local\Programs\Python\Python310\lib\site-packages\googletrans\gtoken.py", line 62, in _update
code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
What it looks like
This image shows that my application is running but something is wrong:

This library's own documentation says (bold added by me):
I eventually figure out a way to generate a ticket by reverse engineering on the obfuscated and minified code used by Google to generate such token, and implemented on the top of Python. However, this could be blocked at any time.
It is designed to work around limitations that Google deliberately installed in Google Translate to make sure you use their official API (and presumably pay) to connect to their service programmatically.
I believe that what you are seeing today is that, as the author warned could happen at any time, it got blocked. The last release was two years ago, so Google has had plenty of time to patch the hole this library exploited.
PS: there's a ticket about this...
Well, I still think this library could get blocked at any time, but it turns out the library is still actively maintained, and they have a ticket open about this issue: https://github.com/ssut/py-googletrans/issues/354 I suggest you watch that ticket, maybe they will fix it.
I just tested the release candidate one reply mentions in the ticket, and it fixed the problem for me:
pip install googletrans==4.0.0rc1
might make your code work.

Related

Why is UPnPy discover throwing AttributeError?

I am working with UPnPy, and I immediately notice an issue when attempting to discover devices on my local network. Here is the basic code I am using:
import upnpy
upnp = upnpy.UPnP()
devices = upnp.discover()
This throws the following exception:
Traceback (most recent call last):
File "C:\Users\name\Projects\pythonProject\main.py", line 5, in <module>
devices = upnp.discover()
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\upnp\UPnP.py", line 33, in discover
for device in self.ssdp.m_search(discover_delay=delay, st='upnp:rootdevice', **headers):
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPRequest.py", line 50, in m_search
devices = self._send_request(self._get_raw_request())
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPRequest.py", line 100, in _send_request
device = SSDPDevice(addr, response.decode())
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPDevice.py", line 87, in __init__
self._get_services_request()
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPDevice.py", line 23, in wrapper
return func(device, *args, **kwargs)
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPDevice.py", line 54, in wrapper
return func(instance, *args, **kwargs)
File "C:\Users\name\Projects\pythonProject\venv\lib\site-packages\upnpy\ssdp\SSDPDevice.py", line 171, in _get_services_request
event_sub_url = service.getElementsByTagName('eventSubURL')[0].firstChild.nodeValue
AttributeError: 'NoneType' object has no attribute 'nodeValue'
I have been researching the cause of this but I have found nothing. I am using UPnPy version 1.1.8. I use PyCharm as my IDE. I've tried using previous versions of UPnPy but none seem to be working. Any help would be appreciated. Thanks!
Most likely you have a non-compliant UPnP Device in your home network that is serving a non-standard/broken XML at their description location, and upnpy was not smart enough to handle the parsing error and perhaps ignore that device.
That scenario is more common than you might think: many Smart TVs (LG ones for sure) have an embedded device that advertises as UPnP but their description endpoint answers JSON instead of XML!
Some suggestions:
Use a different library or app (you could try my own), at least to identify the culprit. Check turn on verbosity and look for warnings and parsing error logs
Use a scanner such as tcpdump to sniff network packets (UDP port 1900) for SSDP NOTICE advertises, and manually open each LOCATION URL in a browser to see if they're valid XML
Selectively turn off / unplug devices you think might be UPnP-enabled, such as Smart TVs, Home Theaters, Video Game consoles, Routers, etc, to see wich one was serving the bogus XML.
Edit your local copy of upnpy to handle that error, for example enclose the function/line with a try/except block and print some details about what is it trying to parse prior to the error.

AttributeError: 'list' object has no attribute 'expandtabs'

So, to start, I was making a discord bot (using discord.py) and making a help command, but it shows an error when I run the python file
I have no idea what was going on about this... (\n didn't cause the problem)
code (new one):
#client.command(aliases=["commands","cmds"], description="Get command list")
async def help(ctx):
embed = discord.Embed(title="Commands",description="List of the bot's commands",color=0xFF0000)
for commands in client.commands:
embed.add_field(name=commands,value=commands.description)
await ctx.send(embed)
and full error message:
Traceback (most recent call last):
File "C:\Users\Name\Documents\Codes\Python\bot.py", line 19, in <module>
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1262, in decorator
result = command(*args, **kwargs)(func)
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 1433, in decorator
return cls(func, name=name, **attrs)
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 244, in __init__
self.description = inspect.cleandoc(kwargs.get('description', ''))
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\inspect.py", line 632, in cleandoc
lines = doc.expandtabs().split('\n')
AttributeError: 'list' object has no attribute 'expandtabs'
would be nice if someone could help me
also, this is my first post (and I'm new here) so I don't know much about Stack Overflow
(PS: I have client.help_command = None in my code, thanks Kermit)
The description argument takes a string, not a list. So, it should look like this:
#client.command(aliases=["commands","cmds"], description="Get command list")
Also, make sure you have client.help_command = None somewhere in your code, so that the default help command provided by discord.py can be overridden.
The immediate issue is that the description kwarg of the command decorator is being given a list when it expects a string, which can be found out from the Command documentation.
However more importantly, as it appears you're trying to create your own help command, that is not the recommended way to do so since you forgo the advantages of the existing HelpCommand framework that handles argument parsing for you. If you need help with using it, check out this guide which goes through subclassing and adding it to your bot.
Sidenote: for future questions, please provide the full error message so it's easier for other users to debug.

AttributeError: 'ElasticLoadBalancingv2' object has no attribute 'set_desired_capacity'

import boto3
import json
import time
client = boto3.client('elbv2')
desired_capacity=8
client.set_desired_capacity(
AutoScalingGroupName='Test-Web',
DesiredCapacity=desired_capacity,
HonorCooldown=True)
and
boto3==1.7.1
When I run this script I get a
File "deploy_staging_web.py", line 6, in <module>
client.set_desired_capacity(
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 601, in __getattr__
self.__class__.__name__, item)
AttributeError: 'ElasticLoadBalancingv2' object has no attribute 'set_desired_capacity'
I intended to use python to scale aws instances up and down.
I'm not inside any virtual environment at the moment.
why is it being thrown, and how do I get across it?
It is even mentioned here on the official documentation : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.set_desired_capacity
The official document is for the latest version, not your too old version. Upgrade your boto3 package to the latest. The most recent version is 1.9.243.
The problem turns out to be a silly one.
boto3 has moved around the various functions.
set_desired_capacity is no longer part of 'elbv2' .
It is part of 'autoscaling' https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/autoscaling.html#AutoScaling.Client.set_desired_capacity
While 'describe_target_health' is still part of the former https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elbv2.html?highlight=elb#ElasticLoadBalancingv2.Client.describe_target_health.
Updating
client = boto3.client('elbv2')
to
client = boto3.client('autoscaling')
has solved my problem.

Python: Reading GuitarPro (.gp5) files

I'm new to writing questions here, so please feel free to point out how i can improve the quality of future questions!
Edit: More code included as was asked in the comments
I'm trying to read GuitarPro files into python. These files essentially contain the sheet music for songs, but contain more information than e.g. MIDI files.
I want to parse the notes and the duration of the notes into e.g. a list structure. Further, i hope other effects can be parsed from the GuitarPro files also, such as bends, slides, hammer-ons etc.
I have been trying to use the library PyGuitarPro, but get stuck:
import guitarpro
import os
# 'wet_sand.gp5' is the guitar pro file
parsed_song = guitarpro.parse('wet_sand.gp5')
song = guitarpro.gp5.GP5File(parsed_song,encoding='UTF-8')
song.readSong()
I get the following error from ReadSong() (documentation here):
Traceback (most recent call last):
File "<ipython-input-15-e1663229852d>", line 8, in <module>
song.readSong()
File "C:\Python27\lib\site-packages\guitarpro\gp5.py", line 62, in readSong
song.version = self.readVersion()
File "C:\Python27\lib\site-packages\guitarpro\iobase.py", line 114, in readVersion
self.version = self.readByteSizeString(30)
File "C:\Python27\lib\site-packages\guitarpro\iobase.py", line 97, in readByteSizeString
return self.readString(size, self.readByte())
File "C:\Python27\lib\site-packages\guitarpro\iobase.py", line 47, in readByte
return (self.read(*args, default=default) if count == 1 else
File "C:\Python27\lib\site-packages\guitarpro\iobase.py", line 35, in read
data = self.data.read(count)
AttributeError: 'Song' object has no attribute 'read'
Looking at the the examples provided, e.g. this one. I don't think you need this portion.
song = guitarpro.gp5.GP5File(parsed_song,encoding='UTF-8')
The following should be enough, as parse already calls readSong here.
song = guitarpro.parse('wet_sand.gp5')
Finally it looks like the file-format is automatically determined by parse here.
As an example you could do something like this.
import guitarpro
song = guitarpro.parse('test.gp5')
for track in song.tracks:
for measure in track.measures:
for voice in measure.voices:
for beat in voice.beats:
for note in beat.notes:
print(note.durationPercent)
print(note.effect)

Why would inspect.getfile give me a file that's not there?

Or, Saltstack + docker-py AttributeError: 'RecentlyUsedContainer' object has no attribute 'lock'
I have been digging into this issue to no avail. I'm trying to use SaltStack to manage my docker images/containers but ran into this problem.
Initially I was using the salt state docker.running but that presented as the command does not exist. When I changed the state to docker.running, I got the traceback I posted over at that GitHub issue:
ID: scheduler
Function: docker.pulled
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/state.py", line 1563, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/dist-packages/salt/states/dockerio.py", line 271, in pulled
returned = pull(name, tag=tag, insecure_registry=insecure_registry)
File "/usr/lib/python2.7/dist-packages/salt/modules/dockerio.py", line 1599, in pull
client = _get_client()
File "/usr/lib/python2.7/dist-packages/salt/modules/dockerio.py", line 277, in _get_client
client._version = client.version()['ApiVersion']
File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 837, in version
return self._result(self._get(url), json=True)
File "/usr/local/lib/python2.7/dist-packages/docker/clientbase.py", line 86, in _get
return self.get(url, **self._set_request_timeout(kwargs))
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 310, in get
#: Stream response content default.
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 279, in request
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 374, in send
url=request.url,
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 155, in send
**proxy_kwargs)
File "/usr/local/lib/python2.7/dist-packages/docker/unixconn/unixconn.py", line 74, in get_connection
with self.pools.lock:
AttributeError: 'RecentlyUsedContainer' object has no attribute 'lock'
Started: 09:33:42.873628
Duration: 22.115 ms
After searching Google a bit more and coming up with nothing, I went ahead and started reading the source.
After reading unixconn.py and realizing that RecentlyUsedContainer was coming from urllib3, I went and tracked down the source for that and discovered that there was a _lock attribute that was changed to lock a while ago. That seemed strange.
I looked closer at the imports and realized that unixconn.py was attempting to use requests' built-in urllib3 and then falling back to the stand alone urllib3. So I checked out the requests urllib3 and found that it did, indeed have the _lock -> lock change. But it was newer than my version of requests. So I upgraded requests and tried again. Still no dice - same AttributeError.
Now things start to get weird.
In order to get information back to my salt master, I started mucking with the docker-py and urllib3 code on my salt minion. At first I raised exceptions with urllib3.__file__ to make sure I was using the right file. But occasionally the file name that it would return was in a file and a folder that did not exist. Usually it was displaying /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/_collections.pyc, but when I would delete that file thinking that maybe the .pyc being cached was causing a problem it would still say that was the __file__, even though it didn't exist.
Then I discovered inspect.getfile. And I got the same bizarre behavior - I could delete the .pyc file and yet inspect.getfile(self.pools) would return the non-existent file.
To make life even better, I've added
raise Exception('Pining for the Fjords')
to
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/_collections.py
At the end of the RecentlyUsedContainer.__init__. Yet that exception does not raise.
And I have just confirmed that something is in fact lying to me, because despite changing unixconn.py
def get_connection(self, url, proxies=None):
import inspect
r = RecentlyUsedContainer(10)
raise Exception(inspect.getfile(r.__class__) + '\n' + r.__doc__)
which returns /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/_collections.pyc, when I go edit that .pyc and modify the RecentlyUsedContainer's docstring I get the original docstring.
And finally, when I edit /usr/lib/python2.7/dist-packages/urllib3/_collections.pyc and change it's docstring, (or the same path but _collections.py instead)...
I still get the same docstring!
Why is the wrong code getting executed here, and how can I find out where it is so I can fix the problem?
So I finally figured out the problem:
It did have something to do with salt. For some reason the way the salt minion imported the docker-py library it did some sort of... partial hold on the imports. I suspect that what was happening was that salt was re-importing just the docker-py library specifically so when I would make changes to those files the changes would show up.
However, since the Python import mechanism will search for pre-imported modules first the urllib3 code was never re-imported.
Ultimately all that is required is to restart the salt minion:
salt 'my-minion' cmd.run "nohup /bin/sh -c 'sleep 10 && salt-call --local service.restart salt-minion'"

Categories