Source

remix-shell / remix.py

Full commit
#!/usr/bin/env python
# encoding: utf-8
"""
shell.py

Created by Adam on 2009-11-22.
Copyright (c) 2009 . All rights reserved.
"""

import sys
import getopt
import cmd
import os.path
import subprocess
import tempfile
import glob

from echonest import audio
from echonest.selection import *
from echonest.sorting import *


help_message = '''
The help message goes here.
'''


class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg


def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "ho:v", ["help", "output="])
        except getopt.error, msg:
            raise Usage(msg)
    
        # option processing
        for option, value in opts:
            if option == "-v":
                verbose = True
            if option in ("-h", "--help"):
                raise Usage(help_message)
            if option in ("-o", "--output"):
                output = value
    
    except Usage, err:
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2

#
class Remix(cmd.Cmd):
    """Simple command processor example."""
    
    prompt = "(no file) > "
    currfile = None
    currfilename = ""
    cwd = ""
    env = dict()
    renderable = None
    renderablename = ""
    
    def do_EOF(self, line):
        return True
    
    def postloop(self):
        print
    
    def precmd(self, line):
        # print line
        self.cwd  = os.getcwd()
        return line
    
    def default(self, line):
        """execute a command"""
        if os.path.exists(os.path.join(self.cwd, line)):
            self.load(os.path.join(self.cwd, line))
        else:
            self.execute(line)
    
    def do_play(self, line):
        """plays the current buffer or a given filename"""
        if not line:
            if self.renderable and not self.renderablename:
                foo, line = tempfile.mkstemp(".wav")
                self.renderablename = line
                self.renderable.encode(self.renderablename)
            elif self.renderablename:
                line = self.renderablename
        if not line:
            print "nothing to play"
            return
        CMD = ["qlmanage", '-p', line]
        pid=subprocess.Popen(CMD, stderr=subprocess.PIPE).pid
        
    def do_load(self, path):
        if os.path.isdir(path):
            self.cwd = os.path.abspath(path)
            os.chdir(self.cwd)
        else:
            try:
                a = audio.LocalAudioFile(path)
                self.env['afile'] = a
            except:
                print "unable to load %s" % path
                return
            self.currfilename = os.path.abspath(path)
            self.prompt = "%s > " % os.path.basename(self.currfilename)
            self.renderable = a
            self.renderablename = self.currfilename
            self.env['segments'] = a.analysis.segments
            self.env['sections'] = a.analysis.sections
            self.env['beats'] = a.analysis.beats
            self.env['bars'] = a.analysis.bars
            self.env['tatums'] = a.analysis.tatums
            self.env['_'] = None
    
    
    
    def complete_load(self, text, line, begidx, endidx):
        wav = glob.glob("%s*.wav" % text)
        mp3 = glob.glob("%s*.mp3" % text)
        dirs = [d for d in glob.glob("%s*" % text) if os.path.isdir(d)]
        return mp3 + wav # + dirs
    
    def execute(self, rawcmd):
        try:
            self.renderable = eval(rawcmd, globals(), self.env)
        except:
            print "syntax error or file not found"
        self.renderablename = ""
        if not isinstance(self.renderable, audio.AudioRenderable):
            self.renderable = audio.AudioQuantumList(self.renderable)
        self.env['_'] = self.renderable



if __name__ == "__main__":
    # sys.exit(main())
    Remix().cmdloop()