desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'@brief add/delete/invite member in chat group @param add_arr [uid: String] @param del_arr [uid: String] @param invite_arr [uid: String] @return Bool: whether operation succeed'
def webwxupdatechatroom(self, add_arr, del_arr, invite_arr):
url = (self.wx_conf['API_webwxupdatechatroom'] + ('?r=%s' % int(time.time()))) params = {'BaseRequest': self.base_request, 'ChatRoomName': '', 'NewTopic': '', 'AddMemberList': add_arr, 'DelMemberList': del_arr, 'InviteMemberList': invite_arr} dic = post(url, params) return (dic['BaseResponse']['Ret'] == 0)
'@brief revoke a message @param msgid String @param user_id String @param client_msgid String @return Bool: whether operation succeed'
def webwxrevokemsg(self, msgid, user_id, client_msgid):
url = (self.wx_conf['API_webwxrevokemsg'] + ('?r=%s' % int(time.time()))) params = {'BaseRequest': self.base_request, 'SvrMsgId': msgid, 'ToUserName': user_id, 'ClientMsgId': client_msgid} dic = post(url, params) return (dic['BaseResponse']['Ret'] == 0)
'@brief push a login confirm alert to mobile device @param uin String @return dic Dict'
def webwxpushloginurl(self, uin):
url = (self.wx_conf['API_webwxpushloginurl'] + ('?uin=%s' % uin)) dic = eval(get(url)) return dic
'@brief login without scan qrcode @return Bool: whether operation succeed'
def association_login(self):
if (self.uin != ''): dic = self.webwxpushloginurl(self.uin) if (dic['ret'] == '0'): self.uuid = dic['uuid'] return True return False
'@brief send text @param user_id String @param text String @return Bool: whether operation succeed'
def send_text(self, user_id, text):
try: dic = self.webwxsendmsg(text, user_id) return (dic['BaseResponse']['Ret'] == 0) except: return False
'@brief send image @param user_id String @param file_path String @return Bool: whether operation succeed'
def send_img(self, user_id, file_path):
response = self.webwxuploadmedia(file_path) media_id = '' if (response is not None): media_id = response['MediaId'] return self.webwxsendmsgimg(user_id, media_id)
'@brief send emotion @param user_id String @param file_path String @return Bool: whether operation succeed'
def send_emot(self, user_id, file_path):
response = self.webwxuploadmedia(file_path) media_id = '' if (response is not None): media_id = response['MediaId'] return self.webwxsendemoticon(user_id, media_id)
'@brief send file @param user_id String @param file_path String @return Bool: whether operation succeed'
def send_file(self, user_id, file_path):
title = file_path.split('/')[(-1)] data = {'appid': Constant.API_WXAPPID, 'title': title, 'totallen': '', 'attachid': '', 'type': self.wx_conf['APPMSGTYPE_ATTACH'], 'fileext': title.split('.')[(-1)]} response = self.webwxuploadmedia(file_path) if (response is not None): data['totallen'] = response['StartPos'] data['attachid'] = response['MediaId'] else: Log.error('File upload error') return self.webwxsendappmsg(user_id, data)
'@brief revoke a message @param msgid String @param user_id String @param client_msgid String @return Bool: whether operation succeed'
def revoke_msg(self, msgid, user_id, client_msgid):
return self.webwxrevokemsg(msgid, user_id, client_msgid)
'@brief get all type of name by user id @param user_id The id of user @return Dict: { \'UserName\' # 埮信劚态ID \'RemarkName\' # 倇泚 \'NickName\' # 埮信昵称 \'ShowName\' # Log星瀺甚的'
def get_user_by_id(self, user_id):
UnknownPeople = (Constant.LOG_MSG_UNKNOWN_NAME + user_id) name = {'UserName': user_id, 'RemarkName': '', 'NickName': '', 'ShowName': ''} name['ShowName'] = UnknownPeople if (user_id == self.User['UserName']): name['RemarkName'] = self.User['RemarkName'] name['NickName'] = self.User['NickName'] name['ShowName'] = name['NickName'] else: for member in self.MemberList: if (member['UserName'] == user_id): (r, n) = (member['RemarkName'], member['NickName']) name['RemarkName'] = r name['NickName'] = n name['ShowName'] = (r if r else n) break for member in self.SpecialUsersList: if (member['UserName'] == user_id): name['RemarkName'] = user_id name['NickName'] = user_id name['ShowName'] = user_id break return name
'@brief get group user by user id @param user_id The id of user @param group_id The id of group @return Dict: { \'UserName\' # 埮信劚态ID \'NickName\' # 埮信昵称 \'DisplayName\' # 矀聊星瀺名称 \'ShowName\' # Log星瀺甚的 \'AttrStatus\' # 矀甚户id'
def get_group_user_by_id(self, user_id, group_id):
UnknownPeople = (Constant.LOG_MSG_UNKNOWN_NAME + user_id) name = {'UserName': user_id, 'NickName': '', 'DisplayName': '', 'ShowName': '', 'AttrStatus': ''} name['ShowName'] = UnknownPeople if (group_id in self.GroupMemeberList): for member in self.GroupMemeberList[group_id]: if (member['UserName'] == user_id): (n, d) = (member['NickName'], member['DisplayName']) name['NickName'] = n name['DisplayName'] = d name['AttrStatus'] = member['AttrStatus'] name['ShowName'] = (d if d else n) break return name
'@brief get basic info by group id @param group_id The id of group @return Dict: { \'UserName\' # 埮信劚态ID \'NickName\' # 埮信昵称 \'DisplayName\' # 矀聊星瀺名称 \'ShowName\' # Log星瀺甚的 \'OwnerUin\' # 矀䞻ID \'MemberCount\' # 矀人数'
def get_group_by_id(self, group_id):
UnknownGroup = (Constant.LOG_MSG_UNKNOWN_GROUP_NAME + group_id) group = {'UserName': group_id, 'NickName': '', 'DisplayName': '', 'ShowName': '', 'OwnerUin': '', 'MemberCount': ''} for member in self.GroupList: if (member['UserName'] == group_id): group['NickName'] = member['NickName'] group['DisplayName'] = member.get('DisplayName', '') group['ShowName'] = member.get('NickName', UnknownGroup) group['OwnerUin'] = member.get('OwnerUin', '') group['MemberCount'] = member['MemberCount'] break return group
'@brief Gets the user id. @param name The user nickname or remarkname @return The user id.'
def get_user_id(self, name):
for member in self.MemberList: if ((name == member['RemarkName']) or (name == member['NickName'])): return member['UserName'] return None
'@brief get how long this run @return String'
def get_run_time(self):
totalTime = int((time.time() - self.start_time)) t = timedelta(seconds=totalTime) return ('%s Day %s' % (t.days, t))
'@brief Save some data and use shell to kill this process'
def stop(self):
run(Constant.LOG_MSG_SNAPSHOT, self.snapshot) echo((Constant.LOG_MSG_RUNTIME % self.get_run_time())) self.db.close()
'@brief Fetches all groups contacts. @return Bool: whether operation succeed. @note This function must be finished in 180s'
def fetch_group_contacts(self):
Log.debug('fetch_group_contacts') if self.msg_handler: self.msg_handler.clean_db() max_thread_num = 4 max_fetch_group_num = 50 group_list_queue = Queue.Queue() class GroupListThread(threading.Thread, ): def __init__(self, group_list_queue, wechat): threading.Thread.__init__(self) self.group_list_queue = group_list_queue self.wechat = wechat def run(self): while (not self.group_list_queue.empty()): g_list = self.group_list_queue.get() gid_list = [] g_dict = {} for g in g_list: gid = g['UserName'] gid_list.append(gid) g_dict[gid] = g group_member_list = self.wechat.webwxbatchgetcontact(gid_list) for member_list in group_member_list: gid = member_list['UserName'] g = g_dict[gid] g['MemberCount'] = member_list['MemberCount'] g['OwnerUin'] = member_list['OwnerUin'] self.wechat.GroupMemeberList[gid] = member_list['MemberList'] self.group_list_queue.task_done() for g_list in split_array(self.GroupList, max_fetch_group_num): group_list_queue.put(g_list) for i in range(max_thread_num): t = GroupListThread(group_list_queue, self) t.setDaemon(True) t.start() group_list_queue.join() if self.msg_handler: if self.GroupList: self.msg_handler.handle_group_list(self.GroupList) for (gid, member_list) in self.GroupMemeberList.items(): self.msg_handler.handle_group_member_list(gid, member_list) return True
'@brief Save basic infos for next login. @return Bool: whether operation succeed.'
def snapshot(self):
try: conf = {'uuid': self.uuid, 'redirect_uri': self.redirect_uri, 'uin': self.uin, 'sid': self.sid, 'skey': self.skey, 'pass_ticket': self.pass_ticket, 'synckey': self.synckey, 'device_id': self.device_id, 'last_login': time.time()} cm = ConfigManager() Log.debug('save wechat config') cm.set_wechat_config(conf) Log.debug('save cookie') if self.cookie: self.cookie.save(ignore_discard=True) Log.debug('save contacts') self.save_contacts() except Exception as e: Log.error(traceback.format_exc()) return False return True
'@brief Recover from snapshot data. @return Bool: whether operation succeed.'
def recover(self):
cm = ConfigManager() [self.uuid, self.redirect_uri, self.uin, self.sid, self.skey, self.pass_ticket, self.synckey, device_id, self.last_login] = cm.get_wechat_config() if device_id: self.device_id = device_id self.base_request = {'Uin': int(self.uin), 'Sid': self.sid, 'Skey': self.skey, 'DeviceID': self.device_id} Log.debug('set cookie') self.cookie = set_cookie(self.cookie_file) return True
'@brief Save contacts.'
def save_contacts(self):
pickle_save(self.User, self.pickle_file['User']) pickle_save(self.MemberList, self.pickle_file['MemberList']) pickle_save(self.GroupList, self.pickle_file['GroupList']) pickle_save(self.GroupMemeberList, self.pickle_file['GroupMemeberList']) pickle_save(self.SpecialUsersList, self.pickle_file['SpecialUsersList'])
'@brief recover contacts. @return Bool: whether operation succeed.'
def recover_contacts(self):
try: self.User = pickle_load(self.pickle_file['User']) self.MemberList = pickle_load(self.pickle_file['MemberList']) self.GroupList = pickle_load(self.pickle_file['GroupList']) self.GroupMemeberList = pickle_load(self.pickle_file['GroupMemeberList']) self.SpecialUsersList = pickle_load(self.pickle_file['SpecialUsersList']) return True except Exception as e: Log.error(traceback.format_exc()) return False
'@brief Recover from snapshot data. @param r Dict: message json'
def handle_msg(self, r):
Log.debug('handle message') if self.msg_handler: self.msg_handler.handle_wxsync(r) n = len(r['AddMsgList']) if (n == 0): return if self.log_mode: echo((Constant.LOG_MSG_NEW_MSG % n)) for msg in r['AddMsgList']: msgType = msg['MsgType'] msgId = msg['MsgId'] content = msg['Content'].replace('&lt;', '<').replace('&gt;', '>') raw_msg = None if (msgType == self.wx_conf['MSGTYPE_TEXT']): if (content.find('pictype=location') != (-1)): location = content.split('<br/>')[1][:(-1)] raw_msg = {'raw_msg': msg, 'location': location, 'log': (Constant.LOG_MSG_LOCATION % location)} else: text = content.split(':<br/>')[(-1)] raw_msg = {'raw_msg': msg, 'text': text, 'log': text.replace('<br/>', '\n')} elif (msgType == self.wx_conf['MSGTYPE_IMAGE']): data = self.webwxgetmsgimg(msgId) fn = (('img_' + msgId) + '.jpg') dir = self.save_data_folders['webwxgetmsgimg'] path = save_file(fn, data, dir) raw_msg = {'raw_msg': msg, 'image': path, 'log': (Constant.LOG_MSG_PICTURE % path)} elif (msgType == self.wx_conf['MSGTYPE_VOICE']): data = self.webwxgetvoice(msgId) fn = (('voice_' + msgId) + '.mp3') dir = self.save_data_folders['webwxgetvoice'] path = save_file(fn, data, dir) raw_msg = {'raw_msg': msg, 'voice': path, 'log': (Constant.LOG_MSG_VOICE % path)} elif (msgType == self.wx_conf['MSGTYPE_SHARECARD']): info = msg['RecommendInfo'] card = (Constant.LOG_MSG_NAME_CARD % (info['NickName'], info['Alias'], info['Province'], info['City'], Constant.LOG_MSG_SEX_OPTION[info['Sex']])) namecard = ('%s %s %s %s %s' % (info['NickName'], info['Alias'], info['Province'], info['City'], Constant.LOG_MSG_SEX_OPTION[info['Sex']])) raw_msg = {'raw_msg': msg, 'namecard': namecard, 'log': card} elif (msgType == self.wx_conf['MSGTYPE_EMOTICON']): url = search_content('cdnurl', content) raw_msg = {'raw_msg': msg, 'emoticon': url, 'log': (Constant.LOG_MSG_EMOTION % url)} elif (msgType == self.wx_conf['MSGTYPE_APP']): card = '' if (msg['AppMsgType'] in [self.wx_conf['APPMSGTYPE_AUDIO'], self.wx_conf['APPMSGTYPE_URL'], self.wx_conf['APPMSGTYPE_OPEN']]): card = (Constant.LOG_MSG_APP_LINK % (Constant.LOG_MSG_APP_LINK_TYPE[msg['AppMsgType']], msg['FileName'], search_content('des', content, 'xml'), msg['Url'], search_content('appname', content, 'xml'))) raw_msg = {'raw_msg': msg, 'link': msg['Url'], 'log': card} elif (msg['AppMsgType'] == self.wx_conf['APPMSGTYPE_IMG']): data = self.webwxgetmsgimg(msgId) fn = (('img_' + msgId) + '.jpg') dir = self.save_data_folders['webwxgetmsgimg'] path = save_file(fn, data, dir) card = (Constant.LOG_MSG_APP_IMG % (path, search_content('appname', content, 'xml'))) raw_msg = {'raw_msg': msg, 'image': path, 'log': card} else: raw_msg = {'raw_msg': msg, 'log': (Constant.LOG_MSG_UNKNOWN_MSG % (msgType, content))} elif (msgType == self.wx_conf['MSGTYPE_STATUSNOTIFY']): Log.info(Constant.LOG_MSG_NOTIFY_PHONE) elif (msgType == self.wx_conf['MSGTYPE_MICROVIDEO']): data = self.webwxgetvideo(msgId) fn = (('video_' + msgId) + '.mp4') dir = self.save_data_folders['webwxgetvideo'] path = save_file(fn, data, dir) raw_msg = {'raw_msg': msg, 'video': path, 'log': (Constant.LOG_MSG_VIDEO % path)} elif (msgType == self.wx_conf['MSGTYPE_RECALLED']): recall_id = search_content('msgid', content, 'xml') text = Constant.LOG_MSG_RECALL raw_msg = {'raw_msg': msg, 'text': text, 'recall_msg_id': recall_id, 'log': text} elif (msgType == self.wx_conf['MSGTYPE_SYS']): raw_msg = {'raw_msg': msg, 'sys_notif': content, 'log': content} elif (msgType == self.wx_conf['MSGTYPE_VERIFYMSG']): name = search_content('fromnickname', content) raw_msg = {'raw_msg': msg, 'log': (Constant.LOG_MSG_ADD_FRIEND % name)} else: raw_msg = {'raw_msg': msg, 'log': (Constant.LOG_MSG_UNKNOWN_MSG % (msgType, content))} isGroupMsg = ('@@' in (msg['FromUserName'] + msg['ToUserName'])) if (self.msg_handler and raw_msg): if isGroupMsg: g_msg = self.make_group_msg(raw_msg) self.msg_handler.handle_group_msg(g_msg) else: self.msg_handler.handle_user_msg(raw_msg) if self.log_mode: self.show_msg(raw_msg)
'@brief Package the group message for storage. @param msg Dict: raw msg @return raw_msg Dict: packged msg'
def make_group_msg(self, msg):
Log.debug('make group message') raw_msg = {'raw_msg': msg['raw_msg'], 'msg_id': msg['raw_msg']['MsgId'], 'group_owner_uin': '', 'group_name': '', 'group_count': '', 'from_user_name': msg['raw_msg']['FromUserName'], 'to_user_name': msg['raw_msg']['ToUserName'], 'user_attrstatus': '', 'user_display_name': '', 'user_nickname': '', 'msg_type': msg['raw_msg']['MsgType'], 'text': '', 'link': '', 'image': '', 'video': '', 'voice': '', 'emoticon': '', 'namecard': '', 'location': '', 'recall_msg_id': '', 'sys_notif': '', 'time': '', 'timestamp': '', 'log': ''} content = msg['raw_msg']['Content'].replace('&lt;', '<').replace('&gt;', '>') group = None src = None if (msg['raw_msg']['FromUserName'][:2] == '@@'): g_id = msg['raw_msg']['FromUserName'] group = self.get_group_by_id(g_id) if re.search(':<br/>', content, re.IGNORECASE): u_id = content.split(':<br/>')[0] src = self.get_group_user_by_id(u_id, g_id) elif (msg['raw_msg']['ToUserName'][:2] == '@@'): g_id = msg['raw_msg']['ToUserName'] u_id = msg['raw_msg']['FromUserName'] src = self.get_group_user_by_id(u_id, g_id) group = self.get_group_by_id(g_id) if src: raw_msg['user_attrstatus'] = src['AttrStatus'] raw_msg['user_display_name'] = src['DisplayName'] raw_msg['user_nickname'] = src['NickName'] if group: raw_msg['group_count'] = group['MemberCount'] raw_msg['group_owner_uin'] = group['OwnerUin'] raw_msg['group_name'] = group['ShowName'] raw_msg['timestamp'] = msg['raw_msg']['CreateTime'] t = time.localtime(float(raw_msg['timestamp'])) raw_msg['time'] = time.strftime('%Y-%m-%d %T', t) for key in ['text', 'link', 'image', 'video', 'voice', 'emoticon', 'namecard', 'location', 'log', 'recall_msg_id', 'sys_notif']: if (key in msg): raw_msg[key] = msg[key] return raw_msg
'@brief Log the message to stdout @param message Dict'
def show_msg(self, message):
msg = message src = None dst = None group = None if (msg and msg['raw_msg']): content = msg['raw_msg']['Content'] content = content.replace('&lt;', '<').replace('&gt;', '>') msg_id = msg['raw_msg']['MsgId'] if (msg['raw_msg']['FromUserName'][:2] == '@@'): g_id = msg['raw_msg']['FromUserName'] group = self.get_group_by_id(g_id) if re.search(':<br/>', content, re.IGNORECASE): u_id = content.split(':<br/>')[0] src = self.get_group_user_by_id(u_id, g_id) dst = {'ShowName': 'GROUP'} else: u_id = msg['raw_msg']['ToUserName'] src = {'ShowName': 'SYSTEM'} dst = self.get_group_user_by_id(u_id, g_id) elif (msg['raw_msg']['ToUserName'][:2] == '@@'): g_id = msg['raw_msg']['ToUserName'] u_id = msg['raw_msg']['FromUserName'] group = self.get_group_by_id(g_id) src = self.get_group_user_by_id(u_id, g_id) dst = {'ShowName': 'GROUP'} else: src = self.get_user_by_id(msg['raw_msg']['FromUserName']) dst = self.get_user_by_id(msg['raw_msg']['ToUserName']) if group: echo(('%s |%s| %s -> %s: %s\n' % (msg_id, trans_emoji(group['ShowName']), trans_emoji(src['ShowName']), dst['ShowName'], trans_emoji(msg['log'])))) else: echo(('%s %s -> %s: %s\n' % (msg_id, trans_emoji(src['ShowName']), trans_emoji(dst['ShowName']), trans_emoji(msg['log']))))
'@brief clean database, delete table & create table'
def clean_db(self):
self.db.delete_table(Constant.TABLE_GROUP_LIST()) self.db.delete_table(Constant.TABLE_GROUP_USER_LIST()) self.db.create_table(Constant.TABLE_GROUP_MSG_LOG, Constant.TABLE_GROUP_MSG_LOG_COL) self.db.create_table(Constant.TABLE_GROUP_LIST(), Constant.TABLE_GROUP_LIST_COL) self.db.create_table(Constant.TABLE_GROUP_USER_LIST(), Constant.TABLE_GROUP_USER_LIST_COL) self.db.create_table(Constant.TABLE_RECORD_ENTER_GROUP, Constant.TABLE_RECORD_ENTER_GROUP_COL) self.db.create_table(Constant.TABLE_RECORD_RENAME_GROUP, Constant.TABLE_RECORD_RENAME_GROUP_COL)
'@brief Recieve webwxsync message, saved into json @param msg Dict: webwxsync msg'
def handle_wxsync(self, msg):
fn = time.strftime(Constant.LOG_MSG_FILE, time.localtime()) save_json(fn, msg, self.log_dir, 'a+')
'@brief handle group list & saved in DB @param group_list Array'
def handle_group_list(self, group_list):
fn = Constant.LOG_MSG_GROUP_LIST_FILE save_json(fn, group_list, self.data_dir) cols = [(g['NickName'], g['UserName'], g['OwnerUin'], g['MemberCount'], g['HeadImgUrl']) for g in group_list] self.db.insertmany(Constant.TABLE_GROUP_LIST(), cols)
'@brief handle group member list & saved in DB @param member_list Array'
def handle_group_member_list(self, group_id, member_list):
fn = (group_id + '.json') save_json(fn, member_list, self.data_dir) cols = [(group_id, m['UserName'], m['NickName'], m['DisplayName'], m['AttrStatus']) for m in member_list] self.db.insertmany(Constant.TABLE_GROUP_USER_LIST(), cols)
'@brief handle adding a new group & saved in DB @param new_group Dict'
def handle_group_list_change(self, new_group):
self.handle_group_list([new_group])
'@brief handle group member changes & saved in DB @param group_id Dict @param member_list Dict'
def handle_group_member_change(self, group_id, member_list):
self.db.delete(Constant.TABLE_GROUP_USER_LIST(), 'RoomID', group_id) self.handle_group_member_list(group_id, member_list)
'@brief Recieve group messages @param msg Dict: packaged msg'
def handle_group_msg(self, msg):
for k in ['image', 'video', 'voice']: if msg[k]: t = time.localtime(float(msg['timestamp'])) time_str = time.strftime('%Y%m%d%H%M%S', t) file_name = ('/%s_%s_%s.' % (time_str, msg['msg_id'], msg['group_name'])) new_name = re.sub('\\/\\w+\\_\\d+\\.', file_name, msg[k]) Log.debug(('rename file to %s' % new_name)) os.rename(msg[k], new_name) msg[k] = new_name if (msg['msg_type'] == 10000): m = re.search('\xe9\x82\x80\xe8\xaf\xb7(.+)\xe5\x8a\xa0\xe5\x85\xa5\xe4\xba\x86\xe7\xbe\xa4\xe8\x81\x8a', msg['sys_notif']) if m: name = m.group(1) col_enter_group = (msg['msg_id'], msg['group_name'], msg['from_user_name'], msg['to_user_name'], name, msg['time']) self.db.insert(Constant.TABLE_RECORD_ENTER_GROUP, col_enter_group) n = re.search('(.+)\xe4\xbf\xae\xe6\x94\xb9\xe7\xbe\xa4\xe5\x90\x8d\xe4\xb8\xba\xe2\x80\x9c(.+)\xe2\x80\x9d', msg['sys_notif']) if n: people = n.group(1) to_name = n.group(2) col_rename_group = (msg['msg_id'], msg['group_name'], to_name, people, msg['time']) self.db.insert(Constant.TABLE_RECORD_RENAME_GROUP, col_rename_group) for g in self.wechat.GroupList: if (g['UserName'] == msg['from_user_name']): g['NickName'] = to_name break col = (msg['msg_id'], msg['group_owner_uin'], msg['group_name'], msg['group_count'], msg['from_user_name'], msg['to_user_name'], msg['user_attrstatus'], msg['user_display_name'], msg['user_nickname'], msg['msg_type'], msg['emoticon'], msg['text'], msg['image'], msg['video'], msg['voice'], msg['link'], msg['namecard'], msg['location'], msg['recall_msg_id'], msg['sys_notif'], msg['time'], msg['timestamp']) self.db.insert(Constant.TABLE_GROUP_MSG_LOG, col) text = msg['text'] if (text and (text[0] == '@')): n = trans_coding(text).find(u'\u2005') name = trans_coding(text)[1:n].encode('utf-8') if (name in [self.wechat.User['NickName'], self.wechat.User['RemarkName']]): self.handle_command(trans_coding(text)[(n + 1):].encode('utf-8'), msg)
'@brief Recieve personal messages @param msg Dict'
def handle_user_msg(self, msg):
wechat = self.wechat text = trans_coding(msg['text']).encode('utf-8') uid = msg['raw_msg']['FromUserName'] if (text == 'test_revoke'): dic = wechat.webwxsendmsg('\xe8\xbf\x99\xe6\x9d\xa1\xe6\xb6\x88\xe6\x81\xaf\xe5\xb0\x86\xe8\xa2\xab\xe6\x92\xa4\xe5\x9b\x9e', uid) wechat.revoke_msg(dic['MsgID'], uid, dic['LocalID']) elif (text == 'reply'): wechat.send_text(uid, '\xe8\x87\xaa\xe5\x8a\xa8\xe5\x9b\x9e\xe5\xa4\x8d')
'@brief handle msg of `@yourself cmd` @param cmd String @param msg Dict'
def handle_command(self, cmd, msg):
wechat = self.wechat g_id = '' for g in wechat.GroupList: if (g['NickName'] == msg['group_name']): g_id = g['UserName'] cmd = cmd.strip() if (cmd == 'runtime'): wechat.send_text(g_id, wechat.get_run_time()) elif (cmd == 'test_sendimg'): wechat.send_img(g_id, 'test/emotion/7.gif') elif (cmd == 'test_sendfile'): wechat.send_file(g_id, 'test/Data/upload/shake.wav') elif (cmd == 'test_bot'): if wechat.bot: r = wechat.bot.reply(cmd) if r: wechat.send_text(g_id, r) else: pass elif (cmd == 'test_emot'): img_name = ['0.jpg', '1.jpeg', '2.gif', '3.jpg', '4.jpeg', '5.gif', '6.gif', '7.gif', '8.jpg', '9.jpg'] name = img_name[(int(time.time()) % 10)] emot_path = os.path.join('test/emotion/', name) wechat.send_emot(g_id, emot_path) else: pass
'@brief Creates a database @param db_name String'
def create_db(self, db_name):
if (self.conf['database'] not in self.show_database()): sql = ('CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' % db_name) Log.debug(('DB -> %s' % sql)) self.execute(sql)
'@brief Creates a table in database @param table String @param cols String, the cols in table'
def create_table(self, table, cols):
if (table not in self.table_cols): sql = ('CREATE TABLE IF NOT EXISTS %s(id int primary key auto_increment, %s) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci' % (table, cols)) Log.debug(('DB -> %s' % sql)) self.execute(sql) self.table_cols[table] = (['id'] + [c.strip().split(' ')[0] for c in cols.split(',')])
'@brief Delete a table in database @param table String'
def delete_table(self, table):
if (table in self.table_cols): sql = ('DROP TABLE IF EXISTS %s' % table) Log.debug(('DB -> %s' % sql)) self.execute(sql) self.table_cols.pop(table)
'@brief Insert a row in table @param table String @param value Tuple'
def insert(self, table, value):
col_name = self.table_cols[table][1:] sql = ('INSERT INTO %s(%s) VALUES (%s)' % (table, str(','.join(col_name)), array_join(value, ','))) Log.debug(('DB -> %s' % sql)) self.execute(sql)
'@brief Insert many rows in table @param table String @param values Array of tuple'
def insertmany(self, table, values):
col_name = self.table_cols[table][1:] sql = ('INSERT INTO %s(%s) VALUES (%s)' % (table, ','.join(col_name), ','.join((['%s'] * len(values[0]))))) Log.debug(('DB -> %s' % sql)) self.execute(sql, values)
'@brief select all result from table @param table String @param field String @param condition String @return result Tuple'
def select(self, table, field='', condition=''):
sql = ('SELECT * FROM %s' % table) if (field and condition): sql += (" WHERE %s='%s'" % (field, condition)) Log.debug(('DB -> %s' % sql)) return self.execute(sql)
'@brief select all result from table @param table String @return result Array'
def get_table_column_name(self, table):
c = self.conn.cursor() c.execute(('SELECT * FROM %s' % table)) names = list(map((lambda x: x[0]), c.description)) return names
'@brief execute sql commands, return result if it has @param sql String @param value Tuple @return result Array'
def execute(self, sql, values=None):
c = self.conn.cursor() self.lock.acquire() hasReturn = sql.lstrip().upper().startswith('SELECT') result = [] try: if values: c.executemany(sql, values) else: c.execute(sql) if hasReturn: result = c.fetchall() except Exception as e: Log.error(traceback.format_exc()) self.conn.rollback() finally: self.lock.release() if hasReturn: return result
'@brief execute sql commands, return result if it has @param table String @param field String @param condition String'
def delete(self, table, field='', condition=''):
sql = ('DELETE FROM %s WHERE %s=%s' % (table, field, condition)) Log.debug(('DB -> %s' % sql)) self.execute(sql)
'@brief close connection to database'
def close(self):
Log.debug('DB -> close') self.conn.close()
'@brief Creates a table in database @param table String @param cols String, the cols in table'
def create_table(self, table, cols):
sql = ('CREATE TABLE if not exists %s (%s);' % (table, cols)) Log.debug(('DB -> %s' % sql)) self.execute(sql)
'@brief Delete a table in database @param table String'
def delete_table(self, table):
sql = ('DROP TABLE if exists %s;' % table) Log.debug(('DB -> %s' % sql)) self.execute(sql)
'@brief Insert a row in table @param table String @param value Tuple'
def insert(self, table, value):
sql = ((('INSERT INTO %s VALUES (' + ','.join((['?'] * len(value)))) + ');') % table) Log.debug(('DB -> %s' % sql)) self.execute(sql, value)
'@brief Insert many rows in table @param table String @param values Array of tuple'
def insertmany(self, table, values):
c = self.conn.cursor() self.lock.acquire() n = len(values[0]) sql = ((('INSERT INTO %s VALUES (' + ','.join((['?'] * n))) + ');') % table) Log.debug(('DB -> %s' % sql)) try: c.executemany(sql, values) except Exception as e: Log.error(traceback.format_exc()) finally: self.lock.release() self.conn.commit()
'@brief select all result from table @param table String @param field String @param condition String @return result Tuple'
def select(self, table, field='', condition=''):
result = [] if (field and condition): cond = (condition,) sql = ('SELECT * FROM %s WHERE %s=?' % (table, field)) Log.debug(('DB -> %s' % sql)) result = self.execute(sql, cond) else: sql = ('SELECT * FROM %s' % table) Log.debug(('DB -> %s' % sql)) result = self.execute(sql) return result
'@brief select all result from table @param table String @return result Array'
def get_table_column_name(self, table):
c = self.conn.cursor() c.execute(('SELECT * FROM %s' % table)) names = list(map((lambda x: x[0]), c.description)) return names
'@brief execute sql commands, return result if it has @param sql String @param value Tuple @return result Array'
def execute(self, sql, value=None):
c = self.conn.cursor() self.lock.acquire() hasReturn = sql.lstrip().upper().startswith('SELECT') try: if value: c.execute(sql, value) else: c.execute(sql) if hasReturn: result = c.fetchall() except Exception as e: Log.error(traceback.format_exc()) finally: self.lock.release() self.conn.commit() if hasReturn: return result
'@brief execute sql commands, return result if it has @param table String @param field String @param condition String'
def delete(self, table, field='', condition=''):
sql = ('DELETE FROM %s WHERE %s=?' % (table, field)) Log.debug(('DB -> %s' % sql)) cond = (condition,) self.execute(sql, cond)
'@brief close connection to database'
def close(self):
Log.debug('DB -> close') self.conn.close()
'Sets the status code for our response. Overriding is done so as to handle unknown response codes gracefully.'
def set_status(self, status_code, reason=None):
self._status_code = status_code if (reason is not None): self._reason = tornado.escape.native_str(reason) else: try: self._reason = tornado.httputil.responses[status_code] except KeyError: self._reason = tornado.escape.native_str('Server Not Found')
'* This function handles all requests except the connect request. * Once ssl stream is formed between browser and proxy, the requests are then processed by this function'
@tornado.web.asynchronous @tornado.gen.coroutine def get(self):
self.request.response_buffer = '' if self.request.uri.startswith(self.request.protocol, 0): self.request.url = self.request.uri else: self.request.url = ((self.request.protocol + '://') + self.request.host) if (self.request.uri != '/'): self.request.url += self.request.uri for header in restricted_request_headers: try: del self.request.headers[header] except: continue self.request_kwargs = {'url': self.request.url, 'method': self.request.method, 'body': (self.request.body if self.request.body else None), 'headers': self.request.headers, 'follow_redirects': False, 'use_gzip': True, 'streaming_callback': self.handle_data_chunk, 'header_callback': None, 'proxy_host': self.application.outbound_ip, 'proxy_port': self.application.outbound_port, 'proxy_username': self.application.outbound_username, 'proxy_password': self.application.outbound_password, 'allow_nonstandard_methods': True, 'validate_cert': False} self.request_object = {'url': self.request.url, 'method': self.request.method, 'body': (self.request.body.decode('utf-8', 'ignore') if self.request.body else None), 'headers': self.request.headers, 'follow_redirects': True, 'use_gzip': True, 'proxy_host': self.application.outbound_ip, 'proxy_port': self.application.outbound_port, 'proxy_username': self.application.outbound_username, 'proxy_password': self.application.outbound_password, 'allow_nonstandard_methods': True, 'validate_cert': False} request = tornado.httpclient.HTTPRequest(**self.request_kwargs) response = (yield tornado.gen.Task(self.application.async_client.fetch, request)) self.finish_response(response)
'This function gets called when a connect request is received. * The host and port are obtained from the request uri * A socket is created, wrapped in ssl and then added to SSLIOStream * This stream is used to connect to speak to the remote host on given port * If the server speaks ssl on that port, callback start_tunnel is called * An OK response is written back to client * The client side socket is wrapped in ssl * If the wrapping is successful, a new SSLIOStream is made using that socket * The stream is added back to the server for monitoring'
@tornado.web.asynchronous def connect(self):
(host, port) = self.request.uri.split(':') def start_tunnel(): try: certs = os.path.join(settings.LOG_DIR, 'certs') base = os.path.dirname(os.path.realpath(__file__)) ca_crt = os.path.join(base, 'ca.crt') ca_key = os.path.join(base, 'ca.key') self.request.connection.stream.write('HTTP/1.1 200 Connection established\r\n\r\n') wrap_socket(self.request.connection.stream.socket, host, ca_crt, ca_key, 'mobsec-yso', certs, success=ssl_success) except tornado.iostream.StreamClosedError: pass def ssl_success(client_socket): client = tornado.iostream.SSLIOStream(client_socket) server.handle_stream(client, self.application.inbound_ip) def ssl_fail(): self.request.connection.stream.write('HTTP/1.1 200 Connection established\r\n\r\n') server.handle_stream(self.request.connection.stream, self.application.inbound_ip) try: s = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)) upstream = tornado.iostream.SSLIOStream(s) upstream.set_close_callback(ssl_fail) upstream.connect((host, int(port)), start_tunnel) except Exception: self.finish()
'Implemented as a custom alternative to tornado.websocket.websocket_connect'
def upstream_connect(self, io_loop=None, callback=None):
if (io_loop is None): io_loop = tornado.ioloop.IOLoop.current() if self.request.uri.startswith(self.request.protocol, 0): self.request.url = self.request.uri else: self.request.url = (((self.request.protocol + '://') + self.request.host) + self.request.uri) self.request.url = self.request.url.replace('http', 'ws', 1) request_headers = tornado.httputil.HTTPHeaders() for (name, value) in self.request.headers.iteritems(): if (name not in restricted_request_headers): request_headers.add(name, value) request = tornado.httpclient.HTTPRequest(url=self.request.url, headers=request_headers, proxy_host=self.application.outbound_ip, proxy_port=self.application.outbound_port, proxy_username=self.application.outbound_username, proxy_password=self.application.outbound_password) self.upstream_connection = CustomWebSocketClientConnection(io_loop, request) if (callback is not None): io_loop.add_future(self.upstream_connection.connect_future, callback) return self.upstream_connection.connect_future
'Overriding of a method of WebSocketHandler'
def _execute(self, transforms, *args, **kwargs):
def start_tunnel(future): '\n A callback which is called when connection to url is successful\n ' self.upstream = future.result() self.handshake_request = self.upstream_connection.request self.handshake_request.response_buffer = '' self.handshake_request.version = 'HTTP/1.1' self.handshake_request.body = (self.handshake_request.body or '') tornado.websocket.WebSocketHandler._execute(self, transforms, *args, **kwargs) self.upstream = self.upstream_connect(callback=start_tunnel)
'Save websocket data sent from client to server, i.e add it to HTTPRequest.response_buffer with direction (>>)'
def store_upstream_data(self, message):
try: self.handshake_request.response_buffer += ('>>> %s\r\n' % message) except TypeError: self.handshake_request.response_buffer += '>>> May be binary\r\n'
'Save websocket data sent from client to server, i.e add it to HTTPRequest.response_buffer with direction (<<)'
def store_downstream_data(self, message):
try: self.handshake_request.response_buffer += ('<<< %s\r\n' % message) except TypeError: self.handshake_request.response_buffer += '<<< May be binary\r\n'
'Everytime a message is received from client side, this instance method is called'
def on_message(self, message):
self.upstream.write_message(message) self.store_upstream_data(message) if (not self.upstream.read_future): self.upstream.read_message(callback=self.on_response)
'A callback when a message is recieved from upstream *** Here message is a future'
def on_response(self, message):
if (not self.upstream.read_future): self.upstream.read_message(callback=self.on_response) if self.ws_connection: if message.result(): self.write_message(message.result()) self.store_downstream_data(message.result()) else: self.close()
'Called when websocket is closed. So handshake request-response pair along with websocket data as response body is saved'
def on_close(self):
self.handshake_response = tornado.httpclient.HTTPResponse(self.handshake_request, self.upstream_connection.code, headers=self.upstream_connection.headers, request_time=0)
'AutoEncoder'
def __call__(self, x, sigmoid=True):
return self.decode(self.encode(x)[0], sigmoid)
'Get loss function of VAE. The loss value is equal to ELBO (Evidence Lower Bound) multiplied by -1. Args: C (int): Usually this is 1.0. Can be changed to control the second term of ELBO bound, which works as regularization. k (int): Number of Monte Carlo samples used in encoded vector.'
def get_loss_func(self, C=1.0, k=1):
def lf(x): (mu, ln_var) = self.encode(x) batchsize = len(mu.data) rec_loss = 0 for l in six.moves.range(k): z = F.gaussian(mu, ln_var) rec_loss += (F.bernoulli_nll(x, self.decode(z, sigmoid=False)) / (k * batchsize)) self.rec_loss = rec_loss self.loss = (self.rec_loss + ((C * gaussian_kl_divergence(mu, ln_var)) / batchsize)) return self.loss return lf
'Compute Q-values of actions for given observations.'
def __call__(self, x):
h = F.relu(self.l0(x)) h = F.relu(self.l1(h)) return self.l2(h)
'Compute Q-values for given state-action pairs.'
def __call__(self, obs, action):
x = F.concat((obs, action), axis=1) h = F.relu(self.l0(x)) h = F.relu(self.l1(h)) return self.l2(h)
'Compute actions for given observations.'
def __call__(self, x):
h = F.relu(self.l0(x)) h = F.relu(self.l1(h)) return squash(self.l2(h), self.xp.asarray(self.action_low), self.xp.asarray(self.action_high))
'Connects the updater to the trainer that will call it. The typical usage of this method is to register additional links to the reporter of the trainer. This method is called at the end of the initialization of :class:`~chainer.training.Trainer`. The default implementation does nothing. Args: trainer (~chainer.training.Trainer): Trainer object to which the updater is registered.'
def connect_trainer(self, trainer):
pass
'Finalizes the updater object. This method is called at the end of training loops. It should finalize each dataset iterator used in this updater.'
def finalize(self):
raise NotImplementedError
'Gets the optimizer of given name. Updater holds one or more optimizers with names. They can be retrieved by this method. Args: name (str): Name of the optimizer. Returns: ~chainer.Optimizer: Optimizer of the name.'
def get_optimizer(self, name):
raise NotImplementedError
'Gets a dictionary of all optimizers for this updater. Returns: dict: Dictionary that maps names to optimizers.'
def get_all_optimizers(self):
raise NotImplementedError
'Updates the parameters of the target model. This method implements an update formula for the training task, including data loading, forward/backward computations, and actual updates of parameters. This method is called once at each iteration of the training loop.'
def update(self):
raise NotImplementedError
'Serializes the current state of the updater object.'
def serialize(self, serializer):
raise NotImplementedError
'Finalizes the updater object. This method calls the `finalize` method of each iterator that this updater has. It is called at the end of training loops.'
def finalize(self):
for iterator in six.itervalues(self._iterators): iterator.finalize()
'Gets the optimizer of given name. Args: name (str): Name of the optimizer. Returns: ~chainer.Optimizer: Corresponding optimizer.'
def get_optimizer(self, name):
return self._optimizers[name]
'Gets a dictionary of all optimizers for this updater. Returns: dict: Dictionary that maps names to optimizers.'
def get_all_optimizers(self):
return dict(self._optimizers)
'Gets the dataset iterator of given name. Args: name (str): Name of the dataset iterator. Returns: ~chainer.dataset.Iterator: Corresponding dataset iterator.'
def get_iterator(self, name):
return self._iterators[name]
'Updates the parameters of the target model. This method implements an update formula for the training task, including data loading, forward/backward computations, and actual updates of parameters. This method is called once at each iteration of the training loop.'
def update(self):
self.update_core() self.iteration += 1
'Serializes the current state of the updater object.'
def serialize(self, serializer):
for (name, iterator) in six.iteritems(self._iterators): iterator.serialize(serializer[('iterator:' + name)]) for (name, optimizer) in six.iteritems(self._optimizers): optimizer.serialize(serializer[('optimizer:' + name)]) optimizer.target.serialize(serializer[('model:' + name)]) self.iteration = serializer('iteration', self.iteration)
'Decides whether the extension should be called on this iteration. Args: trainer (Trainer): Trainer object that this trigger is associated with. The updater associated with this trainer is used to determine if the trigger should fire. Returns: bool: True if the corresponding extension should be invoked in this iteration.'
def __call__(self, trainer):
updater = trainer.updater if (self.unit == 'epoch'): epoch_detail = updater.epoch_detail previous_epoch_detail = self._previous_epoch_detail if (previous_epoch_detail < 0): previous_epoch_detail = updater.previous_epoch_detail self.count = (epoch_detail // self.period) fire = ((previous_epoch_detail // self.period) != (epoch_detail // self.period)) else: iteration = updater.iteration previous_iteration = self._previous_iteration if (previous_iteration < 0): previous_iteration = (iteration - 1) fire = ((previous_iteration // self.period) != (iteration // self.period)) self._previous_iteration = updater.iteration if hasattr(updater, 'epoch_detail'): self._previous_epoch_detail = updater.epoch_detail return fire
'Decides whether the extension should be called on this iteration. Args: trainer (Trainer): Trainer object that this trigger is associated with. The updater associated with this trainer is used to determine if the trigger should fire. Returns: bool: True if the corresponding extension should be invoked in this iteration.'
def __call__(self, trainer):
updater = trainer.updater if (self.unit == 'epoch'): epoch_detail = updater.epoch_detail previous_epoch_detail = self._previous_epoch_detail if (previous_epoch_detail < 0): previous_epoch_detail = updater.previous_epoch_detail fire = any(((previous_epoch_detail < p <= epoch_detail) for p in self.points)) else: iteration = updater.iteration previous_iteration = self._previous_iteration if (previous_iteration < 0): previous_iteration = (iteration - 1) fire = any(((previous_iteration < p <= iteration) for p in self.points)) self._previous_iteration = updater.iteration if hasattr(updater, 'epoch_detail'): self._previous_epoch_detail = updater.epoch_detail return fire
'Decides whether the extension should be called on this iteration. Args: trainer (~chainer.training.Trainer): Trainer object that this trigger is associated with. The ``observation`` of this trainer is used to determine if the trigger should fire. Returns: bool: ``True`` if the corresponding extension should be invoked in this iteration.'
def __call__(self, trainer):
observation = trainer.observation summary = self._summary key = self._key if (key in observation): summary.add({key: observation[key]}) if (not self._interval_trigger(trainer)): return False stats = summary.compute_mean() value = float(stats[key]) self._init_summary() if ((self._best_value is None) or self._compare(self._best_value, value)): self._best_value = value return True return False
'Default name of the extension. It is the name of the class by default. Implementation can override this property, or provide a class attribute to hide it.'
@property def default_name(self):
return type(self).__name__
'Invokes the extension. Implementations should override this operator. This method is called at iterations which the corresponding trigger accepts. Args: trainer (Trainer): Trainer object that calls this operator.'
def __call__(self, trainer):
pass
'Finalizes the extension. This method is called at the end of the training loop.'
def finalize(self):
pass
'Initializes up the trainer state. This method is called before entering the training loop. An extension that modifies the state of :class:`~chainer.training.Trainer` can override this method to initialize it. When the trainer has been restored from a snapshot, this method has to recover an appropriate part of the state of the trainer. For example, :class:`~chainer.training.extensions.ExponentialShift` extension changes the optimizer\'s hyperparameter at each invocation. Note that the hyperparameter is not saved to the snapshot; it is the responsibility of the extension to recover the hyperparameter. The :class:`~chainer.training.extensions.ExponentialShift` extension recovers it in its ``initialize`` method if it has been loaded from a snapshot, or just setting the initial value otherwise. Args: trainer (Trainer): Trainer object that runs the training loop.'
def initialize(self, trainer):
pass
'Serializes the extension state. It is called when a trainer that owns this extension is serialized. It serializes nothing by default.'
def serialize(self, serializer):
pass
'Returns the iterator of the given name.'
def get_iterator(self, name):
return self._iterators[name]
'Returns a dictionary of all iterators.'
def get_all_iterators(self):
return dict(self._iterators)
'Returns the target link of the given name.'
def get_target(self, name):
return self._targets[name]
'Returns a dictionary of all target links.'
def get_all_targets(self):
return dict(self._targets)
'Executes the evaluator extension. Unlike usual extensions, this extension can be executed without passing a trainer object. This extension reports the performance on validation dataset using the :func:`~chainer.report` function. Thus, users can use this extension independently from any trainer by manually configuring a :class:`~chainer.Reporter` object. Args: trainer (~chainer.training.Trainer): Trainer object that invokes this extension. It can be omitted in case of calling this extension manually. Returns: dict: Result dictionary that contains mean statistics of values reported by the evaluation function.'
def __call__(self, trainer=None):
reporter = reporter_module.Reporter() if hasattr(self, 'name'): prefix = (self.name + '/') else: prefix = '' for (name, target) in six.iteritems(self._targets): reporter.add_observer((prefix + name), target) reporter.add_observers((prefix + name), target.namedlinks(skipself=True)) with reporter: with configuration.using_config('train', False): result = self.evaluate() reporter_module.report(result) return result
'Evaluates the model and returns a result dictionary. This method runs the evaluation loop over the validation dataset. It accumulates the reported values to :class:`~chainer.DictSummary` and returns a dictionary whose values are means computed by the summary. Users can override this method to customize the evaluation routine. Returns: dict: Result dictionary. This dictionary is further reported via :func:`~chainer.report` without specifying any observer.'
def evaluate(self):
iterator = self._iterators['main'] target = self._targets['main'] eval_func = (self.eval_func or target) if self.eval_hook: self.eval_hook(self) if hasattr(iterator, 'reset'): iterator.reset() it = iterator else: it = copy.copy(iterator) summary = reporter_module.DictSummary() for batch in it: observation = {} with reporter_module.report_scope(observation): in_arrays = self.converter(batch, self.device) with function.no_backprop_mode(): if isinstance(in_arrays, tuple): eval_func(*in_arrays) elif isinstance(in_arrays, dict): eval_func(**in_arrays) else: eval_func(in_arrays) summary.add(observation) return summary.compute_mean()
'Execute the statistics extension. Collect statistics for the current state of parameters. Note that this method will merely update its statistic summary, unless the internal trigger is fired. If the trigger is fired, the summary will also be reported and then reset for the next accumulation. Args: trainer (~chainer.training.Trainer): Associated trainer that invoked this extension.'
def __call__(self, trainer):
statistics = {} for link in self._links: link_name = getattr(link, 'name', 'None') for (param_name, param) in link.namedparams(): for attr_name in self._attrs: for (function_name, function) in six.iteritems(self._statistics): params = getattr(param, attr_name).ravel() value = function(params) key = self.report_key_template.format(prefix=((self._prefix + '/') if self._prefix else ''), link_name=link_name, param_name=param_name, attr_name=attr_name, function_name=function_name) if hasattr(value, '__iter__'): statistics.update({'{}/{}'.format(key, i): v for (i, v) in enumerate(value)}) else: statistics[key] = value self._summary.add(statistics) if self._trigger(trainer): reporter.report(self._summary.compute_mean()) self._summary = reporter.DictSummary()
'Register a function to compute a certain statistic. The registered function will be called each time the extension runs and the results will be included in the report. Args: name (str): Name of the statistic. function: Function to generate the statistic. Any function that takes a one-dimensional :class:`numpy.ndarray` or a :class:`cupy.ndarray` and outputs a single or multiple real numbers is allowed.'
def register_statistics(self, name, function):
self._statistics[name] = function
'The current list of observation dictionaries.'
@property def log(self):
return self._log
'Total time used for the training. The time is in seconds. If the training is resumed from snapshot, it includes the time of all the previous training to get the current state of the trainer.'
@property def elapsed_time(self):
if self._done: return self._final_elapsed_time if (self._start_at is None): raise RuntimeError('training has not been started yet') return ((_get_time() - self._start_at) + self._snapshot_elapsed_time)
'Registers an extension to the trainer. :class:`Extension` is a callable object which is called after each update unless the corresponding trigger object decides to skip the iteration. The order of execution is determined by priorities: extensions with higher priorities are called earlier in each iteration. Extensions with the same priority are invoked in the order of registrations. If two or more extensions with the same name are registered, suffixes are added to the names of the second to last extensions. The suffix is ``_N`` where N is the ordinal of the extensions. See :class:`Extension` for the interface of extensions. Args: extension: Extension to register. name (str): Name of the extension. If it is omitted, the ``default_name`` attribute of the extension is used instead. Note that the name would be suffixed by an ordinal in case of duplicated names as explained above. trigger (tuple or Trigger): Trigger object that determines when to invoke the extension. If it is ``None``, ``extension.trigger`` is used instead. If it is ``None`` and the extension does not have the trigger attribute, the extension is triggered at every iteration by default. If the trigger is not callable, it is passed to :class:`IntervalTrigger` to build an interval trigger. priority (int): Invocation priority of the extension. Extensions are invoked in the descending order of priorities in each iteration. If this is ``None``, ``extension.priority`` is used instead. invoke_before_training (bool or None): If ``True``, the extension is also invoked just before entering the training loop. If this is ``None``, ``extension.invoke_before_training`` is used instead. This option is mainly used for extensions that alter the training configuration (e.g., learning rates); in such a case, resuming from snapshots require the call of extension to recover the configuration before any updates.'
def extend(self, extension, name=None, trigger=None, priority=None, invoke_before_training=None):
if (name is None): name = getattr(extension, 'name', None) if (name is None): name = getattr(extension, 'default_name', None) if (name is None): name = getattr(extension, '__name__', None) if (name is None): raise TypeError('name is not given for the extension') if (name == 'training'): raise ValueError('the name "training" is prohibited as an extension name') if (trigger is None): trigger = getattr(extension, 'trigger', (1, 'iteration')) trigger = trigger_module.get_trigger(trigger) if (priority is None): priority = getattr(extension, 'priority', extension_module.PRIORITY_READER) if (invoke_before_training is None): invoke_before_training = getattr(extension, 'invoke_before_training', False) modified_name = name ordinal = 0 while (modified_name in self._extensions): ordinal += 1 modified_name = ('%s_%d' % (name, ordinal)) extension.name = modified_name self._extensions[modified_name] = _ExtensionEntry(extension, priority, trigger, invoke_before_training)
'Returns the extension of a given name. Args: name (str): Name of the extension. Returns: Extension.'
def get_extension(self, name):
extensions = self._extensions if (name in extensions): return extensions[name].extension else: raise ValueError(('extension %s not found' % name))
'Executes the training loop. This method is the core of ``Trainer``. It executes the whole loop of training the models. Note that this method cannot run multiple times for one trainer object.'
def run(self, show_loop_exception_msg=True):
if self._done: raise RuntimeError('cannot run training loop multiple times') try: os.makedirs(self.out) except OSError: pass extension_order = sorted(self._extensions.keys(), key=(lambda name: self._extensions[name].priority), reverse=True) extensions = [(name, self._extensions[name]) for name in extension_order] self._start_at = _get_time() for (_, entry) in extensions: initializer = getattr(entry.extension, 'initialize', None) if initializer: initializer(self) update = self.updater.update reporter = self.reporter stop_trigger = self.stop_trigger try: while (not stop_trigger(self)): self.observation = {} with reporter.scope(self.observation): update() for (name, entry) in extensions: if entry.trigger(self): entry.extension(self) except Exception as e: if show_loop_exception_msg: print('Exception in main training loop: {}'.format(e), file=sys.stderr) print('Traceback (most recent call last):', file=sys.stderr) traceback.print_tb(sys.exc_info()[2]) print('Will finalize trainer extensions and updater before reraising the exception.', file=sys.stderr) six.reraise(*sys.exc_info()) finally: for (_, entry) in extensions: finalize = getattr(entry.extension, 'finalize', None) if finalize: finalize() self.updater.finalize() self._final_elapsed_time = self.elapsed_time self._done = True
'Gets a child serializer. This operator creates a _child_ serializer represented by the given key. Args: key (str): Name of the child serializer.'
def __getitem__(self, key):
raise NotImplementedError