PageRenderTime 37ms CodeModel.GetById 19ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/shell/remix.py

http://echo-nest-remix.googlecode.com/
Python | 154 lines | 142 code | 4 blank | 8 comment | 0 complexity | 4b5eb69f682219327102b39398653837 MD5 | raw file
  1#!/usr/bin/env python
  2# encoding: utf-8
  3"""
  4shell.py
  5
  6Created by Adam on 2009-11-22.
  7Copyright (c) 2009 . All rights reserved.
  8"""
  9
 10import sys
 11import cmd
 12import os.path
 13import subprocess
 14import tempfile
 15import glob
 16import types
 17from optparse import OptionParser
 18
 19from echonest.audio import *
 20from echonest.audio import AudioQuantumList as aql
 21from echonest.audio import AudioQuantum as aq
 22from echonest.selection import *
 23from echonest.sorting import *
 24
 25
 26USAGE = '''
 27%prog [options] [filename]
 28
 29Optional filename pre-loads the file.
 30'''
 31
 32def main(argv=None):
 33    if argv is None:
 34        argv = sys.argv
 35    parser = OptionParser(usage=USAGE)
 36    parser.add_option("-q", "--quiet",
 37                      action="store_false", dest="verbose", default=True,
 38                      help="try to suppress messages")
 39    parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
 40    
 41    (options, args) = parser.parse_args()
 42    
 43    r = Remix()
 44    r.options = options
 45    r.args = args
 46    r.cmdloop()
 47
 48class Remix(cmd.Cmd):
 49    """Loop while keeping track of the last thing."""
 50    
 51    prompt = "(no file) > "
 52    currfile = None
 53    currfilename = ""
 54    cwd = ""
 55    env = dict()
 56    renderable = None
 57    renderablename = ""
 58    options = dict()
 59    args = list()
 60    
 61    def do_EOF(self, line):
 62        return True
 63    
 64    def preloop(self):
 65        if self.args:
 66            self.do_load(self.args[0])
 67        self.cwd  = os.getcwd()
 68    
 69    def postloop(self):
 70        print
 71    
 72    def default(self, line):
 73        """execute a command"""
 74        self.execute(line)
 75    
 76    def do_play(self, line):
 77        """plays the current buffer or a given filename"""
 78        if not line:
 79            if self.renderable and not self.renderablename:
 80                foo, line = tempfile.mkstemp(".wav")
 81                self.renderablename = line
 82                self.renderable.encode(self.renderablename)
 83            elif self.renderablename:
 84                line = self.renderablename
 85        if not line:
 86            print "nothing to play"
 87            return
 88        CMD = ["qlmanage", '-p', line]
 89        pid=subprocess.Popen(CMD, stderr=subprocess.PIPE).pid
 90        
 91    def do_load(self, path):
 92        """loads the requested file (or directory)"""
 93        if os.path.isdir(path):
 94            self.cwd = os.path.abspath(path)
 95            os.chdir(self.cwd)
 96        else:
 97            try:
 98                self.currfile = LocalAudioFile(path, verbose=self.options.verbose)
 99            except:
100                print "unable to load %s" % path
101                return
102            self.currfilename = os.path.abspath(path)
103            self.prompt = "%s > " % os.path.basename(self.currfilename)
104            self.renderable = self.currfile
105            self.renderablename = self.currfilename
106            self.env['segments'] = self.currfile.analysis.segments
107            self.env['sections'] = self.currfile.analysis.sections
108            self.env['beats'] = self.currfile.analysis.beats
109            self.env['bars'] = self.currfile.analysis.bars
110            self.env['tatums'] = self.currfile.analysis.tatums
111            self.env['analysis'] = self.currfile.analysis
112            self.env['_'] = None
113    
114    def complete_load(self, text, line, begidx, endidx):
115        l = line.split(None, 1)[1]
116        wav = [os.path.basename(f) for f in glob.glob("%s*.wav" % l)]
117        mp3 = [os.path.basename(f) for f in glob.glob("%s*.mp3" % l)]
118        dirs = [os.path.basename(d) + '/' for d in glob.glob("%s*" % l) if os.path.isdir(d)]
119        return mp3 + wav + dirs
120    
121    def do_save(self, line):
122        """saves to the designated filename in the current directory"""
123        if not line:
124            print "missing filename"
125            return
126        if not self.renderable:
127            print "nothing to save"
128        self.renderable.encode(line)
129        print "saved as " + os.path.abspath(os.path.join(os.getcwd(), line))
130    
131    def execute(self, rawcmd):
132        try:
133            result = eval(rawcmd, globals(), self.env)
134        except:
135            print "syntax error"
136            return
137        if isinstance(result, tuple) or isinstance(result, dict) or isinstance(result, types.StringTypes):
138            print result
139            return
140        try:
141            if not isinstance(result, AudioRenderable):
142                self.renderable = AudioQuantumList(result, source=self.currfile)
143                self.renderable.attach(None)
144            else:
145                self.renderable = result
146            self.renderablename = ""
147            self.env['_'] = self.renderable
148        except TypeError:
149            print result
150
151
152if __name__ == "__main__":
153    sys.exit(main())
154    # Remix().cmdloop()