片段音乐歌词生成工具

代码很简单,不再解释了,在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-2 or 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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值