片段音乐歌词生成工具

代码很简单,不再解释了,在mac机上实测通过

import web
from web import form
import tempfile
import urllib2
import subprocess

import os,re,time

def make_text(string):
    return string

urls = ('/', 'tutorial', '/download/(.*)', 'download')
render = web.template.render('templates/')
app = web.application(urls, globals())

def checkurl0(d):
    if d.clipmp3==None: return False
    if d.clipmp3[:7].lower()!="http://": return False
    return True

def checkurl1(d):
    if d.fullmp3==None: return False
    if d.fullmp3[:7].lower()!="http://": return False
    return True

def checkurl2(d):
    if d.fulllyric==None: return False
    if d.fulllyric[:7].lower()!="http://": return False
    return True

my_form = form.Form(
    form.Textbox("clipmp3",description='music clip url:', size=50, id='clipmp3', value='http://localhost:8080/download/4.wav'),
    form.Textbox("fullmp3",description='full music url:', size=50, id='fullmp3', value='http://localhost:8080/download/3.wav'),
    form.Textbox("fulllyric",description='full lyric url:', size=50, id='fulllyric', value='http://localhost:8080/download/1.lrc'),
    validators = [ form.Validator("clip mp3 url illegal", checkurl0),
                  form.Validator("full mp3 url illegal", checkurl1),
                  form.Validator("full lyric url illegal", checkurl2) ]

    )
BUF_SIZE = 262144
class download:
    def GET(self,path):
        try:
            f = open("down/%s"%path, "rb")
            web.header('Content-Type','application/octet-stream')
            web.header('Content-disposition', 'attachment; filename=%s'%path)
            while True:
                c = f.read(BUF_SIZE)
                if c:
                    yield c
                else:
                    break
        except Exception, e:
            print e
            yield 'Error'
        finally:
            if f:
                f.close()
class tutorial:
    def GET(self):
        myform = my_form()
        return render.tutorial(myform, "Please fill song information into form up here.")
    def download(self,var):
        url=self.inp[var]
        mp3file = urllib2.urlopen(url)
        fileext=url.rsplit('.',1)[-1]
        fileext=fileext.split('#?%%&/\\',1)[0]
        self.files[var]='.'.join([self.tmpdir,var,fileext])
        output = open(self.files[var],'wb')
        output.write(mp3file.read())
        output.close()
    def getMp3Data(self):
        self.files={}
        self.download("clipmp3")
        self.download("fullmp3")
        self.download("fulllyric")
    def lyricsparser(self):
        for sentence in file(self.files["fulllyric"]):
            sentence = sentence.strip()
            if len(sentence)==0: continue
            while True:
                timestamp,sentence = re.findall("(?:\[([^\[\]]*)\])?(.*)",sentence)[0]
                if timestamp=="": break
                minv,secv=timestamp.split(':')
                stamp = int(minv)*60+float(secv)
                self.lyric.append((stamp, sentence))
    def unifyFormat(self):
        os.system("sox %s  -r 8000 -e signed-integer -b 16 -c 1 -t raw %s"%( self.files["clipmp3"],
        '/'.join([os.path.dirname(self.files["clipmp3"]),"clipmp3.wav"])))
        os.system("sox %s  -r 8000 -e signed-integer -b 16 -c 1 -t raw %s"%( self.files["fullmp3"],
        '/'.join([os.path.dirname(self.files["fullmp3"]),"fullmp3.wav"])))
    def alignBoundary(self):
        cmd=["/Users/funplus/web/lyrictool/sdhumming", '/'.join([os.path.dirname(self.files["fullmp3"]),"fullmp3.wav"]),
        '/'.join([os.path.dirname(self.files["clipmp3"]),"clipmp3.wav"]) ]
        print "cmd:", cmd
        stpos,dura = subprocess.check_output(cmd).split(",")
        print "result:",stpos,dura
        self.startpos = float(stpos)
        self.dura = float(dura)
    def calcLyric(self):
        self.lyric=[]
        self.lyricsparser()
        strout=""
        for l in self.lyric:
            if l[0]self.startpos+1+self.dura:
                continue
            amendstamp=l[0]-self.startpos
            if amendstamp<0:amendstamp=0
            strout+="[%d:%.2f]%s\n"%(int(amendstamp/60),amendstamp-int(amendstamp/60)*60,l[1])
        return strout
    def POST(self):
        myform = my_form()
        if not myform.validates():
            return "[%s]"%(myform.note)
        self.tmpdir=tempfile.mkdtemp(prefix="funp")
        print "tmpdir",self.tmpdir
        self.inp=web.input()
        lyrc=""
        try:
            self.getMp3Data()
            self.unifyFormat()
            self.alignBoundary()
            lyrc=self.calcLyric()
        finally:
            pass
        os.rmdir(self.tmpdir)
        return make_text(lyrc)

if __name__ == '__main__':
    web.internalerror = web.debugerror
    app.run()


你可能感兴趣的:(算法)