Converting python2 PIL to python3 code - python

A program I'm trying to convert from python2 to python3 uses PIL the python image library.
I try to download a thumbnail from the web to display within a tkinter style gui. Here is, what I think, the offending line of code:
# grab the thumbnail jpg.
req = requests.get(video.thumb)
photo = ImageTk.PhotoImage(Image.open(StringIO(req.content)))
# now this is in PhotoImage format can be displayed by Tk.
plabel = tk.Label(tf, image=photo)
plabel.image = photo
plabel.grid(row=0, column=2)
The program stops and gives a TypeError, here is the backtrce:
Traceback (most recent call last): File "/home/kreator/.local/bin/url-launcher.py", line 281, in <module>
main()
File "/home/kreator/.local/bin/url-launcher.py", line 251, in main
runYoutubeDownloader()
File "/home/kreator/.local/bin/url-launcher.py", line 210, in runYoutubeDownloader
photo = ImageTk.PhotoImage(Image.open(StringIO(req.content)))
TypeError: initial_value must be str or None, not bytes
How do I satisfy python3's requirements here?

In this case you can see that the library you have imported doesn't support Python3. This isn't something you can fix from within your own code.
The lack of Python3 support is because PIL has been discontinued for quite some time now. There is a fork that's actively maintained that I would recommend you use instead: https://pillow.readthedocs.io/
You can download it from pypi.

Related

When opining a PDF with Python tkPDFViewer throws an error, is there an mistake I'm not seeing?

When testing the opening of a PDF for a larger project the code throws an error. The error emanates from the tkPDFViewer.
Any ideas?
Here is the error:
Exception in thread Thread-1 (add_img): Traceback (most recent call last):
File "C:\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run()
File "C:\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, *self._kwargs)
File "C:\Python\Python310\lib\site-packages\tkPDFViewer\tkPDFViewer.py", line 46, in add_img
pix = page.getPixmap()
AttributeError: 'Page' object has no attribute 'getPixmap'. Did you mean: 'get_pixmap'?
import tkinter as tk
from tkPDFViewer import tkPDFViewer as pdf
print('Starting TestPDF2')
mainWindow = tk.Tk()
# Set the width and height of our root window.
mainWindow.geometry("550x750")
# creating object of ShowPdf from tkPDFViewer.
v1 = pdf.ShowPdf()
# Adding pdf location and width and height.
v2 = v1.pdf_view(mainWindow, pdf_location = 'testpdf.pdf', width = 50, height = 100)
# Placing Pdf in my gui.
v2.pack()
mainWindow.mainloop()
print('End TestPDF2')
This is an internal problem with tkPDFViewer. The error is quite self-explanatory - getPixmap was deprecated and removed in favor of get_pixmap in one of the dependencies of tkPDFViewer (see here). So the library needs to get fixed (the methods need to be renamed to match the new version) and it doesn't look very well maintained. You can try opening an issue or a PR on its GitHub. But I'd probably lean towards saying this library is dead and broken, and finding yourself an alternative that works.

Get a list of YouTube Music library uploads with ytmusicapi

I need to get a list of all albums of my YouTube Music uploads library with ytmusicapi and I never work with Python before. I created the headers_auth.json and a test.py file with the following code from the example:
from ytmusicapi import YTMusic
ytmusic = YTMusic('headers_auth.json')
playlistId = ytmusic.create_playlist("test", "test description")
search_results = ytmusic.search("Oasis Wonderwall")
ytmusic.add_playlist_items(playlistId, [search_results[0]['videoId']])
I ran from the Ubuntu terminal: python /home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py
Result error:
Traceback (most recent call last): File
"/home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py", line 1, in
from ytmusicapi import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/init.py",
line 2, in
from ytmusicapi.ytmusic import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/ytmusic.py",
line 28
auth: str = None,
^ SyntaxError: invalid syntax
How to fix that?
This is because you are using a different version of Python.
The library you are using requires Python>=3.5 wheraas you seem to be using Python2.
If you are curious this code
def f(x:int):
return
is valid in Python3.5+ versions but not in Python2.
You will have to either switch to Python3 to use that library or else you can clone the repo and convert the whole repo to Python2 using something like this(though there might be other ways too).
I'd recommend you simply switch to Python3.5 or higher.

How to save an Image locally using PIL

I am making a program that builds a thumbnail based on user input, and I am running into problems actually saving the image. I am used to C++ where you can simply save the image, it seems that python does not support this.
This is my code right now:
def combine(self):
img = Image.new("RGBA", (top.width,top.height+mid.height+mid.height),(255,255,255))
img.paste(top, (0,0))
img.paste(mid, (0,top.height))
img.paste(bot, (0,top.height+mid.height))
img.show()
img.save("Thumbnail.png", "PNG")
The error that shows up when I run it is :
Traceback (most recent call last):
File "TextToThumbnail.py", line 4, in <module>
class Thumbnail(object):
File "TextToThumbnail.py", line 461, in Thumbnail
img.save("Thumbnail.png", "PNG")
NameError: name 'img' is not defined
What is going on? Preferably I just want to be able to save the image locally, since this program will be running on multiple setups with different pathways to the program.

uTorrent Automation using pywinauto

I am trying out an utorrent automation using pywinauto lib. I want to add a torrent with URL. This option is under the file menu. I can get as far as opening uTorrent and then nothing happens. I used Swapy for generating this code. The box below opens only when I run the code in swapy. But when I save it into a file and run with cmd, only utorrent opens and a traceback occurs in the cmd.
from pywinauto.application import Application
app = Application().Start(cmd_line=u'"C:\\Users\\User\\AppData\\Roaming\\uTorrent\\u Torrent.exe" ')
torrentdfb = app[u'\xb5Torrent4823DF041B09']
torrentdfb.Wait('ready')
menu_item = torrentdfb.MenuItem(u'&File->Add Torrent from &URL...\tCtrl+U')
menu_item.Click()
app.Kill_()
Traceback:
Traceback (most recent call last):
File "AddTorrent.py", line 5, in <module>
torrentdfb.Wait('ready')
File "C:\Python27\lib\site-packages\pywinauto\application.py", line 380, in Wait
WaitUntil(timeout, retry_interval, lambda: self.__check_all_conditions(check_method_names))
File "C:\Python27\lib\site-packages\pywinauto\timings.py", line 308, in WaitUntil
raise err
pywinauto.timings.TimeoutError: timed out
I am new to python coding and I am not an expert. It would be helpful if you provide the explanation to solve my problem or the code. Thanks!!
uTorrent is spawning another process, this is how I got it:
>>> app.windows_()
[]
>>> app.process
6096
>>> app.connect(title_re=u'^μTorrent.*(build \d+).*')
<pywinauto.application.Application object at 0x000000000405C240>
>>> app.process
4044L
This is a final code working for me (with 32-bit uTorrent and 32-bit Python 2.7):
import pywinauto
app = pywinauto.Application().start(r'uTorrent.exe')
time.sleep(5) # because method connect() has no timeout param yet (planned for 0.6.0)
app.connect(title_re=u'^\u03bcTorrent.*(build \d+).*')
main_window = app.window_(title_re=u'^\u03bcTorrent.*(build \d+).*')
main_window.MenuSelect(u'&File->Add Torrent from &URL...\tCtrl+U')
app.AddTorrentFromURL.Edit.SetText('some URL')
app.AddTorrentFromURL.OK.Click()
Bitness is important. 32-bit uTorrent crashes if I use 64-bit Python.

ID3-mp3 editing in python - up-to-date package?

Edit: Trying to get these libraries to work in python 3.3 was clearly the wrong approach, and my problem now is entirely different so I'll just re-ask it in a new question.
I want to be able to edit ID3 tags of mp3 files with python commands, for example something like setAlbumName("folderPath\song.mp3", "albumname"). So far I've tried Mutagen, PyID3, pytagger, eyeD3, and they all seem to be outdated because the installation fails due to syntax errors. I tried to fix it in eyeD3, but I hit a dead end: http://i41.tinypic.com/o6zklv.png (second screenshot from after I had fixed all the prints and "except Error, e" and so on).
I tried the same with Mutagen, but I ran into a wall there as well when replacing "raise KeyError, key" with "raise KeyError as key" didn't work.
I didn't even know what to make of this one (pytagger): http://i41.tinypic.com/29fz7mh.png
It seems to suggest that there's something wrong with my python installation? Not getting into that.
So, would anyone like to point me to an ID3 package that works, or have a go at fixing an outdated one?
(Also, I tried both "python setup.py install" and "setup.py install" and it seemed to make no difference. I'm on windows 8.)
Edit: From the screenshot below, plus the source code (mutagen with python 2.7.5)
from mutagen.mp3 import MP3
p = "E:\\Musik\\Aeon\\2005 Bleeding the False\\01 Cenobites - Copy.mp3"
audio = MP3(p)
audio["title"] = "An example"
audio.pprint()
audio.save()
_
Traceback (most recent call last):
File "id3tag.py", line 5, in <module>
audio.pprint()
File "C:\Python27\lib\site-packages\mutagen\__init__.py", line 138, in pprint
try: tags = self.tags.pprint()
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 190, in pprint
frames = list(map(Frame.pprint, self.values()))
TypeError: unbound method pprint() must be called with Frame instance as first a
rgument (got str instance instead)
_
from mutagen.mp3 import MP3
p = "E:\\Musik\\Aeon\\2005 Bleeding the False\\01 Cenobites - Copy.mp3"
audio = MP3(p)
audio["title"] = "An example"
audio.save()
_
Traceback (most recent call last):
File "id3tag.py", line 7, in <module>
audio.save()
File "C:\Python27\lib\site-packages\mutagen\__init__.py", line 132, in save
return self.tags.save(filename, **kwargs)
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 370, in save
framedata = [self.__save_frame(frame) for (key, frame) in frames]
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 461, in __save_frame
framedata = frame._writeData()
AttributeError: 'str' object has no attribute '_writeData'
mutagen works great for me with Python 2.7.
examples:
https://code.google.com/p/mutagen/wiki/Tutorial
from mutagen.mp3 import MP3
audio = MP3("example.mp3")
audio["title"] = "An example"
audio.pprint()
audio.save()
p.s. please post code samples so people can help.. not links to screenshots.
p.p.s. it looks like you are trying to install Python2 libs into Python3.
Mutagen also has an EasyID3 tool, which handles simple tasks like changing the file's title:
from mutagen.easyid3 import EasyID3
f = EasyID3("file.mp3")
f["title"] = u"Some title"
f.save()
Works like a charm. But it has very restricted functionality.
See more examples at http://code.google.com/p/mutagen/wiki/Tutorial

Categories

Resources