text
stringlengths
81
112k
在一个 Python 文件中读取配置。 :param filename: 配置文件的文件名 :return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常 def from_pyfile(self, filename): """ 在一个 Python 文件中读取配置。 :param filename: 配置文件的文件名 :return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常 """ d = types.ModuleType('config') ...
为一个 BaseRoBot 生成 Tornado Handler。 Usage :: import tornado.ioloop import tornado.web from werobot import WeRoBot from tornado_werobot import make_handler robot = WeRoBot(token='token') @robot.handler def hello(message): return 'Hello World!' ...
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ document = self._get_document(id) if document: session_j...
根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 def set(self, id, value): """ 根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 """ session = json_dumps(value) self.collection.replace_one( ...
获取 Access Token。 :return: 返回的 JSON 数据包 def grant_token(self): """ 获取 Access Token。 :return: 返回的 JSON 数据包 """ return self.get( url="https://api.weixin.qq.com/cgi-bin/token", params={ "grant_type": "client_credential", ...
判断现有的token是否过期。 用户需要多进程或者多机部署可以手动重写这个函数 来自定义token的存储,刷新策略。 :return: 返回token def get_access_token(self): """ 判断现有的token是否过期。 用户需要多进程或者多机部署可以手动重写这个函数 来自定义token的存储,刷新策略。 :return: 返回token """ if self._token: now = time.time() ...
创建个性化菜单:: button = [ { "type":"click", "name":"今日歌曲", "key":"V1001_TODAY_MUSIC" }, { "name":"菜单", "sub_button":[ { ...
添加客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param password: 客服账号的密码 :return: 返回的 JSON 数据包 def add_custom_service_account(self, account, nickname, password): """ 添加客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param pass...
修改客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param password: 客服账号的密码 :return: 返回的 JSON 数据包 def update_custom_service_account(self, account, nickname, password): """ 修改客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param p...
删除客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param password: 客服账号的密码 :return: 返回的 JSON 数据包 def delete_custom_service_account(self, account, nickname, password): """ 删除客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param p...
设置客服帐号的头像。 :param account: 客服账号的用户名 :param avatar: 头像文件,必须是 jpg 格式 :return: 返回的 JSON 数据包 def upload_custom_service_account_avatar(self, account, avatar): """ 设置客服帐号的头像。 :param account: 客服账号的用户名 :param avatar: 头像文件,必须是 jpg 格式 :return: 返回的 JSON 数据包 ...
下载临时多媒体文件。 :param media_id: 媒体文件 ID :return: requests 的 Response 实例 def download_media(self, media_id): """ 下载临时多媒体文件。 :param media_id: 媒体文件 ID :return: requests 的 Response 实例 """ return requests.get( url="https://api.weixin.qq.com/cgi-bin/m...
上传图文消息内的图片。 :param file: 要上传的文件,一个 File-object :return: 返回的 JSON 数据包 def upload_news_picture(self, file): """ 上传图文消息内的图片。 :param file: 要上传的文件,一个 File-object :return: 返回的 JSON 数据包 """ return self.post( url="https://api.weixin.qq.com/cgi-bin/m...
上传其他类型永久素材。 :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)和缩略图(thumb) :param media_file: 要上传的文件,一个 File-object :return: 返回的 JSON 数据包 def upload_permanent_media(self, media_type, media_file): """ 上传其他类型永久素材。 :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)和缩略图(thumb) ...
上传永久视频。 :param title: 视频素材的标题 :param introduction: 视频素材的描述 :param video: 要上传的视频,一个 File-object :return: requests 的 Response 实例 def upload_permanent_video(self, title, introduction, video): """ 上传永久视频。 :param title: 视频素材的标题 :param introduction: 视频素材的描述 ...
获取永久素材。 :param media_id: 媒体文件 ID :return: requests 的 Response 实例 def download_permanent_media(self, media_id): """ 获取永久素材。 :param media_id: 媒体文件 ID :return: requests 的 Response 实例 """ return requests.post( url="https://api.weixin.qq.com/cgi-...
获取素材列表。 :param media_type: 素材的类型,图片(image)、视频(video)、语音 (voice)、图文(news) :param offset: 从全部素材的该偏移位置开始返回,0表示从第一个素材返回 :param count: 返回素材的数量,取值在1到20之间 :return: 返回的 JSON 数据包 def get_media_list(self, media_type, offset, count): """ 获取素材列表。 :param media_type: 素材的类型,图...
创建分组。 :param name: 分组名字(30个字符以内) :return: 返回的 JSON 数据包 def create_group(self, name): """ 创建分组。 :param name: 分组名字(30个字符以内) :return: 返回的 JSON 数据包 """ name = to_text(name) return self.post( url="https://api.weixin.qq.com/cgi-bin/groups...
修改分组名。 :param group_id: 分组 ID,由微信分配 :param name: 分组名字(30个字符以内) :return: 返回的 JSON 数据包 def update_group(self, group_id, name): """ 修改分组名。 :param group_id: 分组 ID,由微信分配 :param name: 分组名字(30个字符以内) :return: 返回的 JSON 数据包 """ return self.post( ...
批量移动用户分组。 :param user_id_list: 用户 ID 的列表(长度不能超过50) :param group_id: 分组 ID :return: 返回的 JSON 数据包 def move_users(self, user_id_list, group_id): """ 批量移动用户分组。 :param user_id_list: 用户 ID 的列表(长度不能超过50) :param group_id: 分组 ID :return: 返回的 JSON 数据包 """...
设置备注名。 :param user_id: 设置备注名的用户 ID :param remark: 新的备注名,长度必须小于30字符 :return: 返回的 JSON 数据包 def remark_user(self, user_id, remark): """ 设置备注名。 :param user_id: 设置备注名的用户 ID :param remark: 新的备注名,长度必须小于30字符 :return: 返回的 JSON 数据包 """ return self...
获取用户基本信息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 def get_user_info(self, user_id, lang="zh_CN"): """ 获取用户基本信息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param lang: 返回国家地区...
批量获取用户基本信息。 :param user_id_list: 用户 ID 的列表 :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 :return: 返回的 JSON 数据包 def get_users_info(self, user_id_list, lang="zh_CN"): """ 批量获取用户基本信息。 :param user_id_list: 用户 ID 的列表 :param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语...
获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 def get_followers(self, first_user_id=None): """ 获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param ...
发送文本消息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param content: 消息正文 :param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定 :return: 返回的 JSON 数据包 def send_text_message(self, user_id, content, kf_account=None): """ 发送文本消息。 :param user_id: 用户 ID 。 就是你收到的 `Mes...
发送图片消息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param media_id: 图片的媒体ID。 可以通过 :func:`upload_media` 上传。 :param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定 :return: 返回的 JSON 数据包 def send_image_message(self, user_id, media_id, kf_account=None): """ 发送图片消息。 ...
发送语音消息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。 :param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定 :return: 返回的 JSON 数据包 def send_voice_message(self, user_id, media_id, kf_account=None): """ 发送语音消息。 ...
发送音乐消息。 注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。 对此我们也无能为力 ( `#197 <https://github.com/whtsky/WeRoBot/issues/197>`_ ) :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url: 音乐链接 :param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐 :param thumb_media_id: 缩略图的媒体ID。 可以通过 :fun...
发送图文消息:: articles = [ { "title":"Happy Day", "description":"Is Really A Happy Day", "url":"URL", "picurl":"PIC_URL" }, { "title":"Happy Day", ...
发送永久素材中的图文消息。 :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param media_id: 媒体文件 ID :param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定 :return: 返回的 JSON 数据包 def send_news_message(self, user_id, media_id, kf_account=None): """ 发送永久素材中的图文消息。 :param user_id: 用户...
发送小程序卡片(要求小程序与公众号已关联) :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param title: 小程序卡片的标题 :param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系 :param pagepath: 小程序的页面路径,跟 app.json 对齐,支持参数,比如 pages/index/index?foo=bar :param thumb_media_id: 小程序卡片图片的媒体 ID,小程序卡片图片建议大小为 520*416 ...
发送模板消息 详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param template_id: 模板 ID。 :param data: 用于渲染模板的数据。 :param url: 模板消息的可选链接。 :return: 返回的 JSON 数据包 def send_template_message(self, user_id, ...
修改标签 :param tag_id: 标签 ID :param tag_name: 新的标签名 :return: 返回的 JSON 数据包 def update_tag(self, tag_id, tag_name): """ 修改标签 :param tag_id: 标签 ID :param tag_name: 新的标签名 :return: 返回的 JSON 数据包 """ return self.post( url="https://api....
获取标签下粉丝列表 :param tag_id: 标签 ID :param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取 :return: 返回的 JSON 数据包 def get_users_by_tag(self, tag_id, next_open_id=""): """ 获取标签下粉丝列表 :param tag_id: 标签 ID :param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取 :return: 返回的 JSON 数据...
批量为用户打标签 :param tag_id: 标签 ID :param open_id_list: 包含一个或多个用户的 OPENID 的列表 :return: 返回的 JSON 数据包 def tag_users(self, tag_id, open_id_list): """ 批量为用户打标签 :param tag_id: 标签 ID :param open_id_list: 包含一个或多个用户的 OPENID 的列表 :return: 返回的 JSON 数据包 """ ...
批量为用户取消标签 :param tag_id: 标签 ID :param open_id_list: 包含一个或多个用户的 OPENID 的列表 :return: 返回的 JSON 数据包 def untag_users(self, tag_id, open_id_list): """ 批量为用户取消标签 :param tag_id: 标签 ID :param open_id_list: 包含一个或多个用户的 OPENID 的列表 :return: 返回的 JSON 数据包 """ ...
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ try: session_json = self.db[id] except KeyError: ...
对明文进行加密 :param text: 需要加密的明文 :param app_id: 微信公众平台的 AppID :return: 加密后的字符串 def encrypt(self, text, app_id): """ 对明文进行加密 :param text: 需要加密的明文 :param app_id: 微信公众平台的 AppID :return: 加密后的字符串 """ text = b"".join( [ t...
对密文进行解密 :param text: 需要解密的密文 :param app_id: 微信公众平台的 AppID :return: 解密后的字符串 def decrypt(self, text, app_id): """ 对密文进行解密 :param text: 需要解密的密文 :param app_id: 微信公众平台的 AppID :return: 解密后的字符串 """ text = to_binary(text) decryptor = self....
解密收到的微信消息 :param timestamp: 请求 URL 中收到的 timestamp :param nonce: 请求 URL 中收到的 nonce :param msg_signature: 请求 URL 中收到的 msg_signature :param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 ) :return: 解密后的 XML 文本 def decrypt_message(self, timestamp, nonce, msg_signature, encrypt_msg): ...
加密微信回复 :param reply: 加密前的回复 :type reply: WeChatReply 或 XML 文本 :return: 加密后的回复文本 def encrypt_message(self, reply, timestamp=None, nonce=None): """ 加密微信回复 :param reply: 加密前的回复 :type reply: WeChatReply 或 XML 文本 :return: 加密后的回复文本 """ if hasatt...
根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 def set(self, id, value): """ 根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 """ return self.kv.set(self.key_name(id), value)
为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view def make_view(robot): """ 为一个 BaseRoBot 生成 Django view。 :param robot: 一个 BaseRoBot 实例。 :return: 一个标准的 Django view """ @csrf_exempt def werobot_view(request): timestamp = request.GET.ge...
签名 pay package 需要的参数 详情请参考 支付开发文档 :param package: 需要签名的的参数 :return: 可以使用的packagestr def create_js_pay_package(self, **package): """ 签名 pay package 需要的参数 详情请参考 支付开发文档 :param package: 需要签名的的参数 :return: 可以使用的packagestr """ assert self.pay_p...
签名 js 需要的参数 详情请参考 支付开发文档 :: wxclient.create_js_pay_params( body=标题, out_trade_no=本地订单号, total_fee=价格单位分, notify_url=通知url, spbill_create_ip=建议为支付人ip, ) :param package: 需要签名的的参数 :return: 支付需要的对象 def create_js_pay_...
alpha 暂时不建议使用 这个接口使用起来十分不友好 而且会引起巨大的误解 url 需要带上 code 和 state (url?code=xxx&state=1) code 和state 是 oauth 时候回来的 token 要传用户的 token 这尼玛 你能相信这些支付接口都是腾讯出的? def create_js_edit_address_param(self, accesstoken, **params): """ alpha 暂时不建议使用 ...
创建 native pay url 详情请参考 支付开发文档 :param productid: 本地商品ID :return: 返回URL def create_native_pay_url(self, productid): """ 创建 native pay url 详情请参考 支付开发文档 :param productid: 本地商品ID :return: 返回URL """ params, sign, = self._pay_sign_dict(produc...
通知 腾讯发货 一般形式 :: wxclient.pay_delivernotify( openid=openid, transid=transaction_id, out_trade_no=本地订单号, deliver_timestamp=int(time.time()), deliver_status="1", deliver_msg="ok" ) :par...
查询订单状态 一般用于无法确定 订单状态时候补偿 :param out_trade_no: 本地订单号 :return: 订单信息dict def pay_order_query(self, out_trade_no): """ 查询订单状态 一般用于无法确定 订单状态时候补偿 :param out_trade_no: 本地订单号 :return: 订单信息dict """ package = { 'partner': self.pay_par...
Get the ASCII int value of a character in a string. :param s: a string :param index: the position of desired character :return: ASCII int value def byte2int(s, index=0): """Get the ASCII int value of a character in a string. :param s: a string :param index: the position of desired character ...
支付参数签名 def pay_sign_dict( appid, pay_sign_key, add_noncestr=True, add_timestamp=True, add_appid=True, **kwargs ): """ 支付参数签名 """ assert pay_sign_key, "PAY SIGN KEY IS EMPTY" if add_appid: kwargs.update({'appid': appid}) if add_noncestr: kwargs.update({'...
为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。 **@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。 def key_click(self, key): """ 为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。 **@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。 """ def wraps(f): argc = len(signatu...
为文本 ``(text)`` 消息添加 handler 的简便方法。 使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))`` 或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。 def filter(self, *args): """ 为文本 ``(text)`` 消息添加 handler 的简便方法。 使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))`` 或 ``@filter("...
为 BaseRoBot 实例添加一个 handler。 :param func: 要作为 handler 的方法。 :param type: handler 的种类。 :return: None def add_handler(self, func, type='all'): """ 为 BaseRoBot 实例添加一个 handler。 :param func: 要作为 handler 的方法。 :param type: handler 的种类。 :return: None """ ...
为 BaseRoBot 添加一个 ``filter handler``。 :param func: 如果 rules 通过,则处理该消息的 handler。 :param rules: 一个 list,包含要匹配的字符串或者正则表达式。 :return: None def add_filter(self, func, rules): """ 为 BaseRoBot 添加一个 ``filter handler``。 :param func: 如果 rules 通过,则处理该消息的 handler。 :param rul...
解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。 :param body: 微信服务器发来的请求中的 Body。 :return: WeRoBot Message def parse_message( self, body, timestamp=None, nonce=None, msg_signature=None ): """ 解析获取到的 Raw XML ,如果需要的话进行解密,返回 WeRoBot Message。 :param body: 微信服务器发来的请求中的 Body。...
根据 message 的内容获取 Reply 对象。 :param message: 要处理的 message :return: 获取的 Reply 对象 def get_reply(self, message): """ 根据 message 的内容获取 Reply 对象。 :param message: 要处理的 message :return: 获取的 Reply 对象 """ session_storage = self.session_storage id = None ...
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。 如果可能,对该 Reply 进行加密。 返回 Reply Render 后的文本。 :param message: 一个 WeRoBot Message 实例。 :return: reply (纯文本) def get_encrypted_reply(self, message): """ 对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。 如果可能,对该 Reply 进行...
根据时间戳和生成签名的字符串 (nonce) 检查签名。 :param timestamp: 时间戳 :param nonce: 生成签名的随机字符串 :param signature: 要检查的签名 :return: 如果签名合法将返回 ``True``,不合法将返回 ``False`` def check_signature(self, timestamp, nonce, signature): """ 根据时间戳和生成签名的字符串 (nonce) 检查签名。 :param timestamp: 时间戳 ...
运行 WeRoBot。 :param server: 传递给 Bottle 框架 run 方法的参数,详情见\ `bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_ :param host: 运行时绑定的主机地址 :param port: 运行时绑定的主机端口 :param enable_pretty_logging: 是否开启 log 的输出格式优化 def run( self, server=None, h...
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ cur = self.conn.cursor() cur.execute("SELECT value FROM WeRoBot WHER...
根据 id 删除数据。 :param id: 要删除的数据的 id def delete(self, id): """ 根据 id 删除数据。 :param id: 要删除的数据的 id """ self.conn.cursor().execute("DELETE FROM WeRoBot WHERE id=%s", (id, )) self.conn.commit()
为一个 BaseRoBot 生成 Bottle view。 Usage :: from werobot import WeRoBot robot = WeRoBot(token='token') @robot.handler def hello(message): return 'Hello World!' from bottle import Bottle from werobot.contrib.bottle import make_view app = Bottle() ...
Process a message dict and return a Message Object :param message: Message dict returned by `parse_xml` function :return: Message Object def process_message(message): """ Process a message dict and return a Message Object :param message: Message dict returned by `parse_xml` function :return: Me...
根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 def set(self, id, value): """ 根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 """ value = json_dumps(value) self.conn.cursor().execute( "INSE...
根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 def get(self, id): """ 根据 id 获取数据。 :param id: 要获取的数据的 id :return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象 """ id = self.key_name(id) session_json = self.redis.get(id) or '{}' ...
根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 def set(self, id, value): """ 根据 id 写入数据。 :param id: 要写入的 id :param value: 要写入的数据,可以是一个 ``dict`` 对象 """ id = self.key_name(id) self.redis.set(id, json_dumps(value))
根据 id 删除数据。 :param id: 要删除的数据的 id def delete(self, id): """ 根据 id 删除数据。 :param id: 要删除的数据的 id """ id = self.key_name(id) self.redis.delete(id)
Arguments: vectors: one of or a list containing instantiations of the GloVe, CharNGram, or Vectors classes. Alternatively, one of or a list of available pretrained vectors: charngram.100d fasttext.en.300d fasttext.simple.300d ...
Set the vectors for the Vocab instance from a collection of Tensors. Arguments: stoi: A dictionary of string to the index of the associated vector in the `vectors` input argument. vectors: An indexed iterable (or other structure supporting __getitem__) that ...
Create dataset objects for splits of the SST dataset. Arguments: text_field: The field that will be used for the sentence. label_field: The field that will be used for label data. root: The root directory that the dataset's zip archive will be expanded into; ...
Create iterator objects for splits of the SST dataset. Arguments: batch_size: Batch_size device: Device to create batches on. Use - 1 for CPU and None for the currently active GPU device. root: The root directory that the dataset's zip archive will be ...
Interleave bits from two sort keys to form a joint sort key. Examples that are similar in both of the provided keys will have similar values for the key defined by this function. Useful for tasks with two text fields like machine translation or natural language inference. def interleave_keys(a, b): ""...
Use a specific RNG state. def use_internal_state(self): """Use a specific RNG state.""" old_state = random.getstate() random.setstate(self._random_state) yield self._random_state = random.getstate() random.setstate(old_state)
Download file, with logic (from tensor2tensor) for Google Drive def download_from_url(url, path): """Download file, with logic (from tensor2tensor) for Google Drive""" def process_response(r): chunk_size = 16 * 1024 total_size = int(r.headers.get('Content-length', 0)) with open(path, "w...
Since the standard csv library does not handle unicode in Python 2, we need a wrapper. Borrowed and slightly modified from the Python docs: https://docs.python.org/2/library/csv.html#csv-examples def unicode_csv_reader(unicode_csv_data, **kwargs): """Since the standard csv library does not handle unicode i...
Create dataset objects for splits of a TranslationDataset. Arguments: exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data in each language. path (str): Common prefix of the splits'...
Create dataset objects for splits of the Multi30k dataset. Arguments: exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data in each language. root: Root dataset storage directory. De...
Create dataset objects for splits of the IWSLT dataset. Arguments: exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data in each language. root: Root dataset storage directory. Defau...
Process a list of examples to create a batch. Postprocess the batch with user-provided Pipeline. Args: batch (list(object)): A list of object from a batch of examples. Returns: object: Processed object given the input and custom postprocessing Pipeline. def...
Load a single example using this field, tokenizing if necessary. If the input is a Python 2 `str`, it will be converted to Unicode first. If `sequential=True`, it will be tokenized. Then the input will be optionally lowercased and passed to the user-provided `preprocessing` Pipeline. d...
Process a list of examples to create a torch.Tensor. Pad, numericalize, and postprocess a batch and create a tensor. Args: batch (list(object)): A list of object from a batch of examples. Returns: torch.autograd.Variable: Processed object given the input and...
Pad a batch of examples using this field. Pads to self.fix_length if provided, otherwise pads to the length of the longest example in the batch. Prepends self.init_token and appends self.eos_token if those attributes are not None. Returns a tuple of the padded list and a list containing...
Construct the Vocab object for this field from one or more datasets. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that represents the set of possible values for this field. If ...
Turn a batch of examples that use this field into a Variable. If the field has include_lengths=True, a tensor of lengths will be included in the return value. Arguments: arr (List[List[str]], or tuple of (List[List[str]], List[int])): List of tokenized and padded ex...
Segment one or more datasets with this subword field. Arguments: Positional arguments: Dataset objects or other indexable mutable sequences to segment. If a Dataset object is provided, all columns corresponding to this field are used; individual colum...
Preprocess a single example. Firstly, tokenization and the supplied preprocessing pipeline is applied. Since this field is always sequential, the result is a list. Then, each element of the list is preprocessed using ``self.nesting_field.preprocess`` and the resulting list is returned. ...
Pad a batch of examples using this field. If ``self.nesting_field.sequential`` is ``False``, each example in the batch must be a list of string tokens, and pads them as if by a ``Field`` with ``sequential=True``. Otherwise, each example must be a list of list of tokens. Using ``self.nes...
Construct the Vocab object for nesting field and combine it with this field's vocab. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that represents the set of possible values for the nesting fi...
Convert a padded minibatch into a variable tensor. Each item in the minibatch will be numericalized independently and the resulting tensors will be stacked at the first dimension. Arguments: arr (List[List[str]]): List of tokenized and padded examples. device (str or to...
Yield elements from data in chunks of batch_size. def batch(data, batch_size, batch_size_fn=None): """Yield elements from data in chunks of batch_size.""" if batch_size_fn is None: def batch_size_fn(new, count, sofar): return count minibatch, size_so_far = [], 0 for ex in data: ...
Sort within buckets, then batch, then shuffle batches. Partitions data into chunks of size 100*batch_size, sorts examples within each chunk using sort_key, then batch these examples and shuffle the batches. def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count, random_shuf...
Create Iterator objects for multiple splits of a dataset. Arguments: datasets: Tuple of Dataset objects corresponding to the splits. The first such object should be the train set. batch_sizes: Tuple of batch sizes to use for the different splits, or None ...
Return the examples in the dataset in order, sorted, or shuffled. def data(self): """Return the examples in the dataset in order, sorted, or shuffled.""" if self.sort: xs = sorted(self.dataset, key=self.sort_key) elif self.shuffle: xs = [self.dataset[i] for i in self.ran...
Set up the batch generator for a new epoch. def init_epoch(self): """Set up the batch generator for a new epoch.""" if self._restored_from_state: self.random_shuffler.random_state = self._random_state_this_epoch else: self._random_state_this_epoch = self.random_shuffler...
Create a Batch directly from a number of Variables. def fromvars(cls, dataset, batch_size, train=None, **kwargs): """Create a Batch directly from a number of Variables.""" batch = cls() batch.batch_size = batch_size batch.dataset = dataset batch.fields = dataset.fields.keys() ...
Downloads and loads the Universal Dependencies Version 2 POS Tagged data. def splits(cls, fields, root=".data", train="en-ud-tag.v2.train.txt", validation="en-ud-tag.v2.dev.txt", test="en-ud-tag.v2.test.txt", **kwargs): """Downloads and loads the Universal Dependencies Ver...
Downloads and loads the CoNLL 2000 Chunking dataset. NOTE: There is only a train and test dataset so we use 10% of the train set as validation def splits(cls, fields, root=".data", train="train.txt", test="test.txt", validation_frac=0.1, **kwargs): """Downloads and loads th...
Create dataset objects for splits of the IMDB dataset. Arguments: text_field: The field that will be used for the sentence. label_field: The field that will be used for label data. root: Root dataset storage directory. Default is '.data'. train: The directory tha...
Create dataset objects for splits of the WikiText-2 dataset. This is the most flexible way to use the dataset. Arguments: text_field: The field that will be used for text data. root: The root directory that the dataset's zip archive will be expanded into; theref...