INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_date : bool Whether or not to count the asset as alive on its start_date....
def lifetimes(self, dates, include_start_date, country_codes): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_da...
Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in this country.
def equities_sids_for_country_code(self, country_code): """Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in t...
Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window. Returns ------- ...
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of in...
Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string The OHLVC name for the desired data point. Returns -...
def get_value(self, continuous_future, dt, field): """ Retrieve the value at the given coordinates. Parameters ---------- sid : int The asset identifier. dt : pd.Timestamp The timestamp for the desired data point. field : string ...
Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the last traded minute. dt : pd.Timestamp Th...
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the...
Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window....
def load_raw_arrays(self, columns, start_date, end_date, assets): """ Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the wi...
Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price times number of shares held times the multiplier.
def current_portfolio_weights(self): """ Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price time...
将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 } hosting_callback : callable 托管回调函数,传入单个图片链接,返回托管后的图片链接...
def __hosting_wechat_img(self, content_info, hosting_callback): """将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 }...
获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_callback : callable 处理出现验证码页面的函数,参见 unlock_callback_example identify_image_callback : callable ...
def get_gzh_info(self, wecgat_id_or_name, unlock_callback=None, identify_image_callback=None, decode_url=True): """获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_ca...
搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Par...
def search_gzh(self, keyword, page=1, unlock_callback=None, identify_image_callback=None, decode_url=True): """搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注...
搜索 文章 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Para...
def search_article(self, keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None, unlock_callback=None, identify_image_callback=None, decode_u...
从 公众号的最近10条群发页面 提取公众号信息 和 文章列表信息 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_...
def get_gzh_article_by_history(self, keyword=None, url=None, unlock_callback_sogou=None, identify_image_callback_sogou=None, unlock_callback_weixin=None, identify_image_callback_we...
获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公...
def get_gzh_article_by_hot(self, hot_index, page=1, unlock_callback=None, identify_image_callback=None): """获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ...
获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : bool True: 返回原始html False: 返回处理后的html del_qqmusic: bool True:微信原文中有插入的qq音乐,则删除 False:微信源文中有插入的qq音乐,则保留 del_mpvoice: bool Tru...
def get_article_content(self, url, del_qqmusic=True, del_mpvoice=True, unlock_callback=None, identify_image_callback=None, hosting_callback=None, raw=False): """获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : boo...
获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException
def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException """ url = 'http://w.sug...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
def unlock_sogou_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : b...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
def unlock_weixin_callback_example(url, req, resp, img, identify_image_callback): """手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : ...
拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 timesn : WechatSogouConst.search_article_time 时间 anytime 没有限制 / day 一天 / week 一周 / month 一月 / year 一年 / specific 自定 默认是 anytim...
def gen_search_article_url(keyword, page=1, timesn=WechatSogouConst.search_article_time.anytime, article_type=WechatSogouConst.search_article_type.all, ft=None, et=None): """拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 ...
拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url
def gen_search_gzh_url(keyword, page=1): """拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url """ assert isinst...
拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url
def gen_hot_url(hot_index, page=1): """拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url """ ...
抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字
def get_first_of_element(element, sub, contype=None): """抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 """ content = element.xpath(sub) return list_or_empty(content, contype)
获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码
def get_encoding_from_reponse(r): """获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 """ encoding = requests.utils.get_encodings_from_content(r.text) return encoding[0] if encoding else requests.utils.get_encoding_from_headers(r.headers)
替换html‘"’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字
def _replace_str_html(s): """替换html‘&quot;’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 """ html_str_list = [ ('&#39;', '\''), ('&quot;', '"'), ('&amp;', '&'), ('&yen;', '¥'), ('amp;', ''), ('&lt;', '<'), ('&gt;', '>'), ...
从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 'headimage': '', # 头像 ...
def get_gzh_by_search(text): """从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 ...
从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # ...
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introduction': '', # 描述 'authentica...
def get_gzh_info_by_history(text): """从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introd...
根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool 删除文章中的语音内容 Returns ------- dict ...
def get_article_detail(text, del_qqmusic=True, del_voice=True): """根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool ...
从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 'wechat_name': str, # 公众号名称 ...
def get_gzh_article_by_hot(text): """从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 ...
Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB) - GIF (1-frame RGB) Since TFDS assumes tha...
def _decode_image(fobj, session, filename): """Reads and decodes an image from a file object as a Numpy array. The SUN dataset contains images in several formats (despite the fact that all of them have .jpg extension). Some of them are: - BMP (RGB) - PNG (grayscale, RGBA, RGB interlaced) - JPEG (RGB)...
Process image files from the dataset.
def _process_image_file(fobj, session, filename): """Process image files from the dataset.""" # We need to read the image files and convert them to JPEG, since some files # actually contain GIF, PNG or BMP data (despite having a .jpg extension) and # some encoding options that will make TF crash in general. i...
Yields examples.
def _generate_examples(self, archive): """Yields examples.""" prefix_len = len("SUN397") with tf.Graph().as_default(): with utils.nogpu_session() as sess: for filepath, fobj in archive: if (filepath.endswith(".jpg") and filepath not in _SUN397_IGNORE_IMAGES): ...
Returns examples from parallel SGML or text files, which may be gzipped.
def _parse_parallel_sentences(f1, f2): """Returns examples from parallel SGML or text files, which may be gzipped.""" def _parse_text(path): """Returns the sentences from a single text file, which may be gzipped.""" split_path = path.split(".") if split_path[-1] == "gz": lang = split_path[-2] ...
Generates examples from TMX file.
def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "In...
Generates examples from TSV file.
def _parse_tsv(path, language_pair=None): """Generates examples from TSV file.""" if language_pair is None: lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])\.tsv", path) assert lang_match is not None, "Invalid TSV filename: %s" % path l1, l2 = lang_match.groups() else: l1, l2 = language_pair ...
Generates examples from Wikiheadlines dataset file.
def _parse_wikiheadlines(path): """Generates examples from Wikiheadlines dataset file.""" lang_match = re.match(r".*\.([a-z][a-z])-([a-z][a-z])$", path) assert lang_match is not None, "Invalid Wikiheadlines filename: %s" % path l1, l2 = lang_match.groups() with tf.io.gfile.GFile(path) as f: for line in f:...
Generates examples from CzEng v1.6, with optional filtering for v1.7.
def _parse_czeng(*paths, **kwargs): """Generates examples from CzEng v1.6, with optional filtering for v1.7.""" filter_path = kwargs.get("filter_path", None) if filter_path: re_block = re.compile(r"^[^-]+-b(\d+)-\d\d[tde]") with tf.io.gfile.GFile(filter_path) as f: bad_blocks = { blk for b...
Injects languages into (potentially) template strings.
def _inject_language(self, src, strings): """Injects languages into (potentially) template strings.""" if src not in self.sources: raise ValueError("Invalid source for '{0}': {1}".format(self.name, src)) def _format_string(s): if "{0}" in s and "{1}" and "{src}" in s: return s.format(*so...
Subsets that make up each split of the dataset for the language pair.
def subsets(self): """Subsets that make up each split of the dataset for the language pair.""" source, target = self.builder_config.language_pair filtered_subsets = {} for split, ss_names in self._subsets.items(): filtered_subsets[split] = [] for ss_name in ss_names: ds = DATASET_MAP...
Returns the examples in the raw (text) form.
def _generate_examples(self, split_subsets, extraction_map): """Returns the examples in the raw (text) form.""" source, _ = self.builder_config.language_pair def _get_local_paths(ds, extract_dirs): rel_paths = ds.get_path(source) if len(extract_dirs) == 1: extract_dirs = extract_dirs * ...
Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `BuilderConfig`s. As a convenience, this string m...
def builder(name, **builder_init_kwargs): """Fetches a `tfds.core.DatasetBuilder` by string name. Args: name: `str`, the registered name of the `DatasetBuilder` (the snake case version of the class name). This can be either `"dataset_name"` or `"dataset_name/config_name"` for datasets with `Builder...
Loads the named dataset into a `tf.data.Dataset`. If `split=None` (the default), returns all splits for the dataset. Otherwise, returns the specified split. `load` is a convenience method that fetches the `tfds.core.DatasetBuilder` by string name, optionally calls `DatasetBuilder.download_and_prepare` (if `...
def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, try_gcs=False): """Loads the named datas...
Extract kwargs from name str.
def _dataset_name_and_kwargs_from_name_str(name_str): """Extract kwargs from name str.""" res = _NAME_REG.match(name_str) if not res: raise ValueError(_NAME_STR_ERR.format(name_str)) name = res.group("dataset_name") kwargs = _kwargs_str_to_kwargs(res.group("kwargs")) try: for attr in ["config", "ver...
Try cast to int, float, bool, str, in that order.
def _cast_to_pod(val): """Try cast to int, float, bool, str, in that order.""" bools = {"True": True, "False": False} if val in bools: return bools[val] try: return int(val) except ValueError: try: return float(val) except ValueError: return tf.compat.as_text(val)
Try importing a module, with an informative error message on failure.
def _try_import(module_name): """Try importing a module, with an informative error message on failure.""" try: mod = importlib.import_module(module_name) return mod except ImportError: err_msg = ("Tried importing %s but failed. See setup.py extras_require. " "The dataset you are trying ...
Returns list from list, tuple or ndarray.
def np_to_list(elem): """Returns list from list, tuple or ndarray.""" if isinstance(elem, list): return elem elif isinstance(elem, tuple): return list(elem) elif isinstance(elem, np.ndarray): return list(elem) else: raise ValueError( 'Input elements of a sequence should be either a num...
Transpose a nested dict[list] into a list[nested dict].
def _transpose_dict_list(dict_list): """Transpose a nested dict[list] into a list[nested dict].""" # 1. Unstack numpy arrays into list dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True) # 2. Extract the sequence length (and ensure the length is constant for all # elements) length = {'value...
See base class for details.
def get_tensor_info(self): """See base class for details.""" # Add the additional length dimension to every shape def add_length_dim(tensor_info): return feature_lib.TensorInfo( shape=(self._length,) + tensor_info.shape, dtype=tensor_info.dtype, ) tensor_info = super(Se...
See base class for details.
def get_serialized_info(self): """See base class for details.""" # Add the additional length dimension to every serialized features def add_length_dim(serialized_info): """Add the length dimension to the serialized_info. Args: serialized_info: One of tf.io.FixedLenFeature, tf.io.VarLen...
Returns SplitGenerators.
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download the full MNIST Database filenames = { "train_data": _MNIST_TRAIN_DATA_FILENAME, "train_labels": _MNIST_TRAIN_LABELS_FILENAME, "test_data": _MNIST_TEST_DATA_FILENAME, "test_labels": _MNIST_TEST_...
Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_path (str): Path to the data files label_path (str): Path to the labels Yields: Generator yielding the next examples
def _generate_examples(self, num_examples, data_path, label_path): """Generate MNIST examples as dicts. Args: num_examples (int): The number of example. data_path (str): Path to the data files label_path (str): Path to the labels Yields: Generator yielding the next examples """...
Returns SplitGenerators.
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # Download images and annotations that come in separate archives. # Note, that the extension of archives is .tar.gz even though the actual # archives format is uncompressed tar. dl_paths = dl_manager.download_and_extract({ ...
Yields examples.
def _generate_examples(self, images_dir_path, labels_path, setid_path, split_name): """Yields examples.""" with tf.io.gfile.GFile(labels_path, "rb") as f: labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0] with tf.io.gfile.GFile(setid_path, "rb") as f: exam...
Calculate statistics for the specified split.
def get_dataset_feature_statistics(builder, split): """Calculate statistics for the specified split.""" statistics = statistics_pb2.DatasetFeatureStatistics() # Make this to the best of our abilities. schema = schema_pb2.Schema() dataset = builder.as_dataset(split=split) # Just computing the number of ex...
Read JSON-formatted proto into DatasetInfo proto.
def read_from_json(json_filename): """Read JSON-formatted proto into DatasetInfo proto.""" with tf.io.gfile.GFile(json_filename) as f: dataset_info_json_str = f.read() # Parse it back into a proto. parsed_proto = json_format.Parse(dataset_info_json_str, dataset_info_pb2.Da...
Full canonical name: (<dataset_name>/<config_name>/<version>).
def full_name(self): """Full canonical name: (<dataset_name>/<config_name>/<version>).""" names = [self._builder.name] if self._builder.builder_config: names.append(self._builder.builder_config.name) names.append(str(self.version)) return posixpath.join(*names)
Overwrite the splits if they are different from the current ones. * If splits aren't already defined or different (ex: different number of shards), then the new split dict is used. This will trigger stats computation during download_and_prepare. * If splits are already defined in DatasetInfo and si...
def update_splits_if_different(self, split_dict): """Overwrite the splits if they are different from the current ones. * If splits aren't already defined or different (ex: different number of shards), then the new split dict is used. This will trigger stats computation during download_and_prepare. ...
Split setter (private method).
def _set_splits(self, split_dict): """Split setter (private method).""" # Update the dictionary representation. # Use from/to proto for a clean copy self._splits = split_dict.copy() # Update the proto del self.as_proto.splits[:] # Clear previous for split_info in split_dict.to_proto(): ...
Update from the DatasetBuilder.
def _compute_dynamic_properties(self, builder): """Update from the DatasetBuilder.""" # Fill other things by going over the dataset. splits = self.splits for split_info in utils.tqdm( splits.values(), desc="Computing statistics...", unit=" split"): try: split_name = split_info.name...
Write `DatasetInfo` as JSON to `dataset_info_dir`.
def write_to_directory(self, dataset_info_dir): """Write `DatasetInfo` as JSON to `dataset_info_dir`.""" # Save the metadata from the features (vocabulary, labels,...) if self.features: self.features.save_metadata(dataset_info_dir) if self.redistribution_info.license: with tf.io.gfile.GFile...
Update DatasetInfo from the JSON file in `dataset_info_dir`. This function updates all the dynamically generated fields (num_examples, hash, time of creation,...) of the DatasetInfo. This will overwrite all previous metadata. Args: dataset_info_dir: `str` The directory containing the metadata f...
def read_from_directory(self, dataset_info_dir): """Update DatasetInfo from the JSON file in `dataset_info_dir`. This function updates all the dynamically generated fields (num_examples, hash, time of creation,...) of the DatasetInfo. This will overwrite all previous metadata. Args: dataset...
Initialize DatasetInfo from GCS bucket info files.
def initialize_from_bucket(self): """Initialize DatasetInfo from GCS bucket info files.""" # In order to support Colab, we use the HTTP GCS API to access the metadata # files. They are copied locally and then loaded. tmp_dir = tempfile.mkdtemp("tfds") data_files = gcs_utils.gcs_dataset_info_files(se...
Returns SplitGenerators.
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" url = _DL_URLS[self.builder_config.name] data_dirs = dl_manager.download_and_extract(url) path_to_dataset = os.path.join(data_dirs, tf.io.gfile.listdir(data_dirs)[0]) train_a_path = os.path.join(path_to_dataset, "trainA") ...
Map the function into each element and resolve the promise.
def _map_promise(map_fn, all_inputs): """Map the function into each element and resolve the promise.""" all_promises = utils.map_nested(map_fn, all_inputs) # Apply the function res = utils.map_nested(_wait_on_promise, all_promises) return res
Store dled file to definitive place, write INFO file, return path.
def _handle_download_result(self, resource, tmp_dir_path, sha256, dl_size): """Store dled file to definitive place, write INFO file, return path.""" fnames = tf.io.gfile.listdir(tmp_dir_path) if len(fnames) > 1: raise AssertionError('More than one file in %s.' % tmp_dir_path) original_fname = fnam...
Download resource, returns Promise->path to downloaded file.
def _download(self, resource): """Download resource, returns Promise->path to downloaded file.""" if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) url = resource.url if url in self._sizes_checksums: expected_sha256 = self._sizes_checksums[url][1] ...
Extract a single archive, returns Promise->path to extraction result.
def _extract(self, resource): """Extract a single archive, returns Promise->path to extraction result.""" if isinstance(resource, six.string_types): resource = resource_lib.Resource(path=resource) path = resource.path extract_method = resource.extract_method if extract_method == resource_lib.E...
Download-extract `Resource` or url, returns Promise->path.
def _download_extract(self, resource): """Download-extract `Resource` or url, returns Promise->path.""" if isinstance(resource, six.string_types): resource = resource_lib.Resource(url=resource) def callback(path): resource.path = path return self._extract(resource) return self._downloa...
Download data for a given Kaggle competition.
def download_kaggle_data(self, competition_name): """Download data for a given Kaggle competition.""" with self._downloader.tqdm(): kaggle_downloader = self._downloader.kaggle_downloader(competition_name) urls = kaggle_downloader.competition_urls files = kaggle_downloader.competition_files ...
Download given url(s). Args: url_or_urls: url or `list`/`dict` of urls to download and extract. Each url can be a `str` or `tfds.download.Resource`. Returns: downloaded_path(s): `str`, The downloaded paths matching the given input url_or_urls.
def download(self, url_or_urls): """Download given url(s). Args: url_or_urls: url or `list`/`dict` of urls to download and extract. Each url can be a `str` or `tfds.download.Resource`. Returns: downloaded_path(s): `str`, The downloaded paths matching the given input url_or_urls...
Returns iterator over files within archive. **Important Note**: caller should read files as they are yielded. Reading out of order is slow. Args: resource: path to archive or `tfds.download.Resource`. Returns: Generator yielding tuple (path_within_archive, file_obj).
def iter_archive(self, resource): """Returns iterator over files within archive. **Important Note**: caller should read files as they are yielded. Reading out of order is slow. Args: resource: path to archive or `tfds.download.Resource`. Returns: Generator yielding tuple (path_within_...
Extract given path(s). Args: path_or_paths: path or `list`/`dict` of path of file to extract. Each path can be a `str` or `tfds.download.Resource`. If not explicitly specified in `Resource`, the extraction method is deduced from downloaded file name. Returns: extracted_path(s): `s...
def extract(self, path_or_paths): """Extract given path(s). Args: path_or_paths: path or `list`/`dict` of path of file to extract. Each path can be a `str` or `tfds.download.Resource`. If not explicitly specified in `Resource`, the extraction method is deduced from downloaded file name. ...
Download and extract given url_or_urls. Is roughly equivalent to: ``` extracted_paths = dl_manager.extract(dl_manager.download(url_or_urls)) ``` Args: url_or_urls: url or `list`/`dict` of urls to download and extract. Each url can be a `str` or `tfds.download.Resource`. If not ...
def download_and_extract(self, url_or_urls): """Download and extract given url_or_urls. Is roughly equivalent to: ``` extracted_paths = dl_manager.extract(dl_manager.download(url_or_urls)) ``` Args: url_or_urls: url or `list`/`dict` of urls to download and extract. Each url can ...
Returns the directory containing the manually extracted data.
def manual_dir(self): """Returns the directory containing the manually extracted data.""" if not tf.io.gfile.exists(self._manual_dir): raise AssertionError( 'Manual directory {} does not exist. Create it and download/extract ' 'dataset artifacts in there.'.format(self._manual_dir)) ...
Construct a list of BuilderConfigs. Construct a list of 75 Cifar10CorruptedConfig objects, corresponding to the 15 corruption types and 5 severities. Returns: A list of 75 Cifar10CorruptedConfig objects.
def _make_builder_configs(): """Construct a list of BuilderConfigs. Construct a list of 75 Cifar10CorruptedConfig objects, corresponding to the 15 corruption types and 5 severities. Returns: A list of 75 Cifar10CorruptedConfig objects. """ config_list = [] for corruption in _CORRUPTIONS: for sev...
Return the test split of Cifar10. Args: dl_manager: download manager object. Returns: test split.
def _split_generators(self, dl_manager): """Return the test split of Cifar10. Args: dl_manager: download manager object. Returns: test split. """ path = dl_manager.download_and_extract(_DOWNLOAD_URL) return [ tfds.core.SplitGenerator( name=tfds.Split.TEST, ...
Generate corrupted Cifar10 test data. Apply corruptions to the raw images according to self.corruption_type. Args: data_dir: root directory of downloaded dataset Yields: dictionary with image file and label.
def _generate_examples(self, data_dir): """Generate corrupted Cifar10 test data. Apply corruptions to the raw images according to self.corruption_type. Args: data_dir: root directory of downloaded dataset Yields: dictionary with image file and label. """ corruption = self.builder_...
Doc string for a single builder, with or without configs.
def document_single_builder(builder): """Doc string for a single builder, with or without configs.""" mod_name = builder.__class__.__module__ cls_name = builder.__class__.__name__ mod_file = sys.modules[mod_name].__file__ if mod_file.endswith("pyc"): mod_file = mod_file[:-1] description_prefix = "" ...
Get all builders organized by module in nested dicts.
def make_module_to_builder_dict(datasets=None): """Get all builders organized by module in nested dicts.""" # pylint: disable=g-long-lambda # dict to hold tfds->image->mnist->[builders] module_to_builder = collections.defaultdict( lambda: collections.defaultdict( lambda: collections.defaultdict(...
Pretty-print tfds.features.FeaturesDict.
def _pprint_features_dict(features_dict, indent=0, add_prefix=True): """Pretty-print tfds.features.FeaturesDict.""" first_last_indent_str = " " * indent indent_str = " " * (indent + 4) first_line = "%s%s({" % ( first_last_indent_str if add_prefix else "", type(features_dict).__name__, ) lines = ...
Make statistics information table.
def make_statistics_information(info): """Make statistics information table.""" if not info.splits.total_num_examples: # That means that we have yet to calculate the statistics for this. return "None computed" stats = [(info.splits.total_num_examples, "ALL")] for split_name, split_info in info.splits.i...
Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format).
def dataset_docs_str(datasets=None): """Create dataset documentation string for given datasets. Args: datasets: list of datasets for which to create documentation. If None, then all available datasets will be used. Returns: string describing the datasets (in the MarkDown format). """ m...
Builds schema.org microdata for DatasetSearch from DatasetBuilder. Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset Testing tool: https://search.google.com/structured-data/testing-tool For Google Dataset Search: https://toolbox.google.com/datasetsearch Microdata format was cho...
def schema_org(builder): # pylint: disable=line-too-long """Builds schema.org microdata for DatasetSearch from DatasetBuilder. Markup spec: https://developers.google.com/search/docs/data-types/dataset#dataset Testing tool: https://search.google.com/structured-data/testing-tool For Google Dataset Search: http...
Generating a Gaussian blurring kernel with disk shape. Generating a Gaussian blurring kernel with disk shape using cv2 API. Args: radius: integer, radius of blurring kernel. alias_blur: float, standard deviation of Gaussian blurring. dtype: data type of kernel Returns: cv2 object of the Gaussia...
def disk(radius, alias_blur=0.1, dtype=np.float32): """Generating a Gaussian blurring kernel with disk shape. Generating a Gaussian blurring kernel with disk shape using cv2 API. Args: radius: integer, radius of blurring kernel. alias_blur: float, standard deviation of Gaussian blurring. dtype: data...
Zoom image with clipping. Zoom the central part of the image and clip extra pixels. Args: img: numpy array, uncorrupted image. zoom_factor: numpy array, a sequence of float numbers for zoom factor. Returns: numpy array, zoomed image after clipping.
def clipped_zoom(img, zoom_factor): """Zoom image with clipping. Zoom the central part of the image and clip extra pixels. Args: img: numpy array, uncorrupted image. zoom_factor: numpy array, a sequence of float numbers for zoom factor. Returns: numpy array, zoomed image after clipping. """ h...
Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py Args: mapsize: side length of the heightmap, must be a power of two. wibbledecay: integer, decay factor. Returns: numpy 2d array, side length 'mapsi...
def plasma_fractal(mapsize=512, wibbledecay=3): """Generate a heightmap using diamond-square algorithm. Modification of the algorithm in https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py Args: mapsize: side length of the heightmap, must be a power of two. wibbledecay: integer, decay facto...
Gaussian noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise.
def gaussian_noise(x, severity=1): """Gaussian noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added Gaussian noise. """ c = [.08, .12...
Shot noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added shot noise.
def shot_noise(x, severity=1): """Shot noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added shot noise. """ c = [60, 25, 12, 5, 3][se...
Impulse noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added impulse noise.
def impulse_noise(x, severity=1): """Impulse noise corruption to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added impulse noise. """ c = [.03, .06, ....
Defocus blurring to images. Apply defocus blurring to images using Gaussian kernel. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied defocus blur.
def defocus_blur(x, severity=1): """Defocus blurring to images. Apply defocus blurring to images using Gaussian kernel. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,2...
Frosted glass blurring to images. Apply frosted glass blurring to images by shuffling pixels locally. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied frosted...
def frosted_glass_blur(x, severity=1): """Frosted glass blurring to images. Apply frosted glass blurring to images by shuffling pixels locally. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image w...
Zoom blurring to images. Applying zoom blurring to images by zooming the central part of the images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied zoom blu...
def zoom_blur(x, severity=1): """Zoom blurring to images. Applying zoom blurring to images by zooming the central part of the images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 ...
Fog corruption to images. Adding fog to images. Fog is generated by diamond-square algorithm. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Added fog.
def fog(x, severity=1): """Fog corruption to images. Adding fog to images. Fog is generated by diamond-square algorithm. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,...
Change brightness of images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Changed brightness.
def brightness(x, severity=1): """Change brightness of images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Changed brightness. """ c = [.1, .2, .3, .4, .5][se...
Change contrast of images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Changed contrast.
def contrast(x, severity=1): """Change contrast of images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Changed contrast. """ c = [0.4, .3, .2, .1, .05][severi...
Conduct elastic transform to images. Elastic transform is performed on small patches of the images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied elastic t...
def elastic(x, severity=1): """Conduct elastic transform to images. Elastic transform is performed on small patches of the images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pix...
Pixelate images. Conduct pixelating corruptions to images by first shrinking the images and then resizing to original size. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in ...
def pixelate(x, severity=1): """Pixelate images. Conduct pixelating corruptions to images by first shrinking the images and then resizing to original size. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy ...
Conduct jpeg compression to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression.
def jpeg_compression(x, severity=1): """Conduct jpeg compression to images. Args: x: numpy array, uncorrupted image, assumed to have uint8 pixel in [0,255]. severity: integer, severity of corruption. Returns: numpy array, image with uint8 pixels in [0,255]. Applied jpeg compression. """ c = [25,...
Temporarily assign obj.attr to value.
def temporary_assignment(obj, attr, value): """Temporarily assign obj.attr to value.""" original = getattr(obj, attr, None) setattr(obj, attr, value) yield setattr(obj, attr, original)
Iterate over items of dictionaries grouped by their keys.
def zip_dict(*dicts): """Iterate over items of dictionaries grouped by their keys.""" for key in set(itertools.chain(*dicts)): # set merge all keys # Will raise KeyError if the dict don't have the same keys yield key, tuple(d[key] for d in dicts)
Apply a function recursively to each element of a nested data struct.
def map_nested(function, data_struct, dict_only=False, map_tuple=False): """Apply a function recursively to each element of a nested data struct.""" # Could add support for more exotic data_struct, like OrderedDict if isinstance(data_struct, dict): return { k: map_nested(function, v, dict_only, map_t...