Python Script, Upload Images To Imgur

lxskllr

No Lifer
Nov 30, 2004
58,553
8,833
126
I used a script to upload images to Imgur through Nautilus. It worked pretty well, and was very convenient. I'm now using Thunar, and while I can get the script to work, I don't get the notification of success or failure like I got when using it in Nautilus.

I know nothing about Python, but looking at the script, I don't see the mechanism it used to popup notifications. Do any of you see where that happens? Here's the script I'm using...

Code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pycurl
import xml.dom.minidom
import StringIO
import sys
import gtk
import os
import imghdr
import locale
import gettext
try:
	import pynotify
except:
	print "Install pynotify. It's whoasome!"
	
APP="Imgur Uploader"
DIR="locale"

locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
_ = gettext.gettext

##STRINGS
notimg = _("is not an image.")
notallowed = _("is not an allowed file type. Skipping.")
uploading = _("Uploading")
oneimage = _("1 image has been uploaded.")
multimages = _("images have been uploaded.")
uploadfailed = _("Unable to upload")

class Uploadr:
	def __init__(self, args):
		
		self.allowedTypes = ("jpeg", "jpg", "gif", "png", "apng", "tiff", "bmp", "pdf", "xcf")
		self.images = []
		self.urls = []
		self.broadcasts = []
		if len(args) == 1:
			return
		else:
			for file in args:
				if file == args[0] or file == "":
					continue
				self.type = imghdr.what(file)
				if not self.type:
					self.broadcasts.append(file+" "+notimg)
				else:
					if self.type not in self.allowedTypes:
						self.broadcasts.append(self.type+" "+notallowed+file)
					else:
						self.images.append(file)
		for file in self.images:
			self.upload(file)
			
		self.setClipBoard()
		
		self.broadcast(self.broadcasts)
		
	def broadcast(self, l):
		try:
			str = '\n'.join(l)
			n = pynotify.Notification(str)
			n.set_urgency(pynotify.URGENCY_LOW)
			n.show()
		except:
			for line in l:
				print line
		
		
	def upload(self, file):
		c = pycurl.Curl()
		
		values = [
				("key", "e85c0044b9222bc9a2813679a452f54f"),
				("image", (c.FORM_FILE, file))]
				
		buf = StringIO.StringIO()
		
		c.setopt(c.URL, "http://imgur.com/api/upload.xml")
		c.setopt(c.HTTPPOST, values)
		c.setopt(c.WRITEFUNCTION, buf.write)
		
		if c.perform():
			self.broadcasts.append(uploadfailed+" "+file+".")
			c.close()
			return

		self.result = buf.getvalue()
		c.close()

		doc = xml.dom.minidom.parseString(self.result)

		self.urls.append(doc.getElementsByTagName("original_image")[0].childNodes[0].nodeValue)
		
	def setClipBoard(self):
		c = gtk.Clipboard()
		c.set_text('\n'.join(self.urls))
		c.store()
		if len(self.urls) == 1:
			self.broadcasts.append(oneimage)
		elif len(self.urls) != 0:
			self.broadcasts.append(str(len(self.urls))+" "+multimages)

if __name__ == '__main__':
	uploadr = Uploadr(sys.argv)

and the whole package for anyone interested...

http://www.omgubuntu.co.uk/2010/11/quickly-upload-images-to-imgur-via-nautilus/
 

Jodell88

Diamond Member
Jan 29, 2007
8,762
30
91
The broadcast function is what is used to send the notifications. It depends on "pynotify"
 

lxskllr

No Lifer
Nov 30, 2004
58,553
8,833
126
For Arch Linux it is packaged as "python-notify".

Hmm... That's already installed. pynotify would have to hand that off to the Gnome notification-daemon, right? I don't see where that's happening. The Xfce equivalent would be notification-daemon-xfce
 

zokudu

Diamond Member
Nov 11, 2009
4,364
1
81
Hmmm I got this from here: http://forums.debian.net/viewtopic.php?f=8&t=49504

but this worked to send an alert.

Code:
#/usr/bin/python
import pynotify
try:
    import pynotify
    if pynotify.init("My Application Name"):
        Alert = pynotify.Notification("Alert Notification", "A Message From Your Applicaton")
        Alert.show()
    else:
        print "Error starting pynotify"
except:
    print "pynotify not installed"

Any help?

EDIT:

Looking at the script code (Beware I don't know python) I think the broadcast command is a method hes calling.
Code:
def broadcast(self, l):
		try:
			str = '\n'.join(l)
			n = pynotify.Notification(str)
			n.set_urgency(pynotify.URGENCY_LOW)
			n.show()
		except:
			for line in l:
				print line

Do you have the xfce notifications installed? I don't think notification-daemon works in xfce.
xfce4-notifyd
or
notification-daemon-xfce
 
Last edited:

lxskllr

No Lifer
Nov 30, 2004
58,553
8,833
126
Hmmm I got this from here: http://forums.debian.net/viewtopic.php?f=8&t=49504

Do you have the xfce notifications installed? I don't think notification-daemon works in xfce.
xfce4-notifyd
or
notification-daemon-xfce

Thanks for the info. It isn't an immediate help, but it gives me something to think about. This returns a notification on my system...

Code:
notify-send --icon=gtk-add Test "This is a test notification"

zf21Z.png


Honestly, the script works for my purposes, but this is an interesting problem for me, and it's simple enough that I can tackle it. My programming experience is very limited, so it's all kind of foreign, but it's still attainable. I may try rewriting the whole thing, and see if I can output notifications to xcowsay. That would amuse me :^)
 

zokudu

Diamond Member
Nov 11, 2009
4,364
1
81
To print to xcowsay in python just do:
Code:
from subprocess import call
call(["xcowsay", "Message Here"])

Should be able to put that in for the pynotify commands and display the str variable. (I think)

So replace the broadcast method with:
Code:
def broadcast(self, l):
		try:
			str = '\n'.join(l)
			call(["xcowsay", str])
		except:
			for line in l:
				print line
and add:
Code:
from subprocess import call

to the import calls. (I think worth a shot I think)
 
Last edited:

lxskllr

No Lifer
Nov 30, 2004
58,553
8,833
126
You're the man zokudu!

This is the code that works...

Code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pycurl
import xml.dom.minidom
import StringIO
import sys
import gtk
import os
import imghdr
import locale
import gettext

try:
	import pynotify
except:
	print "Install pynotify. It's whoasome!"

from subprocess import call

	
APP="Imgur Uploader"
DIR="locale"


locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain(APP, DIR)
gettext.textdomain(APP)
_ = gettext.gettext

##STRINGS
notimg = _("is not an image.")
notallowed = _("is not an allowed file type. Skipping.")
uploading = _("Uploading")
oneimage = _("1 image has been uploaded.")
multimages = _("images have been uploaded.")
uploadfailed = _("Unable to upload")

class Uploadr:
	def __init__(self, args):
		
		self.allowedTypes = ("jpeg", "jpg", "gif", "png", "apng", "tiff", "bmp", "pdf", "xcf")
		self.images = []
		self.urls = []
		self.broadcasts = []
		if len(args) == 1:
			return
		else:
			for file in args:
				if file == args[0] or file == "":
					continue
				self.type = imghdr.what(file)
				if not self.type:
					self.broadcasts.append(file+" "+notimg)
				else:
					if self.type not in self.allowedTypes:
						self.broadcasts.append(self.type+" "+notallowed+file)
					else:
						self.images.append(file)
		for file in self.images:
			self.upload(file)
			
		self.setClipBoard()
		
		self.broadcast(self.broadcasts)
		
	def broadcast(self, l):
		try:
			str = '\n'.join(l)
			call(["xcowsay", str])
		except:
			for line in l:
				print line
		
		
	def upload(self, file):
		c = pycurl.Curl()
		
		values = [
				("key", "e85c0044b9222bc9a2813679a452f54f"),
				("image", (c.FORM_FILE, file))]
				
		buf = StringIO.StringIO()
		
		c.setopt(c.URL, "http://imgur.com/api/upload.xml")
		c.setopt(c.HTTPPOST, values)
		c.setopt(c.WRITEFUNCTION, buf.write)
		
		if c.perform():
			self.broadcasts.append(uploadfailed+" "+file+".")
			c.close()
			return

		self.result = buf.getvalue()
		c.close()

		doc = xml.dom.minidom.parseString(self.result)

		self.urls.append(doc.getElementsByTagName("original_image")[0].childNodes[0].nodeValue)
		
	def setClipBoard(self):
		c = gtk.Clipboard()
		c.set_text('\n'.join(self.urls))
		c.store()
		if len(self.urls) == 1:
			self.broadcasts.append(oneimage)
		elif len(self.urls) != 0:
			self.broadcasts.append(str(len(self.urls))+" "+multimages)

if __name__ == '__main__':
	uploadr = Uploadr(sys.argv)

I inserted this after the pynotify import...

Code:
from subprocess import call

and replaced broadcast method as you said.

The cow pops up as expected, and while I haven't tried all circumstances, it errors out on an unsupported image, and gives a success notice on image upload.

Thanks a ton. I think I might try to learn a little Python. It doesn't look too hard to learn, and seems like it would be useful for stupid little things like this :^)

Edit:
The script in action...

00v53.jpg
 
Last edited:

zokudu

Diamond Member
Nov 11, 2009
4,364
1
81
Np. I've done some coding in Java for my IS major it translated decently. I'm glad the script is working for you though.

From what I've heard Python is very "natural" in that it sounds very much like spoken english when coding and is good for beginners. Like notice on the pynotify import try statement where it prints
Code:
print "Install pynotify. It's whoasome!"

In Java that line is:
Code:
System.out.print("Install pynotify. It's whoasome!");

I think most colleges only use Java because it is usable very easily on windows though tbh I've never tried to program in Python so maybe there's an implementation I don't know about.

Also I think you can remove the pynotify import as well because its usage was removed but if it ain't broke I wouldn't bother fixing it.
 
Last edited: