Skip to content

Commit

Permalink
[done] split long text to do multi request
Browse files Browse the repository at this point in the history
  • Loading branch information
eisneim committed Mar 23, 2017
1 parent 53b96af commit 2b792bf
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 52 deletions.
73 changes: 53 additions & 20 deletions actionHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import shutil
from os.path import join
import uuid
import re

ttsInstance = None

Expand Down Expand Up @@ -37,44 +38,76 @@ def get_token(ctx, payload, action):
})


def splitText(text, maxBytes):
# remove extra newline
text = re.sub(r"\n+", "\n", text)
# every chinese char == 3 bytes
maxChineseChar = maxBytes // 3 + 1
idx = 0
parts = []
while idx < len(text):
parts.append(text[idx : (idx + maxChineseChar)])
idx += maxChineseChar
return parts

def postRequest(ctx, payload, action):
global ttsInstance
if not ttsInstance:
ttsInstance = Baidutts(ctx.config.get("appid"), ctx.config.get("appsecret"))

token = ctx.config.get("token")
cuid = ctx.config.get("cuid")
err, res = ttsInstance.t2a(payload["text"],
token,
cuid=cuid,
spd=payload["spd"],
pit=payload["pit"],
per=payload["per"],
vol=payload["vol"])
if err:
ctx.queue.put({
"type": "POST_REQUEST_ERROR",
"payload": err,
})

tex = payload["text"]
fileName = str(uuid.uuid1()) + ".mp3"
filePath = join(payload["dest"], fileName)
# should save to mp3 file
with open(filePath, "wb") as fout:
# res.raw.decode_content = True
shutil.copyfileobj(res.raw, fout)
# check if text is too long, if so, split it
if len(tex.encode("utf-8")) < 1024:
err, res = ttsInstance.t2a(payload["text"],
token,
cuid=cuid,
spd=payload["spd"],
pit=payload["pit"],
per=payload["per"],
vol=payload["vol"])
if err:
return (err, False)
# should save to mp3 file
# http://stackoverflow.com/questions/13137817/how-to-download-image-using-requests
with open(filePath, "wb") as fout:
# res.raw.decode_content = True
shutil.copyfileobj(res.raw, fout)
else:
textList = splitText(tex, 1024)
rawResList = []
for tx in textList:
err, res = ttsInstance.t2a(tx,
token,
cuid=cuid,
spd=payload["spd"],
pit=payload["pit"],
per=payload["per"],
vol=payload["vol"])
if err:
return (err, False)
# save raw resonponse
rawResList.append(res)
# concat all mp3 binary
with open(filePath, "wb") as fout:
# res.raw.decode_content = True
# shutil.copyfileobj(binary, fout)
for res in rawResList:
for chunk in res.iter_content(chunk_size=1024):
fout.write(chunk)

ctx.queue.put({
"type": "POST_REQUEST_DONE",
"payload": {
"fileName": fileName,
"filePatth": filePath
"filePath": filePath,
},
})




handlers = {
"END_APP": end_app,
"GET_TOKEN": get_token,
Expand Down
66 changes: 34 additions & 32 deletions test.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,34 @@
from tkinter import *
import os

print(os.path.abspath(__file__))
print(os.path.dirname(os.path.abspath(__file__)))

class Application(Frame):
def say_hi(self):
print("hi there, everyone")

def createWidgets(self):
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "green"
self.QUIT["command"] = self.quit

self.QUIT.pack({"side": "left"})

self.hithere_ = Button(self)
self.hithere_["text"] = "Hello"
self.hithere_["command"] = self.say_hi
self.hithere_.pack({"side": "left"})

def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
import re

def splitText(text, maxBytes):
text = re.sub(r"\n+", "\n", text)
# every chinese char == 3 bytes
maxChineseChar = maxBytes // 3 + 1
idx = 0
parts = []
while idx < len(text):
parts.append(text[idx : (idx + maxChineseChar)])
idx += maxChineseChar
return parts

tex = """
既然发出祝福的人可以从网上复制一条段子,甚至可能是随手复制七大姑八大姨群发给TA自己的段子,然后在微信群发助手全选联系人,往里面一粘贴点击发送就成功地搞定了所有过去的一年里爱过帮助过鼓励过同舟共济过的亲朋好友们。
那我为什么不可以用类似的方式去搞定企图用群发来搞定我的人呢?
不过我也不是批评群发祝福这种行为,敷衍确实是敷衍了一点,多少也算一份心意。
可是收到祝福的我就很尴尬了,假如我不回显得我不近人情,我要是手动回复了,很明显是我吃亏了,可能一整天的精力都要耗在回复祝福上。并且我也不愿意做那种群发祝福敷衍我的亲朋好友的那种人。
有没有既不浪费时间又能保持礼貌和客套的办法呢?
好歹也算是学过两年编程的人,其实只需要12行Python代码,就可以让你的微信拥有自动回复功能了,并且还能够自动判断消息种类和内容,只回复新年祝福相关的消息。
首先确保你安装好了Python和Python的包管理工具pip
感谢知友们的支持,更新一个进阶版,可以自动获取好友的备注名,并且从祝福语API里随机抽取祝福词进行定制的回复,并且会记录回复过的好友,不会因为重复自动回复露馅。
"""

ll = splitText(tex, 1024)
print(len(ll))
print(ll[0])
1 change: 1 addition & 0 deletions uiHandlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def post_request_done(ctrl, payload, msg):
log.info("post_request_done")
# should restore ui
ctrl.frames["MainPage"].showRequesting(True)
messagebox.showinfo("Done", "mp3 file saved in: {}".format(payload["filePath"]))

handlers = {
"GET_TOKEN_ERROR": get_token_err,
Expand Down

0 comments on commit 2b792bf

Please sign in to comment.