remix-shell / remix.py

#!/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 cmd
import os.path
import subprocess
import tempfile
import glob
import types
from optparse import OptionParser

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


usage = '''
%prog [options] [filename]
'''


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


def main(argv=None):
    if argv is None:
        argv = sys.argv
    parser = OptionParser()
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="try to suppress messages")
    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
    
    (options, args) = parser.parse_args()
    
    r = Remix()
    r.options = options
    r.args = args
    r.cmdloop()


class Remix(cmd.Cmd):
    """Simple command processor example."""
    
    prompt = "(no file) > "
    currfile = None
    currfilename = ""
    cwd = ""
    env = dict()
    renderable = None
    renderablename = ""
    options = dict()
    args = list()
    
    def do_EOF(self, line):
        return True
    
    def preloop(self):
        if self.args:
            self.do_load(self.args[0])
    
    def postloop(self):
        print
    
    def precmd(self, line):
        # print line
        self.cwd  = os.getcwd()
        return line
    
    def default(self, line):
        """execute a command"""
        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['analysis'] = a.analysis
            self.env['_'] = None
    
    def complete_load(self, text, line, begidx, endidx):
        l = line.split(None, 1)[1]
        wav = [os.path.basename(f) for f in glob.glob("%s*.wav" % l)]
        mp3 = [os.path.basename(f) for f in glob.glob("%s*.mp3" % l)]
        dirs = [os.path.basename(d) for d in glob.glob("%s*" % l) if os.path.isdir(d)]
        return mp3 + wav + dirs
    
    def do_save(self, line):
        if not line:
            print "missing filename"
            return
        self.renderable.encode(line)
        print "saved as " + os.path.abspath(os.path.join(os.getcwd(), line))
    
    def execute(self, rawcmd):
        try:
            result = eval(rawcmd, globals(), self.env)
        except:
            print "syntax error or file not found"
            return
        if isinstance(result, tuple) or isinstance(result, dict) or isinstance(result, types.StringTypes):
            print result
            return
        try:
            if not isinstance(result, audio.AudioRenderable):
                self.renderable = audio.AudioQuantumList(result)
            else:
                self.renderable = result
            self.renderablename = ""
            self.env['_'] = self.renderable
        except TypeError:
            print result


if __name__ == "__main__":
    sys.exit(main())
    # Remix().cmdloop()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.