python


24
Jan 09

Networked Sound Board

Hi Everybody,

I’ve created a network sound board that you can use to have endless fun with co-workers.

In my office quad we have one OSX machine that is used to play music for everyone, it’s usually running last.fm, pandora or someones iTunes library as background music for everyone. Occasionally it gets cranked up when it’s time to get the led out. I was thinking that it’d be fun to be able to trigger sound effects on that machine from my machine, kind of like what happens on radio shows, expect that my co-workers wouldn’t really be able to change the channel.

So the itch was scratched and I’m proud to present the network sound board. It should run out of the box on any OSX machine with a recent installation of Python. If you’re on Windows or Linux it’ll work if you can find a command line audio player.  Anybody on the same network as the music machine will be able to trigger the sound effects from the comfort of their browsers. After you install there is a soundEffects folder that you can place sound files (.wav/mp3) into and they are instantly available, check the documentation for more info.

You can git the source from github at http://github.com/code128/networkedsoundboard/tree/master

It looks like this.

networked_soundboard

If you’re looking to extend it, adding the ability to upload new sounds from the flex interface would be sweet. If you do let me know.

Have fun.

P.S. If you can get samples of your co-workers saying things and add them to the server that would just be the icing on the comedy cake.


22
Oct 08

Iterating over a custom object in python

A coworker recently needed to iterate over a custom object in python. It’s pretty easy to do, you just need to implement the __iter__ method on your object.

Here’s some example code that shows you how to extend your object, returning everything in your objects local dictionary:

class IterableObject(object):
    def __iter__(self):
        for item in self.__dict__:
            yield self.__dict__[item]

Now for sample usage:

myObj = IterableObject()
myObj.name = "Johnny Hammersticks"
myObj.otherProperty = "Something Else"
myObj.testList = [1,2,3,4]
myObj.testDict = {1:'one', 2:'two'}
# Serialize the IterableObject into json
for x in myObj:
     print x, type(x)

which returns:

Something Else <type 'str'>
{1: 'one', 2: 'two'} <type 'dict'>
[1, 2, 3, 4] <type 'list'>
Johnny Hammersticks <type 'str'>

Oh and another handy feature of this dictionary style approach, you can do easy string formatting/printing of the object properties in this style.

print "Hi %(name)s, your list %(testList)s" % myObj.__dict__

Which prints:

Hi Johnny Hammersticks, your list: [1, 2, 3, 4]

20
Oct 08

FlixBot

I’ve built a proof of concept in some hacked together python code to automatically add movies to my netflix queue when I send twitter messages to @flixbot.

For example this tweet:

Gets Blade into my queue. Awesome.

I started building this out into a full fledged service so other people can use it as well. Of course I’m going to need a hosted site somewhere for people to sign up. I figured it might be a good time to play with my app engine account.

I got part of the way of there with app engine serving up pages, but then ran into problems with xml libraries I was using in my POC not existing in the AppEngine sandbox. :(

Also I’m starting to run out of enthusiasm.

So that’s where I’m at. Goodnight.


21
Jan 08

Duplicate music file finder code.

I’ve been consolidating my music collection and found that there were lots of duplicate files.

Most of the dupes were named something like “Happy Birthday 1.mp3″ and “Happy Birthday.mp3″ would exist in the same directory. I’m not sure which program added these dupes, but removing 2500 or so of em by hand would not be fun.

Without further ado, here’s some python code that takes care of that problem for you. It only examines the filename, not the date or the bitrate or the actual file contents, etc. But you could of course extend it to do all those things.

Enjoy.

#-------------------------------------------------------------------------------
# Name:        cleanDuplicateMusicFiles.py
# Purpose:     Loops over a directory structure looking for 'duplicate' music files
#				and moving them to a safe directory for deletion.
#
# Author:      Joshua Bloom
#
# Created:     01/18/2008
#-------------------------------------------------------------------------------
#!/usr/bin/env python
 
import os
import sys
 
dupList = []
rootDirectory = "/Users/joshbloom/Music/iTunes/iTunes Music"
sequesteredFilesDirectory = "/Users/joshbloom"
 
def main():
    print "Starting search ..."
    checkDir(rootDirectory)
    print "Found %s dupes" % len(dupList)
 
def checkDir(path):
    print "Checking path '%s' for duplicates" % os.path.basename(path)
    for item in [ os.path.join(path, x) for x in os.listdir(path) ]:
        if os.path.isdir(item):
            checkDir(item)
        else:
            checkForDupe(item)
 
def checkForDupe(fName):
	'''Example: if we find 'Happy Birthday 1.mp3' and 'Happy Birthday.mp3' exists in the
	same directory we consider this a duplicate and send it for re-education. '''
    fileName = os.path.basename(fName)
    folderList = os.listdir(os.path.dirname(fName))
    if fileName.endswith("1.mp3"):
        for otherName in folderList:
            if otherName != fileName: #Make sure we aren't comparing with the current file
                if os.path.basename (otherName).startswith(fileName[:-6]):
                    #This is a duplicate
                    dupList.append(fName)
                    sequesterDup(fName)
 
def sequesterDup(fName):
    ''' Move em to a new folder, if you were confident you could change
 		this function to delete the file. '''
    try:
        print "Moving file: %s" % fName
        os.rename(fName, os.path.join(sequesteredFilesDirectory, os.path.basename(fName)) )
    except Exception, E:
        print E
 
if __name__ == '__main__':
    main()

20
Jul 07

Auto twitter SMS on/off

So I’ve spent a little more time thinking about this and have decided this utility would be better as a server utility that sits out in the cloud and monitors for my computer activity. If it doesn’t see activity for some set period it notifies twitter to re-enable SMS messages.
This takes care of any issues with me shutting down or closing my laptop/computer before my notifier can get its message out.

I’m thinking a python script, called by cron that checks for an indication that I’m active on my computer, if it doesn’t see the indication after some number of tries it turns SMS notifications on. That part seems pretty solid, what should I use on the laptop to signal my presence? If this was a Windows machine I’d be off and running but I’ve recently switched to a Mac and I don’t know the platform very well. Instant messenger sounds like something to tap into as it already has the concept of active/idle built into it, but I’m using Adium and it seems like Adium plug-ins are written in Objective-C which is totally foreign to me.

I think it’s time for some googling…


6
Jun 07

Convert m4a to mp3

I’ve been moving a bunch of my brothers music out of iTunes for him so he can use it with portable players besides iPod. Unfortunately he encoded a lot of his cd’s in .m4a format. I found a decent utility for converting to mp3 (and other formats) http://www.bonkenc.org/

Unfortunately when you point Bonk at a directory full of m4a’s it crashes on certain files for some reason (encoding issues probably.) After the crash you need to setup all of your settings and add the files again, which is really time consuming and annoying.

To make this easier I whipped up a short python script that calls Bonk for you on each file, if it runs into a bad file it will rename the file for you so you don’t try to process it again.

Here’s the python code:

import os
import pprint
import subprocess
curDir = os.getcwd() # The current directory. This should contain your .m4a files
pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives
problemFiles = [] #A list of files that failed conversion
#
for item in os.listdir(curDir):
	if item.upper().endswith('.M4A'):
		fullPath = os.path.join(curDir,item)
		cmd = '"%s" -e LAME -d "%s" "%s"' #The command to convert a single file
		cmd = cmd % (pathToBonk, curDir, fullPath)
		val = subprocess.call(cmd)
		if val == 0: #Successfull conversion, delete the original
			os.remove(fullPath)
		else:
			problemFiles.append(fullPath)
			print 'Problem converting %s' % item
			os.rename(fullPath, fullPath + ".BAD")
print 'These files had problems converting and have been renamed with .BAD extensions:'
pprint.pprint(problemFiles)

NOTES: This will delete the .m4a file after converting it. If you want to keep your old files for some reason make sure to run this on a copy of your files. IE in a different directory.


4
Apr 07

Count the duplicates in a Python List

Here’s a nice little function I’ve written to report the number of duplicates in a python list.

from sets import Set
#
def countDuplicatesInList(dupedList):
   uniqueSet = Set(item for item in dupedList)
   return [(item, dupedList.count(item)) for item in uniqueSet]
#
lst = ['I1','I2','I1','I3','I4','I4','I7','I7','I7','I7','I7']
print countDuplicatesInList(lst)

The Set datatype is an unordered set that doesn’t allow duplicates, so the first line in the function adds each item in the original list to the Set. The set automatically throws out duplicates so we end up with a unique list.
The next line creates a tuple of the unique item name and its count in the original list.

The output of the function will look like this:

[('I1', 2), ('I3', 1), ('I2', 1), ('I4', 2), ('I7', 5)]

14
Feb 07

A Million Monkeys making Shakespeare?

So I had a little time on my hands and thought it might be fun to get to the bottom of this Infinite Monkeys and Shakespeare dillema.

Here’s some python code that tries to randomly write the line “Alas, poor Yorick, I knew him, Horatio.” To make it easier I’ve ignored punctuation and case but still, you’re gonna need a lot of monkeys to get this level of randomness to happen.

#-------------------------------------------------------------------------------
# Name:        CreateShakespeare.py
# Purpose:     Simulate lots of monkeys banging on typewriters. Find out how long
#               it takes to create shakespeare. To make it easy we just want our
#               monkeys to write the line
#               "Alas, poor Yorick, I knew him, Horatio"
#               And we'll ignore the punctuation and case to make it easier for
#               our tireless computer monkeys.
#
# Author:      jbloom
#
# Created:     07/11/2006
#-------------------------------------------------------------------------------
import random
import string
import time
 
correctText = 'Alas poor Yorick I knew him Horatio'
charList = string.ascii_uppercase + ' '
startTime = time.localtime()
endTime = None
currentLoopCounter = 0
 
def getRandomCharacter():
    return charList[random.randrange(0,27)]
 
def createRandomLine():
   '''Creates the Random Line by monkey power'''
   randomLine = []
   for char in xrange(len(correctText)):
   randomLine.append(getRandomCharacter())
   return ''.join(randomLine)
 
def testLine(inputLine):
    '''Tests the passed line to see if we got the correct text '''
    if inputLine == correctText.upper():
        return True
    else:
        return False
 
if __name__ == "__main__":
    #print testLine('ALAS POOR YORICK I KNEW HIM HORATIO')
    while True:
       currentLoopCounter += 1
       line = createRandomLine()
       if testLine(line) == True:
           endTime = time.localtime()
           print ('')
           print ('Started: %s' % startTime)
           print ('Ended  : %s' % endTime)
           print ('Total Iterations: %s' % currentLoopCounter)
           print ('MONKEY  LINE: %s' % line)
           print ('DESIRED LINE: %s' % correctText)
           break
      else:
           print line, currentLoopCounter

18
Jan 07

Kodak Gallery RipAndZipper

After my recent wedding Jody and I were getting lots of invitations to view Kodak Easy Share photo galleries.

Unfortunately there is no ability to download quality copies of the images you are looking at.

Fortunately however I know me some intarweb. So without further ado I am happy to introduce RipAndZipKodakGallery.

Basically this a command anyone can use to rip through any Kodak gallery and create a Zip file of all the pictures and download it to your computer.

How do I use it?

The easiest way to use it is with this bookmarklet: RipAndZipKodak

  • To install you simply drag the bookmarklet onto your browsers bookmark toolbar.
  • To use the bookmarklet you simply press the button when you are viewing the gallery. Thats it.

Another way to use it is through the YubNub interface

  • From the YubNub command line you enter this command:
  • RipZipKodakGallery http://www.kodakgallery.com/Slideshow.jsp?Uc=plr4ibx.lk0n0q9&Uy=cmi7nr
  • Replace http://… with the url for the gallery you want to RipAndZip

25
Sep 06

Python reverse string method

Saw this easy way to reverse a string in python today, over at Answer My Searches

Here’s how to do it:

exampleString = 'Hey there fancy pants'
reversedString = exampleString[::-1]
print reversedString
>> stnap ycnaf ereht yeH

This works because a String is a sequence type in python and you can apply all the ’slicing’ syntax you want to it. So in this case [::-1] is saying, taking the string sequence start from the beginning ‘:’ go to the end ‘:’ and step through it in reverse (-1).