INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
发送文本消息。 | def send_text_message(self, user_id, content, kf_account=None):
"""
发送文本消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param content: 消息正文
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"touser": us... |
发送图片消息。 | 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):
"""
发送语音消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 发送的语音的媒体ID。 可以通过 :func:`upload_media` 上传。
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
... |
发送音乐消息。 注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。 对此我们也无能为力 ( #197 <https:// github. com/ whtsky/ WeRoBot/ issues/ 197 > _ ) | def send_music_message(
self,
user_id,
url,
hq_url,
thumb_media_id,
title=None,
description=None,
kf_account=None
):
"""
发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/We... |
发送图文消息:: | def send_article_message(self, user_id, articles, kf_account=None):
"""
发送图文消息::
articles = [
{
"title":"Happy Day",
"description":"Is Really A Happy Day",
"url":"URL",
"picurl":"PIC_URL"
... |
发送永久素材中的图文消息。 | def send_news_message(self, user_id, media_id, kf_account=None):
"""
发送永久素材中的图文消息。
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param media_id: 媒体文件 ID
:param kf_account: 发送消息的客服账户,默认值为 None,None 为不指定
:return: 返回的 JSON 数据包
"""
data = {
"... |
发送小程序卡片(要求小程序与公众号已关联) | def send_miniprogrampage_message(
self, user_id, title, appid, pagepath, thumb_media_id, kf_account=None
):
"""
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:p... |
发送模板消息 详情请参考 http:// mp. weixin. qq. com/ wiki/ 17/ 304c1885ea66dbedf7dc170d84999a9d. html | def send_template_message(self, user_id, template_id, data, url=''):
"""
发送模板消息
详情请参考 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param template_id: 模板 ID。
:param data: 用于渲染模板的数据。
:param... |
修改标签 | def update_tag(self, tag_id, tag_name):
"""
修改标签
:param tag_id: 标签 ID
:param tag_name: 新的标签名
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/update",
data={"tag": {
"id": tag_id,
... |
获取标签下粉丝列表 | def get_users_by_tag(self, tag_id, next_open_id=""):
"""
获取标签下粉丝列表
:param tag_id: 标签 ID
:param next_open_id: 第一个拉取用户的 OPENID,默认从头开始拉取
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/user/tag/get",
data={
... |
批量为用户打标签 | def tag_users(self, tag_id, open_id_list):
"""
批量为用户打标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging",
data={
... |
批量为用户取消标签 | def untag_users(self, tag_id, open_id_list):
"""
批量为用户取消标签
:param tag_id: 标签 ID
:param open_id_list: 包含一个或多个用户的 OPENID 的列表
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging",
dat... |
根据 id 获取数据。 | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
try:
session_json = self.db[id]
except KeyError:
session_json = "{}"
return json_loads(session_json) |
对明文进行加密: param text: 需要加密的明文: param app_id: 微信公众平台的 AppID: return: 加密后的字符串 | def encrypt(self, text, app_id):
"""
对明文进行加密
:param text: 需要加密的明文
:param app_id: 微信公众平台的 AppID
:return: 加密后的字符串
"""
text = b"".join(
[
to_binary(self.get_random_string()),
struct.pack(b"I", socket.htonl(len(to_binary(tex... |
对密文进行解密: 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.cipher.decryptor()
plain_text = decryptor.update(base64.b64decode(text)
... |
解密收到的微信消息: 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 timestamp: 请求 URL 中收到的 timestamp
:param nonce: 请求 URL 中收到的 nonce
:param msg_signature: 请求 URL 中收到的 msg_signature
:param encrypt_msg: 收到的加密文本. ( XML 中的 <Encrypt> 部分 )
:ret... |
加密微信回复: param reply: 加密前的回复: type reply: WeChatReply 或 XML 文本: return: 加密后的回复文本 | def encrypt_message(self, reply, timestamp=None, nonce=None):
"""
加密微信回复
:param reply: 加密前的回复
:type reply: WeChatReply 或 XML 文本
:return: 加密后的回复文本
"""
if hasattr(reply, "render"):
reply = reply.render()
timestamp = timestamp or to_text(int(time... |
根据 id 写入数据。 | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
return self.kv.set(self.key_name(id), value) |
为一个 BaseRoBot 生成 Django view。 | def make_view(robot):
"""
为一个 BaseRoBot 生成 Django view。
:param robot: 一个 BaseRoBot 实例。
:return: 一个标准的 Django view
"""
@csrf_exempt
def werobot_view(request):
timestamp = request.GET.get("timestamp", "")
nonce = request.GET.get("nonce", "")
signature = request.GET.ge... |
签名 pay package 需要的参数 详情请参考 支付开发文档 | def create_js_pay_package(self, **package):
"""
签名 pay package 需要的参数
详情请参考 支付开发文档
:param package: 需要签名的的参数
:return: 可以使用的packagestr
"""
assert self.pay_partner_id, "PAY_PARTNER_ID IS EMPTY"
assert self.pay_partner_key, "PAY_PARTNER_KEY IS EMPTY"
... |
签名 js 需要的参数 详情请参考 支付开发文档 | def create_js_pay_params(self, **package):
"""
签名 js 需要的参数
详情请参考 支付开发文档
::
wxclient.create_js_pay_params(
body=标题, out_trade_no=本地订单号, total_fee=价格单位分,
notify_url=通知url,
spbill_create_ip=建议为支付人ip,
)
:param... |
alpha 暂时不建议使用 这个接口使用起来十分不友好 而且会引起巨大的误解 | def create_js_edit_address_param(self, accesstoken, **params):
"""
alpha
暂时不建议使用
这个接口使用起来十分不友好
而且会引起巨大的误解
url 需要带上 code 和 state (url?code=xxx&state=1)
code 和state 是 oauth 时候回来的
token 要传用户的 token
这尼玛 你能相信这些支付接口都是腾讯出的?
"""
params.u... |
创建 native pay url 详情请参考 支付开发文档 | def create_native_pay_url(self, productid):
"""
创建 native pay url
详情请参考 支付开发文档
:param productid: 本地商品ID
:return: 返回URL
"""
params, sign, = self._pay_sign_dict(productid=productid)
params['sign'] = sign
return NATIVE_BASE_URL + urlencode(params) |
通知 腾讯发货 | def pay_deliver_notify(self, **deliver_info):
"""
通知 腾讯发货
一般形式 ::
wxclient.pay_delivernotify(
openid=openid,
transid=transaction_id,
out_trade_no=本地订单号,
deliver_timestamp=int(time.time()),
deliver_status... |
查询订单状态 一般用于无法确定 订单状态时候补偿 | def pay_order_query(self, out_trade_no):
"""
查询订单状态
一般用于无法确定 订单状态时候补偿
:param out_trade_no: 本地订单号
:return: 订单信息dict
"""
package = {
'partner': self.pay_partner_id,
'out_trade_no': out_trade_no,
}
_package = package.items()... |
Get the ASCII int value of a character in a string. | 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
:return: ASCII int value
"""
if six.PY2:
return ord(s[index])
return s[index] |
支付参数签名 | 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({'noncestr... |
为自定义菜单 ( click ) 事件添加 handler 的简便方法。 | def key_click(self, key):
"""
为自定义菜单 ``(click)`` 事件添加 handler 的简便方法。
**@key_click('KEYNAME')** 用来为特定 key 的点击事件添加 handler 方法。
"""
def wraps(f):
argc = len(signature(f).parameters.keys())
@self.click
def onclick(message, session=None):
... |
为文本 ( text ) 消息添加 handler 的简便方法。 | def filter(self, *args):
"""
为文本 ``(text)`` 消息添加 handler 的简便方法。
使用 ``@filter("xxx")``, ``@filter(re.compile("xxx"))``
或 ``@filter("xxx", "xxx2")`` 的形式为特定内容添加 handler。
"""
def wraps(f):
self.add_filter(func=f, rules=list(args))
return f
r... |
为 BaseRoBot 实例添加一个 handler。 | def add_handler(self, func, type='all'):
"""
为 BaseRoBot 实例添加一个 handler。
:param func: 要作为 handler 的方法。
:param type: handler 的种类。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
self._handlers[type]... |
为 BaseRoBot 添加一个 filter handler 。 | def add_filter(self, func, rules):
"""
为 BaseRoBot 添加一个 ``filter handler``。
:param func: 如果 rules 通过,则处理该消息的 handler。
:param rules: 一个 list,包含要匹配的字符串或者正则表达式。
:return: None
"""
if not callable(func):
raise ValueError("{} is not callable".format(func))
... |
解析获取到的 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。
:return: WeRoBot Message
"""
message_dict = parse_xml(body)
if "Encrypt" in message_dict... |
根据 message 的内容获取 Reply 对象。 | def get_reply(self, message):
"""
根据 message 的内容获取 Reply 对象。
:param message: 要处理的 message
:return: 获取的 Reply 对象
"""
session_storage = self.session_storage
id = None
session = None
if session_storage and hasattr(message, "source"):
id ... |
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。 如果可能,对该 Reply 进行加密。 返回 Reply Render 后的文本。 | def get_encrypted_reply(self, message):
"""
对一个指定的 WeRoBot Message ,获取 handlers 处理后得到的 Reply。
如果可能,对该 Reply 进行加密。
返回 Reply Render 后的文本。
:param message: 一个 WeRoBot Message 实例。
:return: reply (纯文本)
"""
reply = self.get_reply(message)
if not reply:
... |
根据时间戳和生成签名的字符串 ( nonce ) 检查签名。 | def check_signature(self, timestamp, nonce, signature):
"""
根据时间戳和生成签名的字符串 (nonce) 检查签名。
:param timestamp: 时间戳
:param nonce: 生成签名的随机字符串
:param signature: 要检查的签名
:return: 如果签名合法将返回 ``True``,不合法将返回 ``False``
"""
return check_signature(
self.conf... |
运行 WeRoBot。 | def run(
self, server=None, host=None, port=None, enable_pretty_logging=True
):
"""
运行 WeRoBot。
:param server: 传递给 Bottle 框架 run 方法的参数,详情见\
`bottle 文档 <https://bottlepy.org/docs/dev/deployment.html#switching-the-server-backend>`_
:param host: 运行时绑定的主机地址
:para... |
根据 id 获取数据。 | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
cur = self.conn.cursor()
cur.execute("SELECT value FROM WeRoBot WHERE id=%s LIMIT 1;", (id, ))
session_json = cur.fetchone()
if session_json is N... |
根据 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。 | def make_view(robot):
"""
为一个 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 ... |
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: Message Object
"""
message["type"] = message.pop("MsgType").lower()
if message["type"] == 'event':
message["type"] = str(message... |
根据 id 写入数据。 | def set(self, id, value):
"""
根据 id 写入数据。
:param id: 要写入的 id
:param value: 要写入的数据,可以是一个 ``dict`` 对象
"""
value = json_dumps(value)
self.conn.cursor().execute(
"INSERT INTO WeRoBot (id, value) VALUES (%s,%s) \
ON DUPLICATE KEY UPDATE val... |
根据 id 获取数据。 | def get(self, id):
"""
根据 id 获取数据。
:param id: 要获取的数据的 id
:return: 返回取到的数据,如果是空则返回一个空的 ``dict`` 对象
"""
id = self.key_name(id)
session_json = self.redis.get(id) or '{}'
return json_loads(session_json) |
根据 id 写入数据。 | 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 删除数据。 | 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 glove. 42B. 300d glove. 840B. 300d glove. twitter. 27B. 25d glove. twitter. 27B. 50d glove. ... | def load_vectors(self, vectors, **kwargs):
"""
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
... |
Set the vectors for the Vocab instance from a collection of Tensors. | def set_vectors(self, stoi, vectors, dim, unk_init=torch.Tensor.zero_):
"""
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.
... |
Create dataset objects for splits of the SST dataset. | def splits(cls, text_field, label_field, root='.data',
train='train.txt', validation='dev.txt', test='test.txt',
train_subtrees=False, **kwargs):
"""Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the... |
Create iterator objects for splits of the SST dataset. | def iters(cls, batch_size=32, device=0, root='.data', vectors=None, **kwargs):
"""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 d... |
Interleave bits from two sort keys to form a joint sort key. | def interleave_keys(a, b):
"""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.
... |
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, "wb") as file:
with tqdm(total=total_size, unit='B',
... |
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 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"""
if six.PY2:
# csv.py doesn't do Unicode; e... |
Create dataset objects for splits of a TranslationDataset. | def splits(cls, exts, fields, path=None, root='.data',
train='train', validation='val', test='test', **kwargs):
"""Create dataset objects for splits of a TranslationDataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tup... |
Create dataset objects for splits of the Multi30k dataset. | def splits(cls, exts, fields, root='.data',
train='train', validation='val', test='test2016', **kwargs):
"""Create dataset objects for splits of the Multi30k dataset.
Arguments:
exts: A tuple containing the extension to path for each language.
fields: A tuple cont... |
Create dataset objects for splits of the IWSLT dataset. | def splits(cls, exts, fields, root='.data',
train='train', validation='IWSLT16.TED.tst2013',
test='IWSLT16.TED.tst2014', **kwargs):
"""Create dataset objects for splits of the IWSLT dataset.
Arguments:
exts: A tuple containing the extension to path for each lan... |
Process a list of examples to create a batch. | def process(self, batch, *args, **kwargs):
""" 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 inp... |
Load a single example using this field tokenizing if necessary. | def preprocess(self, x):
"""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
... |
Process a list of examples to create a torch. Tensor. | def process(self, batch, device=None):
""" 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.Variabl... |
Pad a batch of examples using this field. | def pad(self, minibatch):
"""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
... |
Construct the Vocab object for this field from one or more datasets. | def build_vocab(self, *args, **kwargs):
"""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... |
Turn a batch of examples that use this field into a Variable. | def numericalize(self, arr, device=None):
"""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[in... |
Segment one or more datasets with this subword field. | def segment(self, *args):
"""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 u... |
Preprocess a single example. | def preprocess(self, xs):
"""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... |
Pad a batch of examples using this field. | def pad(self, minibatch):
"""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 lis... |
Construct the Vocab object for nesting field and combine it with this field s vocab. | def build_vocab(self, *args, **kwargs):
"""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
repre... |
Convert a padded minibatch into a variable tensor. | def numericalize(self, arrs, device=None):
"""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 tokeni... |
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:
minibatch.append(ex)
size_so_far = batc... |
Sort within buckets then batch then shuffle batches. | def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count,
random_shuffler=None, shuffle=False, sort_within_batch=False):
"""Sort within buckets, then batch, then shuffle batches.
Partitions data into chunks of size 100*batch_size, sorts examples within
each chunk using sort_ke... |
Create Iterator objects for multiple splits of a dataset. | def splits(cls, datasets, batch_sizes=None, **kwargs):
"""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 bat... |
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.random_shuffler(range(len(self.dataset)))]
else:
x... |
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.random_state
self.create_batches()
... |
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()
for k, v in kwargs.items():
setattr... |
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 Version 2 POS Tagged
data.
"""
return super(UDPOS, cls).split... |
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 the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... |
Create dataset objects for splits of the IMDB dataset. | def splits(cls, text_field, label_field, root='.data',
train='train', test='test', **kwargs):
"""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 fo... |
Create dataset objects for splits of the WikiText - 2 dataset. | def splits(cls, text_field, root='.data', train='wiki.train.tokens',
validation='wiki.valid.tokens', test='wiki.test.tokens',
**kwargs):
"""Create dataset objects for splits of the WikiText-2 dataset.
This is the most flexible way to use the dataset.
Arguments:
... |
Create iterator objects for splits of the WikiText - 2 dataset. | def iters(cls, batch_size=32, bptt_len=35, device=0, root='.data',
vectors=None, **kwargs):
"""Create iterator objects for splits of the WikiText-2 dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... |
Apply _only_ the convert_token function of the current pipeline to the input. If the input is a list a list with the results of applying the convert_token function to all input elements is returned. | def call(self, x, *args):
"""Apply _only_ the convert_token function of the current pipeline
to the input. If the input is a list, a list with the results of
applying the `convert_token` function to all input elements is
returned.
Arguments:
x: The input to apply the... |
Add a Pipeline to be applied before this processing pipeline. | def add_before(self, pipeline):
"""Add a Pipeline to be applied before this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply before this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... |
Add a Pipeline to be applied after this processing pipeline. | def add_after(self, pipeline):
"""Add a Pipeline to be applied after this processing pipeline.
Arguments:
pipeline: The Pipeline or callable to apply after this
Pipeline.
"""
if not isinstance(pipeline, Pipeline):
pipeline = Pipeline(pipeline)
... |
Check that the split ratio argument is not malformed | def check_split_ratio(split_ratio):
"""Check that the split ratio argument is not malformed"""
valid_ratio = 0.
if isinstance(split_ratio, float):
# Only the train set relative ratio is provided
# Assert in bounds, validation size is zero
assert 0. < split_ratio < 1., (
"... |
Create train - test ( - valid? ) splits from the instance s examples. | def split(self, split_ratio=0.7, stratified=False, strata_field='label',
random_state=None):
"""Create train-test(-valid?) splits from the instance's examples.
Arguments:
split_ratio (float or List of floats): a number [0, 1] denoting the amount
of data to be u... |
Download and unzip an online archive (. zip. gz or. tgz ). | def download(cls, root, check=None):
"""Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
... |
Remove unknown words from dataset examples with respect to given field. | def filter_examples(self, field_names):
"""Remove unknown words from dataset examples with respect to given field.
Arguments:
field_names (list(str)): Within example only the parts with field names in
field_names will have their unknown words deleted.
"""
for... |
Create dataset objects for splits of the SNLI dataset. | def splits(cls, text_field, label_field, parse_field=None,
extra_fields={}, root='.data', train='train.jsonl',
validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
A... |
Create iterator objects for splits of the SNLI dataset. | def iters(cls, batch_size=32, device=0, root='.data',
vectors=None, trees=False, **kwargs):
"""Create iterator objects for splits of the SNLI dataset.
This is the simplest way to use the dataset, and assumes common
defaults for field, vocabulary, and iterator parameters.
... |
Decode given bytes using specified escaping method.: param byte_data: The byte - like object with bytes to decode.: param escape: The escape method to use.: param skip_printable: If True don t escape byte_data with all printable ASCII bytes. Defaults to False.: return: New unicode string escaped with the specified meth... | def bytes_to_unicode(byte_data, escape, skip_printable=False):
"""
Decode given bytes using specified escaping method.
:param byte_data: The byte-like object with bytes to decode.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ASCI... |
Apply the specified escape method on the given bytes.: param byte_data: The byte - like object with bytes to escape.: param escape: The escape method to use.: param skip_printable: If True don t escape byte_data with all printable ASCII bytes. Defaults to False.: return: new bytes object with the escaped bytes or byte_... | def apply_escape_bytes(byte_data, escape, skip_printable=False):
"""
Apply the specified escape method on the given bytes.
:param byte_data: The byte-like object with bytes to escape.
:param escape: The escape method to use.
:param skip_printable: If True, don't escape byte_data with all 'printable ... |
decode module id to string based on | def _decode_module_id(self, module_id):
"""
decode module id to string
based on @antirez moduleTypeNameByID function from redis/src/module.c
:param module_id: 64bit integer
:return: string
"""
name = [''] * 9
module_id >>= 10
for i in reversed(rang... |
Return the step value in format suitable for display. | def format_step(step, zero_prefix=False):
"""Return the step value in format suitable for display."""
if isinstance(step, int):
return "{:06}".format(step) if zero_prefix else "{}".format(step)
elif isinstance(step, tuple):
return "{:04}:{:06}".format(*step) if zero_prefix else "{}:{}".forma... |
Record metrics at a specific step. E. g. | def log(self, step, **kwargs):
"""Record metrics at a specific step. E.g.
my_history.log(34, loss=2.3, accuracy=0.2)
Okay to call multiple times for the same step. New values overwrite
older ones if they have the same metric name.
step: An integer or tuple of integers. If a tu... |
Returns the total period between when the first and last steps where logged. This usually correspnods to the total training time if there were no gaps in the training. | def get_total_time(self):
"""Returns the total period between when the first and last steps
where logged. This usually correspnods to the total training time
if there were no gaps in the training.
"""
first_step = self.steps[0]
last_step = self.steps[-1]
seconds =... |
Returns nodes connecting out of the given node ( or list of nodes ). | def outgoing(self, node):
"""Returns nodes connecting out of the given node (or list of nodes)."""
nodes = node if isinstance(node, list) else [node]
node_ids = [self.id(n) for n in nodes]
# Find edges outgoing from this group but not incoming to it
outgoing = [self[e[1]] for e i... |
Returns all nodes that share the same parent ( incoming node ) with the given node including the node itself. | def siblings(self, node):
"""Returns all nodes that share the same parent (incoming node) with
the given node, including the node itself.
"""
incoming = self.incoming(node)
# TODO: Not handling the case of multiple incoming nodes yet
if len(incoming) == 1:
inc... |
Remove a node and its edges. | def remove(self, nodes):
"""Remove a node and its edges."""
nodes = nodes if isinstance(nodes, list) else [nodes]
for node in nodes:
k = self.id(node)
self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges))
del self.nodes[k] |
Replace nodes with node. Edges incoming to nodes [ 0 ] are connected to the new node and nodes outgoing from nodes [ - 1 ] become outgoing from the new node. | def replace(self, nodes, node):
"""Replace nodes with node. Edges incoming to nodes[0] are connected to
the new node, and nodes outgoing from nodes[-1] become outgoing from
the new node."""
nodes = nodes if isinstance(nodes, list) else [nodes]
# Is the new node part of the replac... |
Searches the graph for a sub - graph that matches the given pattern and returns the first match it finds. | def search(self, pattern):
"""Searches the graph for a sub-graph that matches the given pattern
and returns the first match it finds.
"""
for node in self.nodes.values():
match, following = pattern.match(self, node)
if match:
return match, followin... |
Make up an ID for a sequence ( list ) of nodes. Note: getrandbits () is very uninformative as a readable ID. Here we build a name such that when the mouse hovers over the drawn node in Jupyter one can figure out which original nodes make up the sequence. This is actually quite useful. | def sequence_id(self, sequence):
"""Make up an ID for a sequence (list) of nodes.
Note: `getrandbits()` is very uninformative as a "readable" ID. Here, we build a name
such that when the mouse hovers over the drawn node in Jupyter, one can figure out
which original nodes make up the sequ... |
Generate a GraphViz Dot graph. | def build_dot(self):
"""Generate a GraphViz Dot graph.
Returns a GraphViz Digraph object.
"""
from graphviz import Digraph
# Build GraphViz Digraph
dot = Digraph()
dot.attr("graph",
bgcolor=self.theme["background_color"],
color... |
Standardize data types. Converts PyTorch tensors to Numpy arrays and Numpy scalars to Python scalars. | def to_data(value):
"""Standardize data types. Converts PyTorch tensors to Numpy arrays,
and Numpy scalars to Python scalars."""
# TODO: Use get_framework() for better detection.
if value.__class__.__module__.startswith("torch"):
import torch
if isinstance(value, torch.nn.parameter.Param... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.