diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/INSTALLER b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/METADATA b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..0a1ed97ac3768196cad9932e5f341e57e4b6ef3a
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/METADATA
@@ -0,0 +1,295 @@
+Metadata-Version: 2.1
+Name: LangSegment
+Version: 0.3.3
+Summary: This is a multilingual tokenization tool that currently supports for zh/ja/en/ko, and more languages.
+Home-page: https://github.com/juntaosun/LangSegment
+Author: sunnyboxs
+License: BSD
+Keywords: language detection,language identification,langid,langid.py,nlp,language
+Platform: UNKNOWN
+Classifier: Intended Audience :: Science/Research
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Requires-Python: >=3.6
+Description-Content-Type: text/markdown
+Requires-Dist: numpy >=1.19.5
+Requires-Dist: py3langid >=0.2.2
+
+# LangSegment
+**简介:它是一个强大的多语言(97种语言)的混合文本自动分词工具。[中/日/英/韩:已测试]**
+**主要用途:“一口气” 让你的 TTS 语音合成项目 VITS 说出多国语言,多语种混合文本的分词推理,和预处理训练。**
+**分词支持:中文/英文/日文/韩语/法语/越南语/俄语/泰语/**
+
+
+
+它基于 py3langid 的扩展实现(>=python3.6)。
+``LangSegment`` It is a multi-lingual (97 languages) text content automatic recognition and segmentation tool.
+The main purposes are: front-end for various TTS (Text-to-Speech) synthesis projects, preprocessing of multilingual text mixing for both training and inference.
+
+>Implementation based on py3langid,See LICENSE file for more info.
+https://github.com/adbar/py3langid
+
+
+功能:将文章或句子里的例如(中/英/日/韩),按不同语言自动识别分词,使文本更适合AI处理。
+本代码专为各种 TTS 项目的前端文本多语种混合标注区分,多语言混合训练和推理而编写。
+
+## 最近更新:News
+* 版本:v0.3.3 fix (更新帮助见下文)。
+* 添加支持: "zh"中文(数字拼音pinyin),保留多音字(音素)指定。
+* 添加支持: "ru"俄语Russian / "th"泰语Thai。
+* 添加支持: "fr"法语French / "vi"越南语Vietnamese。
+* 语言优先级,置信度评分和阀值。
+* 优化字符处理。fix: LangSegment.setfilters
+* 更细致的处理,中日英韩,分词更精准!
+* 多语言过滤组功能(默认:中/英/日/韩)!帮您自动清理不需要的语言内容。
+* 添加 WebUI 可视化界面,运行 app.py 即可快捷体验(如图所示)。
+
+* 点击在线体验,感谢 huggingface 提供服务支持:
+
+
+
+```python
+# Gradio demo:To use our gradio demo locally:
+# 运行脚本,打开浏览器 gradio webui 界面,开始快速体验。(gradio==3.50.2)
+python app.py
+```
+
+## 完全可控:支持
+* (1)自动分词:“韩语中的오빠读什么呢?あなたの体育の先生は誰ですか? 此次带来了四款iPhone 15系列机型”
+* (2)手动分词:“你的名字叫\佐々木?\吗?”
+
+## 语言标签:支持
+>分词语言标签:它和html类似,它需要成对出现 \内容\ 或者 \内容\。
+本处理结果主要针对(中文=zh , 日文=ja , 英文=en , 韩语=ko), 实际上可支持多达 97 种不同的语言混合处理。
+
+## 安装方法:Install (推荐使用官方源)
+```bash
+# 首次安装:官方源(推荐)
+pip3 install LangSegment -i https://pypi.org/simple
+# 后续版本升级或更新:
+pip3 install LangSegment -i https://pypi.org/simple --upgrade
+
+# 或者,国内镜像(国内镜像同步慢几天,可能会导致您无法极时获得最新版本!!!):
+# pip3 install LangSegment -i https://pypi.mirrors.ustc.edu.cn/simple
+```
+## 使用示例:Example Input
+>示例中的句子,同时包含中日英韩4种语言,接下来将对它们按不同语种进行分词,以方便各种TTS项目进行语音合成。
+```python
+
+ # pip3 install LangSegment -i https://pypi.org/simple
+ import LangSegment
+
+ # input text example 示例:
+ text = "你的名字叫佐々木?吗?韩语中的오빠读什么呢?あなたの体育の先生は\
+ 誰ですか? 此次发布会带来了四款iPhone 15系列机型\
+ 和三款Apple Watch等一系列新品,这次的iPad Air采用了LCD屏幕"
+
+ # example
+ langlist = LangSegment.getTexts(text)
+
+ # output list : {'lang': 'zh', 'text': '...'}
+ print("=================================")
+ for line in langlist:
+ print(line)
+ print("=================================")
+```
+## 处理结果:Example Output
+```python
+ # output 输出列表行:lang=语言,text=内容
+ # ===========================================================================
+ # {'lang': 'zh', 'text': '你的名字叫'}
+ # {'lang': 'ja', 'text': '佐々木?'}
+ # {'lang': 'zh', 'text': '吗?韩语中的'}
+ # {'lang': 'ko', 'text': '오빠'}
+ # {'lang': 'zh', 'text': '读什么呢?'}
+ # {'lang': 'ja', 'text': 'あなたの体育の先生は誰ですか?'}
+ # {'lang': 'zh', 'text': ' 此次发布会带来了四款'}
+ # {'lang': 'en', 'text': 'i Phone'}
+ # {'lang': 'zh', 'text': ' 15系列机型和三款'}
+ # {'lang': 'en', 'text': 'Apple Watch'}
+ # {'lang': 'zh', 'text': '等一系列新品,这次的'}
+ # {'lang': 'en', 'text': 'i Pad Air'}
+ # {'lang': 'zh', 'text': '采用了'}
+ # {'lang': 'en', 'text': 'L C D'}
+ # {'lang': 'zh', 'text': '屏幕'}
+ # ===========================================================================
+ # 其中英文缩写字母如“LCD”,英文标准发音为“L-C-D”,
+ # 而在语音合成TTS项目中,一般用空格隔开字母来单独发音:“L C D”
+```
+
+## 英文拼读:支持
+```python
+TTS语音合成(英文字母)大小写拼读规则:
+(1)需要单个字母发音就大写,比如:USA,USB,ChatGPT,LCD,GPU,CEO。
+(2)其它情况正常拼读,就按正常拼写。比如:Nvidia , Cuda 或者全小写 (nvidia , cuda )
+```
+
+## 拼音保留:支持(多音字)
+> 版本支持:>= 0.3.2
+> 常见需求:直接修改 TTS 的汉字读音,保留拼音输入。
+```python
+# 开启汉语拼音保留,(TTS标准:数字拼音格式),默认关闭。
+LangSegment.setKeepPinyin(True)
+
+# 汉字拼音指定示例:以下句子,括号中的拼音,均识别为中文。
+text = "这个字的读音是角(jue2)色,而不是角(jiao3)色"
+```
+
+## 分词纠错:很重要!
+>综上所述,“自动分词”已经极大的提高了我们的工作效率,但还是建议您对分词结果进行人工校对。
+特别是中文与日文,存在大量汉字互用,这对自动分词是极具挑战性的,“分词纠错” 解决方案如下:
+
+
+* (1)自动分词纠错:在中文与日文句子之间,打上句号。来辅助分词(自动上下文分词)。
+* (2)手动分词纠错:您可手动添加语言标签\,\,\,\等来辅助进行强制分词。
+
+以下是语言标签分词详细示例:
+```python
+ # 手动分词标签的应用示例,例如针对中日汉字有重叠,而需要在 TTS 中混合发音的情况:
+ # 分词标签内的文本将识别成日文ja内容,也可以写成内容
+ text = "你的名字叫佐々木?"
+ # 或者:
+ text = "你的名字叫佐々木?"
+ # 以上均能正确输出:
+ # 处理成中文-- {'lang': 'zh', 'text': '你的名字叫'}
+ # 处理成日文-- {'lang': 'ja', 'text': '佐々木?'}
+```
+自动分词能力目前主要针对中文(zh)/日文(ja)/英文(en)/韩文(ko),进行了特别优化。
+它特别适合各种 TTS 前端文本多语种内容的混合分词(自动/手动),训练和推理使用。
+
+```python
+ # 手动分词标签规范:<语言标签>文本内容语言标签>
+ # ===========================================================================
+ # 如需手动标注,标签需要成对出现,如:“佐々木” 或者 “佐々木”
+ # 错误示范:“你的名字叫佐々木。” 此句子中出现的单个标签将被忽略,不会处理。
+ # ===========================================================================
+```
+
+## 语言过滤:支持
+> 版本支持:>=0.2.0
+语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
+```python
+# Set language filters
+# 设置语言过滤功能,未指定的语言将被清除,使它完全适配您的TTS项目。
+LangSegment.setfilters(["zh", "en", "ja", "ko"]) # 标准写法
+# 或者写成:
+# LangSegment.setfilters(["zh_en_ja_ko"]) # 写法1,过滤效果相同
+# LangSegment.setfilters(["zh-en-ja-ko"]) # 写法2,过滤效果相同
+# 获取过滤器:
+# LangSegment.getfilters()
+
+# 参数组合说明,以下是部份场景示例:
+# ["zh"] # 按中文识别
+# ["en"] # 按英文识别
+# ["ja"] # 按日文识别
+# ["ko"] # 按韩文识别
+# ["zh_ja"] # 中日混合识别
+# ["zh_en"] # 中英混合识别
+# ["zh_ko"] # 中韩混合识别
+# ["ja_en"] # 日英混合识别
+# ["zh_ko_en"] # 中韩英混合识别
+# 以上是示例,您可根据自己的TTS项目进行自由组合。
+```
+## 语言优先级:支持(纯数字输入示例)
+> 版本支持:>=0.2.1
+当我们在鉴别纯数字时,比如“123456”,全球通用。如果没有提供上下文,将无法区分归属(默认en)。
+这时候,您只需调整语言优先级。就能准确识别。相关示例如下:
+
+```python
+# 仅输入独立纯数字:所有国家通用,因为没有提供上下文,所以无法区分语言归属
+print(LangSegment.getTexts("123456789")) # 国际纯数字,默认输出:英文=en
+
+# 调整过滤语言优先级,中文优先,数字按中文优先识别
+LangSegment.setfilters(["zh","ja"])
+print(LangSegment.getTexts("123456789")) # 识别输出:中文=zh
+
+# 调整过滤语言优先级,日语优先,数字按日语优先识别
+LangSegment.setfilters(["ja","zh"])
+print(LangSegment.getTexts("123456789")) # 识别输出:日文=ja
+
+# 调整过滤语言优先级,韩语优先,数字按韩语优先识别
+LangSegment.setfilters(["ko","zh"])
+print(LangSegment.getTexts("123456789")) # 识别输出:韩文=ko
+
+# 识别输出:中文,(因为提供了上下文,汉字“编号:”)
+LangSegment.setfilters(["ko","zh","en","ja"])
+print(LangSegment.getTexts("编号:123456789")) # 提供上下文,识别输出:中文=zh
+print(LangSegment.getTexts("Number:123456789")) # 提供上下文,识别输出:英文=en
+print(LangSegment.getTexts("번호:123456789")) # 提供上下文,识别输出:韩文=ko
+```
+## 优先级与置信度:特殊示例
+> 版本支持:>=0.2.1
+语言优先级除了对输入的纯数字外,它对中文与日文也特别有用,以下是使用示例:
+
+* 示例汉字词:“番号”,由于在中文和日语,两者使用几乎完全一样,在中日混合模式下。
+```python
+# 在中日混合下,默认情况为中文优先。
+LangSegment.setfilters(["zh","ja","en","ko"])
+# 默认处理:
+print(LangSegment.getTexts("番号: 123456789"))
+# [{'lang': 'zh', 'text': '番号: 123456789 ', 'score': 0.87188566}]
+# 默认识别:中文=zh ,识别的参考置信度是:0.87
+```
+* 而此时,在中日混合模式下,我们希望它识别成:日语=ja。
+```python
+# 只需按如下调整过滤器的语言优先级。让 ja 优先于 zh 之前。
+LangSegment.setfilters(["ja","zh","en","ko"])
+# 再次处理:
+print(LangSegment.getTexts("番号: 123456789"))
+# [{'lang': 'ja', 'text': '番号: 123456789 ', 'score': 0.87188566}]
+# 阀值的精准控制下,它被优先识别为我们希望的结果:日文=ja
+
+# 您还可以添加语言标签:精准控制
+print(LangSegment.getTexts("番号: 123456789"))
+# 添加语言标签,正确输出:日文=ja
+```
+
+## 预览新增:法语(French)/越南语(Vietnamese)/俄语(Russian)/泰语(Thai)
+> 版本支持:>=0.2.2 (法语(French)/越南语(Vietnamese))
+> 版本支持:>=0.2.3 (俄语(Russian)/泰语(Thai))
+> 法语和越南语,您只需在语言过滤器中添加,即可配合分词标签使用。
+
+```python
+# 自动分词启用设置:法语="fr" , 越南语="vi", "ru"俄语=Russian, "th"泰语=Thai
+LangSegment.setfilters(["fr", "vi" , "zh", "ja", "ko", "en"])
+
+# 可以随意搭配,比如您的TTS只需(越南语/中文),则仅需保留两个语言。
+# LangSegment.setfilters(["vi" , "zh"])
+
+# 对应的(法语fr和越南语vi)手动分词语言标签:
+# Français、Tiếng Việt
+```
+>每个语种它们对应的语言分词标签: (ISO 639-1 codes given):
+>* \:中文 = Chinese
+>* \:英语 = English
+>* \:日语 = Japanese
+>* \:韩语 = Korean
+>* \:法语 = French
+>* \:越南语 = Vietnamese
+>* \:俄语 = Russian
+>* \:泰语 = Thai
+>* 更多其它97个语种标签,在下方完整列表已经列出。
+
+
+## 总结说明:
+它经过了高达 97 种语言的预训练,相信它绝对能满足您的 TTS 语音合成项目所需。
+comes pre-trained on 97 languages (ISO 639-1 codes given):
+>af, am, an, ar, as, az, be, bg, bn, br, bs, ca, cs, cy, da, de, dz, el, en, eo, es, et, eu, fa, fi, fo, fr, ga, gl, gu, he, hi, hr, ht, hu, hy, id, is, it, ja, jv, ka, kk, km, kn, ko, ku, ky, la, lb, lo, lt, lv, mg, mk, ml, mn, mr, ms, mt, nb, ne, nl, nn, no, oc, or, pa, pl, ps, pt, qu, ro, ru, rw, se, si, sk, sl, sq, sr, sv, sw, ta, te, th, tl, tr, ug, uk, ur, vi, vo, wa, xh, zh, zu
+
+
+---
+---
+> 备注:多语种混合文本转语音合成(TTS),中/日/英/韩/已完成测试。
+其它语种未作具体测试,如有Bug和优化建议,欢迎提出或指正,感谢~。
+Note: The speech synthesis test content is currently mainly for four categories: Chinese, Japanese, English and Korean.
+Other languages have not been specifically tested. If there are any bugs or optimization suggestions, please feel free to raise them or correct them. Thank you~
+Special thanks to the following projects: [py3langid](https://github.com/adbar/py3langid)
+---
+---
+
diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/RECORD b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..86ed3ddc270a25e062be88b2146a1933e30e28fd
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/RECORD
@@ -0,0 +1,10 @@
+LangSegment-0.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+LangSegment-0.3.3.dist-info/METADATA,sha256=-TyEKCRRg1NTF6tk9LlV88cL1aojbmKF24Cx-CJ8fTc,15251
+LangSegment-0.3.3.dist-info/RECORD,,
+LangSegment-0.3.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+LangSegment-0.3.3.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
+LangSegment-0.3.3.dist-info/top_level.txt,sha256=Vg8k4ac6vg9w9gy7bI5JReoo-pLVXtmsmcfQCN4IaJw,12
+LangSegment/LangSegment.py,sha256=QdBWPscz-4U9EWfKOlcgcs9733rMEajJmwVXRqSS_DU,44726
+LangSegment/__init__.py,sha256=qgAenFaQR4zrmTgj4mhgBF4ccPvKF4M78phDZQzS0G4,278
+LangSegment/__pycache__/LangSegment.cpython-39.pyc,,
+LangSegment/__pycache__/__init__.cpython-39.pyc,,
diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/REQUESTED b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/WHEEL b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.41.2)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/top_level.txt b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f5250b178c188a14640a479272462b220dd84a62
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/top_level.txt
@@ -0,0 +1 @@
+LangSegment
diff --git a/runtime/Lib/site-packages/LangSegment/LangSegment.py b/runtime/Lib/site-packages/LangSegment/LangSegment.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0a810f2304c597261063ac091d1030a11133288
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment/LangSegment.py
@@ -0,0 +1,837 @@
+"""
+This file bundles language identification functions.
+
+Modifications (fork): Copyright (c) 2021, Adrien Barbaresi.
+
+Original code: Copyright (c) 2011 Marco Lui .
+Based on research by Marco Lui and Tim Baldwin.
+
+See LICENSE file for more info.
+https://github.com/adbar/py3langid
+
+Projects:
+https://github.com/juntaosun/LangSegment
+"""
+
+import re
+from collections import defaultdict
+
+# import langid
+# import py3langid as langid
+# pip install py3langid==0.2.2
+
+# 启用语言预测概率归一化,概率预测的分数。因此,实现重新规范化 产生 0-1 范围内的输出。
+# langid disables probability normalization by default. For command-line usages of , it can be enabled by passing the flag.
+# For probability normalization in library use, the user must instantiate their own . An example of such usage is as follows:
+from py3langid.langid import LanguageIdentifier, MODEL_FILE
+langid = LanguageIdentifier.from_pickled_model(MODEL_FILE, norm_probs=True)
+
+
+# -----------------------------------
+# 更新日志:新版本分词更加精准。
+# Changelog: The new version of the word segmentation is more accurate.
+# チェンジログ:新しいバージョンの単語セグメンテーションはより正確です。
+# Changelog: 분할이라는 단어의 새로운 버전이 더 정확합니다.
+# -----------------------------------
+
+
+# Word segmentation function:
+# automatically identify and split the words (Chinese/English/Japanese/Korean) in the article or sentence according to different languages,
+# making it more suitable for TTS processing.
+# This code is designed for front-end text multi-lingual mixed annotation distinction, multi-language mixed training and inference of various TTS projects.
+# This processing result is mainly for (Chinese = zh, Japanese = ja, English = en, Korean = ko), and can actually support up to 97 different language mixing processing.
+
+#===========================================================================================================
+#分かち書き機能:文章や文章の中の例えば(中国語/英語/日本語/韓国語)を、異なる言語で自動的に認識して分割し、TTS処理により適したものにします。
+#このコードは、さまざまなTTSプロジェクトのフロントエンドテキストの多言語混合注釈区別、多言語混合トレーニング、および推論のために特別に作成されています。
+#===========================================================================================================
+#(1)自動分詞:「韓国語では何を読むのですかあなたの体育の先生は誰ですか?今回の発表会では、iPhone 15シリーズの4機種が登場しました」
+#(2)手动分词:“あなたの名前は佐々木ですか?ですか?”
+#この処理結果は主に(中国語=ja、日本語=ja、英語=en、韓国語=ko)を対象としており、実際には最大97の異なる言語の混合処理をサポートできます。
+#===========================================================================================================
+
+#===========================================================================================================
+# 단어 분할 기능: 기사 또는 문장에서 단어(중국어/영어/일본어/한국어)를 다른 언어에 따라 자동으로 식별하고 분할하여 TTS 처리에 더 적합합니다.
+# 이 코드는 프런트 엔드 텍스트 다국어 혼합 주석 분화, 다국어 혼합 교육 및 다양한 TTS 프로젝트의 추론을 위해 설계되었습니다.
+#===========================================================================================================
+# (1) 자동 단어 분할: "한국어로 무엇을 읽습니까? 스포츠 씨? 이 컨퍼런스는 4개의 iPhone 15 시리즈 모델을 제공합니다."
+# (2) 수동 참여: "이름이 Saki입니까? ?"
+# 이 처리 결과는 주로 (중국어 = zh, 일본어 = ja, 영어 = en, 한국어 = ko)를 위한 것이며 실제로 혼합 처리를 위해 최대 97개의 언어를 지원합니다.
+#===========================================================================================================
+
+# ===========================================================================================================
+# 分词功能:将文章或句子里的例如(中/英/日/韩),按不同语言自动识别并拆分,让它更适合TTS处理。
+# 本代码专为各种 TTS 项目的前端文本多语种混合标注区分,多语言混合训练和推理而编写。
+# ===========================================================================================================
+# (1)自动分词:“韩语中的오빠读什么呢?あなたの体育の先生は誰ですか? 此次发布会带来了四款iPhone 15系列机型”
+# (2)手动分词:“你的名字叫佐々木?吗?”
+# 本处理结果主要针对(中文=zh , 日文=ja , 英文=en , 韩语=ko), 实际上可支持多达 97 种不同的语言混合处理。
+# ===========================================================================================================
+
+
+# 手动分词标签规范:<语言标签>文本内容语言标签>
+# 수동 단어 분할 태그 사양: <언어 태그> 텍스트 내용언어 태그>
+# Manual word segmentation tag specification: text content
+# 手動分詞タグ仕様:<言語タグ>テキスト内容言語タグ>
+# ===========================================================================================================
+# For manual word segmentation, labels need to appear in pairs, such as:
+# 如需手动分词,标签需要成对出现,例如:“佐々木” 或者 “佐々木”
+# 错误示范:“你的名字叫佐々木。” 此句子中出现的单个标签将被忽略,不会处理。
+# Error demonstration: "Your name is 佐々木。" Single tags that appear in this sentence will be ignored and will not be processed.
+# ===========================================================================================================
+
+class LangSegment():
+
+ _text_cache = None
+ _text_lasts = None
+ _text_langs = None
+ _lang_count = None
+ _lang_eos = None
+
+ # 可自定义语言匹配标签:カスタマイズ可能な言語対応タグ:사용자 지정 가능한 언어 일치 태그:
+ # Customizable language matching tags: These are supported,이 표현들은 모두 지지합니다
+ # 你好 , 佐々木 , OK , 오빠 这些写法均支持
+ SYMBOLS_PATTERN = r'(<([a-zA-Z|-]*)>(.*?)<\/*[a-zA-Z|-]*>)'
+
+ # 语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
+ # 언어 필터 그룹 기능을 사용하면 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
+ # 言語フィルターグループ機能では、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
+ # The language filter group function allows you to specify reserved languages.
+ # Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.
+ # 排名越前,优先级越高,The higher the ranking, the higher the priority,ランキングが上位になるほど、優先度が高くなります。
+
+ # 系统默认过滤器。System default filter。(ISO 639-1 codes given)
+ # ----------------------------------------------------------------------------------------------------------------------------------
+ # "zh"中文=Chinese ,"en"英语=English ,"ja"日语=Japanese ,"ko"韩语=Korean ,"fr"法语=French ,"vi"越南语=Vietnamese , "ru"俄语=Russian
+ # "th"泰语=Thai
+ # ----------------------------------------------------------------------------------------------------------------------------------
+ DEFAULT_FILTERS = ["zh", "ja", "ko", "en"]
+
+ # 用户可自定义过滤器。User-defined filters
+ Langfilters = DEFAULT_FILTERS[:] # 创建副本
+
+ # 试验性支持:您可自定义添加:"fr"法语 , "vi"越南语。Experimental: You can customize to add: "fr" French, "vi" Vietnamese.
+ # 请使用API启用:LangSegment.setfilters(["zh", "en", "ja", "ko", "fr", "vi" , "ru" , "th"]) # 您可自定义添加,如:"fr"法语 , "vi"越南语。
+
+ # 预览版功能,自动启用或禁用,无需设置
+ # Preview feature, automatically enabled or disabled, no settings required
+ EnablePreview = False
+
+ # 除此以外,它支持简写过滤器,只需按不同语种任意组合即可。
+ # In addition to that, it supports abbreviation filters, allowing for any combination of different languages.
+ # 示例:您可以任意指定多种组合,进行过滤
+ # Example: You can specify any combination to filter
+
+ # 中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
+ # 중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
+ # 中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
+ # Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
+ # Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
+ LangPriorityThreshold = 0.89
+
+ # Langfilters = ["zh"] # 按中文识别
+ # Langfilters = ["en"] # 按英文识别
+ # Langfilters = ["ja"] # 按日文识别
+ # Langfilters = ["ko"] # 按韩文识别
+ # Langfilters = ["zh_ja"] # 中日混合识别
+ # Langfilters = ["zh_en"] # 中英混合识别
+ # Langfilters = ["ja_en"] # 日英混合识别
+ # Langfilters = ["zh_ko"] # 中韩混合识别
+ # Langfilters = ["ja_ko"] # 日韩混合识别
+ # Langfilters = ["en_ko"] # 英韩混合识别
+ # Langfilters = ["zh_ja_en"] # 中日英混合识别
+ # Langfilters = ["zh_ja_en_ko"] # 中日英韩混合识别
+
+ # 更多过滤组合,请您随意。。。For more filter combinations, please feel free to......
+ # より多くのフィルターの組み合わせ、お気軽に。。。더 많은 필터 조합을 원하시면 자유롭게 해주세요. .....
+
+ # 可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。
+ # 开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
+ keepPinyin = False
+
+
+ # DEFINITION
+ PARSE_TAG = re.compile(r'(⑥\$*\d+[\d]{6,}⑥)')
+
+ @staticmethod
+ def _clears():
+ LangSegment._text_cache = None
+ LangSegment._text_lasts = None
+ LangSegment._text_langs = None
+ LangSegment._text_waits = None
+ LangSegment._lang_count = None
+ LangSegment._lang_eos = None
+ pass
+
+ @staticmethod
+ def _is_english_word(word):
+ return bool(re.match(r'^[a-zA-Z]+$', word))
+
+ @staticmethod
+ def _is_chinese(word):
+ for char in word:
+ if '\u4e00' <= char <= '\u9fff':
+ return True
+ return False
+
+ @staticmethod
+ def _is_japanese_kana(word):
+ pattern = re.compile(r'[\u3040-\u309F\u30A0-\u30FF]+')
+ matches = pattern.findall(word)
+ return len(matches) > 0
+
+ @staticmethod
+ def _insert_english_uppercase(word):
+ modified_text = re.sub(r'(? 0 else None
+ if preData is not None:
+ if len(clear_text) == 0:language = preData["lang"]
+ elif is_number == True:language = preData["lang"]
+ _ , pre_is_number = LangSegment._clear_text_number(preData["text"])
+ if (preData["lang"] == language):
+ LangSegment._statistics(preData["lang"],text)
+ text = preData["text"] + text
+ preData["text"] = text
+ return preData
+ elif pre_is_number == True:
+ text = f'{preData["text"]}{text}'
+ words.pop()
+ elif is_number == True:
+ priority_language = LangSegment._get_filters_string()[:2]
+ if priority_language in "ja-zh-en-ko-fr-vi":language = priority_language
+ data = {"lang":language,"text": text,"score":score}
+ filters = LangSegment.Langfilters
+ if filters is None or len(filters) == 0 or "?" in language or \
+ language in filters or language in filters[0] or \
+ filters[0] == "*" or filters[0] in "alls-mixs-autos":
+ words.append(data)
+ LangSegment._statistics(data["lang"],data["text"])
+ return data
+
+ @staticmethod
+ def _addwords(words,language,text,score):
+ if text is None or len(text.strip()) == 0:return True
+ if language is None:language = ""
+ language = language.lower()
+ if language == 'en':text = LangSegment._insert_english_uppercase(text)
+ # text = re.sub(r'[(())]', ',' , text) # Keep it.
+ text_waits = LangSegment._text_waits
+ ispre_waits = len(text_waits)>0
+ preResult = text_waits.pop() if ispre_waits else None
+ if preResult is None:preResult = words[-1] if len(words) > 0 else None
+ if preResult and ("|" in preResult["lang"]):
+ pre_lang = preResult["lang"]
+ if language in pre_lang:preResult["lang"] = language = language.split("|")[0]
+ else:preResult["lang"]=pre_lang.split("|")[0]
+ if ispre_waits:preResult = LangSegment._saveData(words,preResult["lang"],preResult["text"],preResult["score"])
+ pre_lang = preResult["lang"] if preResult else None
+ if ("|" in language) and (pre_lang and not pre_lang in language and not "…" in language):language = language.split("|")[0]
+ if "|" in language:LangSegment._text_waits.append({"lang":language,"text": text,"score":score})
+ else:LangSegment._saveData(words,language,text,score)
+ return False
+
+ @staticmethod
+ def _get_prev_data(words):
+ data = words[-1] if words and len(words) > 0 else None
+ if data:return (data["lang"] , data["text"])
+ return (None,"")
+
+ @staticmethod
+ def _match_ending(input , index):
+ if input is None or len(input) == 0:return False,None
+ input = re.sub(r'\s+', '', input)
+ if len(input) == 0 or abs(index) > len(input):return False,None
+ ending_pattern = re.compile(r'([「」“”‘’"\'::。.!!?.?])')
+ return ending_pattern.match(input[index]),input[index]
+
+ @staticmethod
+ def _cleans_text(cleans_text):
+ cleans_text = re.sub(r'(.*?)([^\w]+)', r'\1 ', cleans_text)
+ cleans_text = re.sub(r'(.)\1+', r'\1', cleans_text)
+ return cleans_text.strip()
+
+ @staticmethod
+ def _lang_classify(cleans_text):
+ language, score = langid.classify(cleans_text)
+ return language, score
+
+ @staticmethod
+ def _get_filters_string():
+ filters = LangSegment.Langfilters
+ return "-".join(filters).lower().strip() if filters is not None else ""
+
+ @staticmethod
+ def _parse_language(words , segment):
+ LANG_JA = "ja"
+ LANG_ZH = "zh"
+ LANG_ZH_JA = f'{LANG_ZH}|{LANG_JA}'
+ LANG_JA_ZH = f'{LANG_JA}|{LANG_ZH}'
+ language = LANG_ZH
+ regex_pattern = re.compile(r'([^\w\s]+)')
+ lines = regex_pattern.split(segment)
+ lines_max = len(lines)
+ LANG_EOS =LangSegment._lang_eos
+ for index, text in enumerate(lines):
+ if len(text) == 0:continue
+ EOS = index >= (lines_max - 1)
+ nextId = index + 1
+ nextText = lines[nextId] if not EOS else ""
+ nextPunc = len(re.sub(regex_pattern,'',re.sub(r'\n+','',nextText)).strip()) == 0
+ textPunc = len(re.sub(regex_pattern,'',re.sub(r'\n+','',text)).strip()) == 0
+ if not EOS and (textPunc == True or ( len(nextText.strip()) >= 0 and nextPunc == True)):
+ lines[nextId] = f'{text}{nextText}'
+ continue
+ number_tags = re.compile(r'(⑥\d{6,}⑥)')
+ cleans_text = re.sub(number_tags, '' ,text)
+ cleans_text = re.sub(r'\d+', '' ,cleans_text)
+ cleans_text = LangSegment._cleans_text(cleans_text)
+ # fix:Langid's recognition of short sentences is inaccurate, and it is spliced longer.
+ if not EOS and len(cleans_text) <= 2:
+ lines[nextId] = f'{text}{nextText}'
+ continue
+ language,score = LangSegment._lang_classify(cleans_text)
+ prev_language , prev_text = LangSegment._get_prev_data(words)
+ if language != LANG_ZH and all('\u4e00' <= c <= '\u9fff' for c in re.sub(r'\s','',cleans_text)):language,score = LANG_ZH,1
+ if len(cleans_text) <= 5 and LangSegment._is_chinese(cleans_text):
+ filters_string = LangSegment._get_filters_string()
+ if score < LangSegment.LangPriorityThreshold and len(filters_string) > 0:
+ index_ja , index_zh = filters_string.find(LANG_JA) , filters_string.find(LANG_ZH)
+ if index_ja != -1 and index_ja < index_zh:language = LANG_JA
+ elif index_zh != -1 and index_zh < index_ja:language = LANG_ZH
+ if LangSegment._is_japanese_kana(cleans_text):language = LANG_JA
+ elif len(cleans_text) > 2 and score > 0.90:pass
+ elif EOS and LANG_EOS:language = LANG_ZH if len(cleans_text) <= 1 else language
+ else:
+ LANG_UNKNOWN = LANG_ZH_JA if language == LANG_ZH or (len(cleans_text) <=2 and prev_language == LANG_ZH) else LANG_JA_ZH
+ match_end,match_char = LangSegment._match_ending(text, -1)
+ referen = prev_language in LANG_UNKNOWN or LANG_UNKNOWN in prev_language if prev_language else False
+ if match_char in "。.": language = prev_language if referen and len(words) > 0 else language
+ else:language = f"{LANG_UNKNOWN}|…"
+ text,*_ = re.subn(number_tags , LangSegment._restore_number , text )
+ LangSegment._addwords(words,language,text,score)
+ pass
+ pass
+
+ @staticmethod
+ def _restore_number(matche):
+ value = matche.group(0)
+ text_cache = LangSegment._text_cache
+ if value in text_cache:
+ process , data = text_cache[value]
+ tag , match = data
+ value = match
+ return value
+
+ @staticmethod
+ def _pattern_symbols(item , text):
+ if text is None:return text
+ tag , pattern , process = item
+ matches = pattern.findall(text)
+ if len(matches) == 1 and "".join(matches[0]) == text:
+ return text
+ for i , match in enumerate(matches):
+ key = f"⑥{tag}{i:06d}⑥"
+ text = re.sub(pattern , key , text , count=1)
+ LangSegment._text_cache[key] = (process , (tag , match))
+ return text
+
+ @staticmethod
+ def _process_symbol(words,data):
+ tag , match = data
+ language = match[1]
+ text = match[2]
+ score = 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_english(words,data):
+ tag , match = data
+ text = match[0]
+ filters = LangSegment._get_filters_string()
+ priority_language = filters[:2]
+ # Preview feature, other language segmentation processing
+ enablePreview = LangSegment.EnablePreview
+ if enablePreview == True:
+ # Experimental: Other language support
+ regex_pattern = re.compile(r'(.*?[。.??!!]+[\n]{,1})')
+ lines = regex_pattern.split(text)
+ for index , text in enumerate(lines):
+ if len(text.strip()) == 0:continue
+ cleans_text = LangSegment._cleans_text(text)
+ language,score = LangSegment._lang_classify(cleans_text)
+ if language in filters:pass
+ elif score >= 0.95:continue # High score, but not in the filter, excluded.
+ elif score <= 0.15 and filters[:2] == "fr":language = priority_language
+ else:language = "en"
+ LangSegment._addwords(words,language,text,score)
+ else:
+ # Default is English
+ language, score = "en", 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_Russian(words,data):
+ tag , match = data
+ text = match[0]
+ language = "ru"
+ score = 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_Thai(words,data):
+ tag , match = data
+ text = match[0]
+ language = "th"
+ score = 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_korean(words,data):
+ tag , match = data
+ text = match[0]
+ language = "ko"
+ score = 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_quotes(words,data):
+ tag , match = data
+ text = "".join(match)
+ childs = LangSegment.PARSE_TAG.findall(text)
+ if len(childs) > 0:
+ LangSegment._process_tags(words , text , False)
+ else:
+ cleans_text = LangSegment._cleans_text(match[1])
+ if len(cleans_text) <= 5:
+ LangSegment._parse_language(words,text)
+ else:
+ language,score = LangSegment._lang_classify(cleans_text)
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+
+ @staticmethod
+ def _process_pinyin(words,data):
+ tag , match = data
+ text = match
+ language = "zh"
+ score = 1.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_number(words,data): # "$0" process only
+ """
+ Numbers alone cannot accurately identify language.
+ Because numbers are universal in all languages.
+ So it won't be executed here, just for testing.
+ """
+ tag , match = data
+ language = words[0]["lang"] if len(words) > 0 else "zh"
+ text = match
+ score = 0.0
+ LangSegment._addwords(words,language,text,score)
+ pass
+
+ @staticmethod
+ def _process_tags(words , text , root_tag):
+ text_cache = LangSegment._text_cache
+ segments = re.split(LangSegment.PARSE_TAG, text)
+ segments_len = len(segments) - 1
+ for index , text in enumerate(segments):
+ if root_tag:LangSegment._lang_eos = index >= segments_len
+ if LangSegment.PARSE_TAG.match(text):
+ process , data = text_cache[text]
+ if process:process(words , data)
+ else:
+ LangSegment._parse_language(words , text)
+ pass
+ return words
+
+ @staticmethod
+ def _parse_symbols(text):
+ TAG_NUM = "00" # "00" => default channels , "$0" => testing channel
+ TAG_S1,TAG_S2,TAG_P1,TAG_P2,TAG_EN,TAG_KO,TAG_RU,TAG_TH = "$1" ,"$2" ,"$3" ,"$4" ,"$5" ,"$6" ,"$7","$8"
+ TAG_BASE = re.compile(fr'(([【《((“‘"\']*[LANGUAGE]+[\W\s]*)+)')
+ # Get custom language filter
+ filters = LangSegment.Langfilters
+ filters = filters if filters is not None else ""
+ # =======================================================================================================
+ # Experimental: Other language support.Thử nghiệm: Hỗ trợ ngôn ngữ khác.Expérimental : prise en charge d’autres langues.
+ # 相关语言字符如有缺失,熟悉相关语言的朋友,可以提交把缺失的发音符号补全。
+ # If relevant language characters are missing, friends who are familiar with the relevant languages can submit a submission to complete the missing pronunciation symbols.
+ # S'il manque des caractères linguistiques pertinents, les amis qui connaissent les langues concernées peuvent soumettre une soumission pour compléter les symboles de prononciation manquants.
+ # Nếu thiếu ký tự ngôn ngữ liên quan, những người bạn quen thuộc với ngôn ngữ liên quan có thể gửi bài để hoàn thành các ký hiệu phát âm còn thiếu.
+ # -------------------------------------------------------------------------------------------------------
+ # Preview feature, other language support
+ enablePreview = LangSegment.EnablePreview
+ if "fr" in filters or \
+ "vi" in filters:enablePreview = True
+ LangSegment.EnablePreview = enablePreview
+ # 实验性:法语字符支持。Prise en charge des caractères français
+ RE_FR = "" if not enablePreview else "àáâãäåæçèéêëìíîïðñòóôõöùúûüýþÿ"
+ # 实验性:越南语字符支持。Hỗ trợ ký tự tiếng Việt
+ RE_VI = "" if not enablePreview else "đơưăáàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựôâêơưỷỹ"
+ # -------------------------------------------------------------------------------------------------------
+ # Basic options:
+ process_list = [
+ ( TAG_S1 , re.compile(LangSegment.SYMBOLS_PATTERN) , LangSegment._process_symbol ), # Symbol Tag
+ ( TAG_KO , re.compile(re.sub(r'LANGUAGE',f'\uac00-\ud7a3',TAG_BASE.pattern)) , LangSegment._process_korean ), # Korean words
+ ( TAG_TH , re.compile(re.sub(r'LANGUAGE',f'\u0E00-\u0E7F',TAG_BASE.pattern)) , LangSegment._process_Thai ), # Thai words support.
+ ( TAG_RU , re.compile(re.sub(r'LANGUAGE',f'А-Яа-яЁё',TAG_BASE.pattern)) , LangSegment._process_Russian ), # Russian words support.
+ ( TAG_NUM , re.compile(r'(\W*\d+\W+\d*\W*\d*)') , LangSegment._process_number ), # Number words, Universal in all languages, Ignore it.
+ ( TAG_EN , re.compile(re.sub(r'LANGUAGE',f'a-zA-Z{RE_FR}{RE_VI}',TAG_BASE.pattern)) , LangSegment._process_english ), # English words + Other language support.
+ ( TAG_P1 , re.compile(r'(["\'])(.*?)(\1)') , LangSegment._process_quotes ), # Regular quotes
+ ( TAG_P2 , re.compile(r'([\n]*[【《((“‘])([^【《((“‘’”))》】]{3,})([’”))》】][\W\s]*[\n]{,1})') , LangSegment._process_quotes ), # Special quotes, There are left and right.
+ ]
+ # Extended options: Default False
+ if LangSegment.keepPinyin == True:process_list.insert(1 ,
+ ( TAG_S2 , re.compile(r'([\(({](?:\s*\w*\d\w*\s*)+[})\)])') , LangSegment._process_pinyin ), # Chinese Pinyin Tag.
+ )
+ # -------------------------------------------------------------------------------------------------------
+ words = []
+ lines = re.findall(r'.*\n*', re.sub(LangSegment.PARSE_TAG, '' ,text))
+ for index , text in enumerate(lines):
+ if len(text.strip()) == 0:continue
+ LangSegment._lang_eos = False
+ LangSegment._text_cache = {}
+ for item in process_list:
+ text = LangSegment._pattern_symbols(item , text)
+ cur_word = LangSegment._process_tags([] , text , True)
+ if len(cur_word) == 0:continue
+ cur_data = cur_word[0] if len(cur_word) > 0 else None
+ pre_data = words[-1] if len(words) > 0 else None
+ if cur_data and pre_data and cur_data["lang"] == pre_data["lang"]:
+ cur_data["text"] = f'{pre_data["text"]}{cur_data["text"]}'
+ words.pop()
+ words += cur_word
+ lang_count = LangSegment._lang_count
+ if lang_count and len(lang_count) > 0:
+ lang_count = dict(sorted(lang_count.items(), key=lambda x: x[1], reverse=True))
+ lang_count = list(lang_count.items())
+ LangSegment._lang_count = lang_count
+ return words
+
+ @staticmethod
+ def setfilters(filters):
+ # 当过滤器更改时,清除缓存
+ # 필터가 변경되면 캐시를 지웁니다.
+ # フィルタが変更されると、キャッシュがクリアされます
+ # When the filter changes, clear the cache
+ if LangSegment.Langfilters != filters:
+ LangSegment._clears()
+ LangSegment.Langfilters = filters
+ pass
+
+ @staticmethod
+ def getfilters():
+ return LangSegment.Langfilters
+
+ @staticmethod
+ def setPriorityThreshold(threshold:float):
+ LangSegment.LangPriorityThreshold = threshold
+ pass
+
+ @staticmethod
+ def getPriorityThreshold():
+ return LangSegment.LangPriorityThreshold
+
+ @staticmethod
+ def getCounts():
+ lang_count = LangSegment._lang_count
+ if lang_count is not None:return lang_count
+ text_langs = LangSegment._text_langs
+ if text_langs is None or len(text_langs) == 0:return [("zh",0)]
+ lang_counts = defaultdict(int)
+ for d in text_langs:lang_counts[d['lang']] += int(len(d['text'])*2) if d['lang'] == "zh" else len(d['text'])
+ lang_counts = dict(sorted(lang_counts.items(), key=lambda x: x[1], reverse=True))
+ lang_counts = list(lang_counts.items())
+ LangSegment._lang_count = lang_counts
+ return lang_counts
+
+ @staticmethod
+ def getTexts(text:str):
+ if text is None or len(text.strip()) == 0:
+ LangSegment._clears()
+ return []
+ # lasts
+ text_langs = LangSegment._text_langs
+ if LangSegment._text_lasts == text and text_langs is not None:return text_langs
+ # parse
+ LangSegment._text_waits = []
+ LangSegment._lang_count = None
+ LangSegment._text_lasts = text
+ text = LangSegment._parse_symbols(text)
+ LangSegment._text_langs = text
+ return text
+
+ @staticmethod
+ def classify(text:str):
+ return LangSegment.getTexts(text)
+
+
+def setfilters(filters):
+ """
+ 功能:语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
+ 기능: 언어 필터 그룹 기능, 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
+ 機能:言語フィルターグループ機能で、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
+ Function: Language filter group function, you can specify reserved languages. \n
+ Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.\n
+ Args:
+ filters (list): ["zh", "en", "ja", "ko"] 排名越前,优先级越高
+ """
+ LangSegment.setfilters(filters)
+ pass
+
+def getfilters():
+ """
+ 功能:语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
+ 기능: 언어 필터 그룹 기능, 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
+ 機能:言語フィルターグループ機能で、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
+ Function: Language filter group function, you can specify reserved languages. \n
+ Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.\n
+ Args:
+ filters (list): ["zh", "en", "ja", "ko"] 排名越前,优先级越高
+ """
+ return LangSegment.getfilters()
+
+# # @Deprecated:Use shorter setfilters
+# def setLangfilters(filters):
+# """
+# >0.1.9废除:使用更简短的setfilters
+# """
+# setfilters(filters)
+# # @Deprecated:Use shorter getfilters
+# def getLangfilters():
+# """
+# >0.1.9废除:使用更简短的getfilters
+# """
+# return getfilters()
+
+
+def setKeepPinyin(value:bool):
+ """
+ 可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。\n
+ 开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
+ """
+ LangSegment.keepPinyin = value
+ pass
+
+def getKeepPinyin():
+ """
+ 可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。\n
+ 开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
+ """
+ return LangSegment.keepPinyin
+
+def setEnablePreview(value:bool):
+ """
+ 启用预览版功能(默认关闭)
+ Enable preview functionality (off by default)
+ Args:
+ value (bool): True=开启, False=关闭
+ """
+ LangSegment.EnablePreview = (value == True)
+ pass
+
+def getEnablePreview():
+ """
+ 启用预览版功能(默认关闭)
+ Enable preview functionality (off by default)
+ Args:
+ value (bool): True=开启, False=关闭
+ """
+ return LangSegment.EnablePreview == True
+
+def setPriorityThreshold(threshold:float):
+ """
+ 中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
+ 中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
+ 중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
+ Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
+ Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
+ Args:
+ threshold:float (score range is 0 ~ 1)
+ """
+ LangSegment.setPriorityThreshold(threshold)
+ pass
+
+def getPriorityThreshold():
+ """
+ 中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
+ 中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
+ 중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
+ Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
+ Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
+ Args:
+ threshold:float (score range is 0 ~ 1)
+ """
+ return LangSegment.getPriorityThreshold()
+
+def getTexts(text:str):
+ """
+ 功能:对输入的文本进行多语种分词\n
+ 기능: 입력 텍스트의 다국어 분할 \n
+ 機能:入力されたテキストの多言語セグメンテーション\n
+ Feature: Tokenizing multilingual text input.\n
+ 参数-Args:
+ text (str): Text content,文本内容\n
+ 返回-Returns:
+ list: 示例结果:[{'lang':'zh','text':'?'},...]\n
+ lang=语种 , text=内容\n
+ """
+ return LangSegment.getTexts(text)
+
+def getCounts():
+ """
+ 功能:分词结果统计,按语种字数降序,用于确定其主要语言\n
+ 기능: 주요 언어를 결정하는 데 사용되는 언어별 단어 수 내림차순으로 단어 분할 결과의 통계 \n
+ 機能:主な言語を決定するために使用される、言語の単語数の降順による単語分割結果の統計\n
+ Function: Tokenizing multilingual text input.\n
+ 返回-Returns:
+ list: 示例结果:[('zh', 5), ('ja', 2), ('en', 1)] = [(语种,字数含标点)]\n
+ """
+ return LangSegment.getCounts()
+
+def classify(text:str):
+ """
+ 功能:兼容接口实现
+ Function: Compatible interface implementation
+ """
+ return LangSegment.classify(text)
+
+def printList(langlist):
+ """
+ 功能:打印数组结果
+ 기능: 어레이 결과 인쇄
+ 機能:配列結果を印刷
+ Function: Print array results
+ """
+ print("\n\n===================【打印结果】===================")
+ if langlist is None or len(langlist) == 0:
+ print("无内容结果,No content result")
+ return
+ for line in langlist:
+ print(line)
+ pass
+
+
+
+def main():
+
+ # -----------------------------------
+ # 更新日志:新版本分词更加精准。
+ # Changelog: The new version of the word segmentation is more accurate.
+ # チェンジログ:新しいバージョンの単語セグメンテーションはより正確です。
+ # Changelog: 분할이라는 단어의 새로운 버전이 더 정확합니다.
+ # -----------------------------------
+
+ # 输入示例1:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
+ # text = "“昨日は雨が降った,音楽、映画。。。”你今天学习日语了吗?春は桜の季節です。语种分词是语音合成必不可少的环节。言語分詞は音声合成に欠かせない環節である!"
+
+ # 输入示例2:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
+ # text = "欢迎来玩。東京,は日本の首都です。欢迎来玩. 太好了!"
+
+ # 输入示例3:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
+ # text = "明日、私たちは海辺にバカンスに行きます。你会说日语吗:“中国語、話せますか” 你的日语真好啊!"
+
+
+ # 输入示例4:(包含日文,中文,韩语,英文)Input Example 4: (including Japanese, Chinese, Korean, English)
+ # text = "你的名字叫佐々木?吗?韩语中的안녕 오빠读什么呢?あなたの体育の先生は誰ですか? 此次发布会带来了四款iPhone 15系列机型和三款Apple Watch等一系列新品,这次的iPad Air采用了LCD屏幕"
+
+
+ # 试验性支持:"fr"法语 , "vi"越南语 , "ru"俄语 , "th"泰语。Experimental: Other language support.
+ LangSegment.setfilters(["fr", "vi" , "ja", "zh", "ko", "en" , "ru" , "th"])
+ text = """
+我喜欢在雨天里听音乐。
+I enjoy listening to music on rainy days.
+雨の日に音楽を聴くのが好きです。
+비 오는 날에 음악을 듣는 것을 즐깁니다。
+J'aime écouter de la musique les jours de pluie.
+Tôi thích nghe nhạc vào những ngày mưa.
+Мне нравится слушать музыку в дождливую погоду.
+ฉันชอบฟังเพลงในวันที่ฝนตก
+"""
+
+
+ # 进行分词:(接入TTS项目仅需一行代码调用)Segmentation: (Only one line of code is required to access the TTS project)
+ langlist = LangSegment.getTexts(text)
+ printList(langlist)
+
+
+ # 语种统计:Language statistics:
+ print("\n===================【语种统计】===================")
+ # 获取所有语种数组结果,根据内容字数降序排列
+ # Get the array results in all languages, sorted in descending order according to the number of content words
+ langCounts = LangSegment.getCounts()
+ print(langCounts , "\n")
+
+ # 根据结果获取内容的主要语种 (语言,字数含标点)
+ # Get the main language of content based on the results (language, word count including punctuation)
+ lang , count = langCounts[0]
+ print(f"输入内容的主要语言为 = {lang} ,字数 = {count}")
+ print("==================================================\n")
+
+
+ # 分词输出:lang=语言,text=内容。Word output: lang = language, text = content
+ # ===================【打印结果】===================
+ # {'lang': 'zh', 'text': '你的名字叫'}
+ # {'lang': 'ja', 'text': '佐々木?'}
+ # {'lang': 'zh', 'text': '吗?韩语中的'}
+ # {'lang': 'ko', 'text': '안녕 오빠'}
+ # {'lang': 'zh', 'text': '读什么呢?'}
+ # {'lang': 'ja', 'text': 'あなたの体育の先生は誰ですか?'}
+ # {'lang': 'zh', 'text': ' 此次发布会带来了四款'}
+ # {'lang': 'en', 'text': 'i Phone '}
+ # {'lang': 'zh', 'text': '15系列机型和三款'}
+ # {'lang': 'en', 'text': 'Apple Watch '}
+ # {'lang': 'zh', 'text': '等一系列新品,这次的'}
+ # {'lang': 'en', 'text': 'i Pad Air '}
+ # {'lang': 'zh', 'text': '采用了'}
+ # {'lang': 'en', 'text': 'L C D '}
+ # {'lang': 'zh', 'text': '屏幕'}
+ # ===================【语种统计】===================
+
+ # ===================【语种统计】===================
+ # [('zh', 51), ('ja', 19), ('en', 18), ('ko', 5)]
+
+ # 输入内容的主要语言为 = zh ,字数 = 51
+ # ==================================================
+ # The main language of the input content is = zh, word count = 51
+
+
+if __name__ == "__main__":
+ main()
+
+
\ No newline at end of file
diff --git a/runtime/Lib/site-packages/LangSegment/__init__.py b/runtime/Lib/site-packages/LangSegment/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..114a3601aae915f7876621a81d97da5fe0943255
--- /dev/null
+++ b/runtime/Lib/site-packages/LangSegment/__init__.py
@@ -0,0 +1,8 @@
+from .LangSegment import LangSegment,getTexts,classify,getCounts,printList,setfilters,getfilters,setPriorityThreshold,getPriorityThreshold,setEnablePreview,getEnablePreview,setKeepPinyin,getKeepPinyin
+
+# release
+__version__ = '0.3.3'
+
+
+# develop
+__develop__ = 'dev-0.0.1'
\ No newline at end of file
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/INSTALLER b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/LICENSE.txt b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..910537bd33412dd9b70c4d07cedd41b519be7fb5
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/LICENSE.txt
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2008-2021, The joblib developers.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/METADATA b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..b8daf369a95e008542ad59b2637187228758ab30
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/METADATA
@@ -0,0 +1,167 @@
+Metadata-Version: 2.1
+Name: joblib
+Version: 1.2.0
+Summary: Lightweight pipelining with Python functions
+Home-page: https://joblib.readthedocs.io
+Author: Gael Varoquaux
+Author-email: gael.varoquaux@normalesup.org
+License: BSD
+Project-URL: Source, https://github.com/joblib/joblib
+Platform: any
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Science/Research
+Classifier: Intended Audience :: Education
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Topic :: Scientific/Engineering
+Classifier: Topic :: Utilities
+Classifier: Topic :: Software Development :: Libraries
+Requires-Python: >=3.7
+Description-Content-Type: text/x-rst
+License-File: LICENSE.txt
+
+|PyPi| |Azure| |ReadTheDocs| |Codecov|
+
+.. |PyPi| image:: https://badge.fury.io/py/joblib.svg
+ :target: https://badge.fury.io/py/joblib
+ :alt: Joblib version
+
+.. |Azure| image:: https://dev.azure.com/joblib/joblib/_apis/build/status/joblib.joblib?branchName=master
+ :target: https://dev.azure.com/joblib/joblib/_build?definitionId=3&_a=summary&branchFilter=40
+ :alt: Azure CI status
+
+.. |ReadTheDocs| image:: https://readthedocs.org/projects/joblib/badge/?version=latest
+ :target: https://joblib.readthedocs.io/en/latest/?badge=latest
+ :alt: Documentation Status
+
+.. |Codecov| image:: https://codecov.io/gh/joblib/joblib/branch/master/graph/badge.svg
+ :target: https://codecov.io/gh/joblib/joblib
+ :alt: Codecov coverage
+
+
+The homepage of joblib with user documentation is located on:
+
+https://joblib.readthedocs.io
+
+Getting the latest code
+=======================
+
+To get the latest code using git, simply type::
+
+ git clone git://github.com/joblib/joblib.git
+
+If you don't have git installed, you can download a zip or tarball
+of the latest code: http://github.com/joblib/joblib/archives/master
+
+Installing
+==========
+
+You can use `pip` to install joblib::
+
+ pip install joblib
+
+from any directory or::
+
+ python setup.py install
+
+from the source directory.
+
+Dependencies
+============
+
+- Joblib has no mandatory dependencies besides Python (supported versions are
+ 3.7+).
+- Joblib has an optional dependency on Numpy (at least version 1.6.1) for array
+ manipulation.
+- Joblib includes its own vendored copy of
+ `loky `_ for process management.
+- Joblib can efficiently dump and load numpy arrays but does not require numpy
+ to be installed.
+- Joblib has an optional dependency on
+ `python-lz4 `_ as a faster alternative to
+ zlib and gzip for compressed serialization.
+- Joblib has an optional dependency on psutil to mitigate memory leaks in
+ parallel worker processes.
+- Some examples require external dependencies such as pandas. See the
+ instructions in the `Building the docs`_ section for details.
+
+Workflow to contribute
+======================
+
+To contribute to joblib, first create an account on `github
+`_. Once this is done, fork the `joblib repository
+`_ to have your own repository,
+clone it using 'git clone' on the computers where you want to work. Make
+your changes in your clone, push them to your github account, test them
+on several computers, and when you are happy with them, send a pull
+request to the main repository.
+
+Running the test suite
+======================
+
+To run the test suite, you need the pytest (version >= 3) and coverage modules.
+Run the test suite using::
+
+ pytest joblib
+
+from the root of the project.
+
+Building the docs
+=================
+
+To build the docs you need to have sphinx (>=1.4) and some dependencies
+installed::
+
+ pip install -U -r .readthedocs-requirements.txt
+
+The docs can then be built with the following command::
+
+ make doc
+
+The html docs are located in the ``doc/_build/html`` directory.
+
+
+Making a source tarball
+=======================
+
+To create a source tarball, eg for packaging or distributing, run the
+following command::
+
+ python setup.py sdist
+
+The tarball will be created in the `dist` directory. This command will
+compile the docs, and the resulting tarball can be installed with
+no extra dependencies than the Python standard library. You will need
+setuptool and sphinx.
+
+Making a release and uploading it to PyPI
+=========================================
+
+This command is only run by project manager, to make a release, and
+upload in to PyPI::
+
+ python setup.py sdist bdist_wheel
+ twine upload dist/*
+
+
+Note that the documentation should automatically get updated at each git
+push. If that is not the case, try building th doc locally and resolve
+any doc build error (in particular when running the examples).
+
+Updating the changelog
+======================
+
+Changes are listed in the CHANGES.rst file. They must be manually updated
+but, the following git command may be used to generate the lines::
+
+ git log --abbrev-commit --date=short --no-merges --sparse
+
+
+
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/RECORD b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..4c107d2489f13aca07a250a34ce604fd05d62669
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/RECORD
@@ -0,0 +1,229 @@
+joblib-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+joblib-1.2.0.dist-info/LICENSE.txt,sha256=QmEpEcGHLF5LQ_auDo7llGfNNQMyJBz3LOkGQCZPrmo,1527
+joblib-1.2.0.dist-info/METADATA,sha256=8WqQd0iOL12Xi46VHDpPINbmuwBKJAbVZhm431qnTjc,5297
+joblib-1.2.0.dist-info/RECORD,,
+joblib-1.2.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
+joblib-1.2.0.dist-info/top_level.txt,sha256=P0LsoZ45gBL7ckL4lqQt7tdbrHD4xlVYhffmhHeeT_U,7
+joblib/__init__.py,sha256=CXOHJmaK9uQ_RyLc4X-FusXf_NDOwd9gIfkE13qA1yM,4995
+joblib/__pycache__/__init__.cpython-39.pyc,,
+joblib/__pycache__/_cloudpickle_wrapper.cpython-39.pyc,,
+joblib/__pycache__/_dask.cpython-39.pyc,,
+joblib/__pycache__/_deprecated_format_stack.cpython-39.pyc,,
+joblib/__pycache__/_deprecated_my_exceptions.cpython-39.pyc,,
+joblib/__pycache__/_memmapping_reducer.cpython-39.pyc,,
+joblib/__pycache__/_multiprocessing_helpers.cpython-39.pyc,,
+joblib/__pycache__/_parallel_backends.cpython-39.pyc,,
+joblib/__pycache__/_store_backends.cpython-39.pyc,,
+joblib/__pycache__/_utils.cpython-39.pyc,,
+joblib/__pycache__/backports.cpython-39.pyc,,
+joblib/__pycache__/compressor.cpython-39.pyc,,
+joblib/__pycache__/disk.cpython-39.pyc,,
+joblib/__pycache__/executor.cpython-39.pyc,,
+joblib/__pycache__/format_stack.cpython-39.pyc,,
+joblib/__pycache__/func_inspect.cpython-39.pyc,,
+joblib/__pycache__/hashing.cpython-39.pyc,,
+joblib/__pycache__/logger.cpython-39.pyc,,
+joblib/__pycache__/memory.cpython-39.pyc,,
+joblib/__pycache__/my_exceptions.cpython-39.pyc,,
+joblib/__pycache__/numpy_pickle.cpython-39.pyc,,
+joblib/__pycache__/numpy_pickle_compat.cpython-39.pyc,,
+joblib/__pycache__/numpy_pickle_utils.cpython-39.pyc,,
+joblib/__pycache__/parallel.cpython-39.pyc,,
+joblib/__pycache__/pool.cpython-39.pyc,,
+joblib/__pycache__/testing.cpython-39.pyc,,
+joblib/_cloudpickle_wrapper.py,sha256=fUx9s5qv2nMDi0xhIT7ttYJd6fGG8aYdBJbdXM-cBmc,376
+joblib/_dask.py,sha256=Tj4GRYMAucsTblVr0HYNDg0tPFgZcjP6zA55jyPj6NM,13006
+joblib/_deprecated_format_stack.py,sha256=_pPLwMH6hydhpPCNxRRTCkbcsKu-SdM0H-cxn5X-EDE,14505
+joblib/_deprecated_my_exceptions.py,sha256=q8QyZCf_sFBM6PUKaebZMTdIIyx8yeBuOfbyxZX7mA0,4134
+joblib/_memmapping_reducer.py,sha256=axuV2_zUxk7k7iJIWPXM9JXxh20_n3wHwrye1BfmmHE,28277
+joblib/_multiprocessing_helpers.py,sha256=t7wIXfrLfzqFXjOeOYs4JP45tptxmYm5_yE8ylIRbR8,1925
+joblib/_parallel_backends.py,sha256=1ui21a49B-xcu-l1dpzdzytb0sWKsiI0otiIir8o1hU,25438
+joblib/_store_backends.py,sha256=uH1_HSM4C28QM-mCR2Tlq5XQZpwQP7In5kxcWfX9ZO0,14434
+joblib/_utils.py,sha256=1Z5H3H2D0GVNMgQlCusSziMGHKHOl0V3um1tDLj-jY0,1116
+joblib/backports.py,sha256=SLHgXOABF9JiHan3RmI_jIIvkiWEyOoGecg8pIA7z1o,6082
+joblib/compressor.py,sha256=1u7lSlHAji0DMvH2qsxTol1dGzDNTWOsLLCFZuSq1AU,19769
+joblib/disk.py,sha256=PxUC63dBG2O1GriL1SLskHUjz7XzR-y6rqKEJHEY0jA,4389
+joblib/executor.py,sha256=wF4pTwot1wRzGLqozbQ8m46SN40RSUFVMLxprqxG2AY,5316
+joblib/externals/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+joblib/externals/__pycache__/__init__.cpython-39.pyc,,
+joblib/externals/cloudpickle/__init__.py,sha256=AjJuqYtfWZSP5igeJIFvAYsNy6kHgLen58Q4w-ZyWH4,292
+joblib/externals/cloudpickle/__pycache__/__init__.cpython-39.pyc,,
+joblib/externals/cloudpickle/__pycache__/cloudpickle.cpython-39.pyc,,
+joblib/externals/cloudpickle/__pycache__/cloudpickle_fast.cpython-39.pyc,,
+joblib/externals/cloudpickle/__pycache__/compat.cpython-39.pyc,,
+joblib/externals/cloudpickle/cloudpickle.py,sha256=tdSUqMaT1OQcSairpMCPqWn6npVpcdjLuTbhUjD11a8,35137
+joblib/externals/cloudpickle/cloudpickle_fast.py,sha256=BXEnvuGqN1rakNfxpmk0zEbZdQLqttn3n2QCO410mRk,34114
+joblib/externals/cloudpickle/compat.py,sha256=ITODUx0U_b7chpS47_Siqx7YP1rMYUpJH6B3rBANmWY,508
+joblib/externals/loky/__init__.py,sha256=V1JyKhbeXyZ4ThFoXVIvC3GQDc9FOXN4VHV6KV69xs0,1085
+joblib/externals/loky/__pycache__/__init__.cpython-39.pyc,,
+joblib/externals/loky/__pycache__/_base.cpython-39.pyc,,
+joblib/externals/loky/__pycache__/cloudpickle_wrapper.cpython-39.pyc,,
+joblib/externals/loky/__pycache__/initializers.cpython-39.pyc,,
+joblib/externals/loky/__pycache__/process_executor.cpython-39.pyc,,
+joblib/externals/loky/__pycache__/reusable_executor.cpython-39.pyc,,
+joblib/externals/loky/_base.py,sha256=Jd_A_xtbMztXEbsD5I8J1-UUv1M2BGFyrPMMnd9mA-Q,1057
+joblib/externals/loky/backend/__init__.py,sha256=7jTmGTrtjxnQF6rqX_xOd3odn22K-zbe4_Of5yZ6dTc,312
+joblib/externals/loky/backend/__pycache__/__init__.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/_posix_reduction.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/_win_reduction.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/context.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/fork_exec.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/popen_loky_posix.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/popen_loky_win32.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/process.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/queues.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/reduction.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/resource_tracker.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/spawn.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/synchronize.cpython-39.pyc,,
+joblib/externals/loky/backend/__pycache__/utils.cpython-39.pyc,,
+joblib/externals/loky/backend/_posix_reduction.py,sha256=FTCvX2f5IfKX5obn5tr61xP6TkN4E68L-mBhWr8tpn4,1801
+joblib/externals/loky/backend/_win_reduction.py,sha256=F6hddzf7ZPUj1O4OYJbZ12pJmBrvGZ3mDaispPa-iqo,2042
+joblib/externals/loky/backend/context.py,sha256=BIRF8utNPHzb0EbjplFzlL0YYa87bPKN2vbFE-NQxl4,11433
+joblib/externals/loky/backend/fork_exec.py,sha256=rBuA8fdO5TVaQBeV7TFrLri3VhLzseyKnBc04fB904A,1185
+joblib/externals/loky/backend/popen_loky_posix.py,sha256=9wOtvORNSP11KQKa8jRSVfQHVvel7lUtCWGRPEkMhTk,5556
+joblib/externals/loky/backend/popen_loky_win32.py,sha256=nll8E81wMpglVazStwo7k3OybdDqOItKA2L84VEr4ag,5052
+joblib/externals/loky/backend/process.py,sha256=LgGKNvSIN7uA-piZ3vdEWpJPgGepU73cRiacA9VqdG0,1798
+joblib/externals/loky/backend/queues.py,sha256=29UGM2u12PvXCB6c-Gkakmc_jlzdYzF0MoXlIileY6Q,6801
+joblib/externals/loky/backend/reduction.py,sha256=6IAslYWdqqotcVSh-6caV-Hy142BaqRQedR7pCYmvtU,7062
+joblib/externals/loky/backend/resource_tracker.py,sha256=Z6dqTP3SyAwtzVDEVbXeAwQj1BKkijhO1uSGst397ug,14359
+joblib/externals/loky/backend/spawn.py,sha256=mydRcNAvzdJt6f1v2T-ORXzF5DlmNKDYTnHukCTLzqE,8857
+joblib/externals/loky/backend/synchronize.py,sha256=CvVpKTTlaKhH0ED573XF9ZrBGau4eBjn3KQGYSCkOfU,11719
+joblib/externals/loky/backend/utils.py,sha256=-bzkl3uj8sr9pFzxUbL6_-f7W-ekC4P10Im1JxXwBcc,5738
+joblib/externals/loky/cloudpickle_wrapper.py,sha256=gUDfxIQ7sm_stiGym1lP5SP9xFbJnUbVZiIG_ypKE9s,3578
+joblib/externals/loky/initializers.py,sha256=XHjfNLD9Y5ruzrpg9geluDPxs4C-kn4s9q1iUGSBlGA,2539
+joblib/externals/loky/process_executor.py,sha256=XVSS0A3WcsweWfnaBnAVtStMtu-1X9y9MYeE-adaCkA,48885
+joblib/externals/loky/reusable_executor.py,sha256=_y61oYui2GMqq5XnOScrwH5Z82lFBgUI6nMnYMGnKBg,10028
+joblib/format_stack.py,sha256=I5WFLlnyYhrYEtZWJXtVhv70B7AwWV_pL4ElvgnIW1o,1045
+joblib/func_inspect.py,sha256=sS-Nc7Xe8SJXtRta8ILhzOCF2KG9TE_UGe5V9qTQIIg,13945
+joblib/hashing.py,sha256=NO90wKt1boeyAM8RlD0HtNwJHVsGLvKdVj9oRGpi8_Y,10537
+joblib/logger.py,sha256=xjTDhqjpQU8DjIqrL35IiZ1z7HJ-fgbVc-7Ijcii3Eg,5129
+joblib/memory.py,sha256=j5nTnYMzVDcQOtQYE68Oc_HAu_JY9bF8VXOysHfFvUQ,40609
+joblib/my_exceptions.py,sha256=-TkSV9Uy6kVSOSm870CQFYHIbIM6CJKlQtrrM-XRDAw,962
+joblib/numpy_pickle.py,sha256=58LBcb1HIvEoew4yCwPl18dvSnCA7F0zLTacOUimN7E,26869
+joblib/numpy_pickle_compat.py,sha256=eRRsub4aOB0fPmkC5L-JoKKs6Nv7hFs9ZwQmDmbANQg,8547
+joblib/numpy_pickle_utils.py,sha256=Ema4jJslsCG_HDIAtnjT7wDNw09Uv-5367N02SN3lAM,8705
+joblib/parallel.py,sha256=_4fVQXQ2mlnJeAaIJQHGNw3w32nw5Rj9pfW-FVi9bX4,48569
+joblib/pool.py,sha256=JuG9uuE3KJwR8gJZIGzwJqObJD0xFuUhQP2IYvgQab0,14334
+joblib/test/__init__.py,sha256=bkIwY5OneyPcRn2VuzQlIFdtW5Cwo1mUJ7IfSztDO9c,73
+joblib/test/__pycache__/__init__.cpython-39.pyc,,
+joblib/test/__pycache__/common.cpython-39.pyc,,
+joblib/test/__pycache__/test_backports.cpython-39.pyc,,
+joblib/test/__pycache__/test_cloudpickle_wrapper.cpython-39.pyc,,
+joblib/test/__pycache__/test_dask.cpython-39.pyc,,
+joblib/test/__pycache__/test_deprecated_objects.cpython-39.pyc,,
+joblib/test/__pycache__/test_disk.cpython-39.pyc,,
+joblib/test/__pycache__/test_format_stack.cpython-39.pyc,,
+joblib/test/__pycache__/test_func_inspect.cpython-39.pyc,,
+joblib/test/__pycache__/test_func_inspect_special_encoding.cpython-39.pyc,,
+joblib/test/__pycache__/test_hashing.cpython-39.pyc,,
+joblib/test/__pycache__/test_init.cpython-39.pyc,,
+joblib/test/__pycache__/test_logger.cpython-39.pyc,,
+joblib/test/__pycache__/test_memmapping.cpython-39.pyc,,
+joblib/test/__pycache__/test_memory.cpython-39.pyc,,
+joblib/test/__pycache__/test_missing_multiprocessing.cpython-39.pyc,,
+joblib/test/__pycache__/test_module.cpython-39.pyc,,
+joblib/test/__pycache__/test_my_exceptions.cpython-39.pyc,,
+joblib/test/__pycache__/test_numpy_pickle.cpython-39.pyc,,
+joblib/test/__pycache__/test_numpy_pickle_compat.cpython-39.pyc,,
+joblib/test/__pycache__/test_numpy_pickle_utils.cpython-39.pyc,,
+joblib/test/__pycache__/test_parallel.cpython-39.pyc,,
+joblib/test/__pycache__/test_store_backends.cpython-39.pyc,,
+joblib/test/__pycache__/test_testing.cpython-39.pyc,,
+joblib/test/__pycache__/test_utils.cpython-39.pyc,,
+joblib/test/__pycache__/testutils.cpython-39.pyc,,
+joblib/test/common.py,sha256=gWDIvGl8Ns6vPTBvItuSFoEWigI0EPXSoPkSvqSM4zM,3283
+joblib/test/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+joblib/test/data/__pycache__/__init__.cpython-39.pyc,,
+joblib/test/data/__pycache__/create_numpy_pickle.cpython-39.pyc,,
+joblib/test/data/create_numpy_pickle.py,sha256=9Gm6_T-pqe7LGTo0xbz3e1KjIhqKKb6A7ImSAlY2RyM,3459
+joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz,sha256=QYRH6Q2DSGVorjCSqWCxjTWCMOJKyew4Nl2qmfQVvQ8,769
+joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz,sha256=ofTozM_KlPJa50TR8FCwc09mMmO6OO0GQhgUBLNIsXs,757
+joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz,sha256=2eIVeA-XjOaT5IEQ6tI2UuHG3hwhiRciMmkBmPcIh4g,792
+joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz,sha256=Gr2z_1tVWDH1H3_wCVHmakknf8KqeHKT8Yz4d1vmUCM,794
+joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz,sha256=pWw_xuDbOkECqu1KGf1OFU7s2VbzC2v5F5iXhE7TwB4,790
+joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl,sha256=icRQjj374B-AHk5znxre0T9oWUHokoHIBQ8MqKo8l-U,986
+joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2,sha256=oYQVIyMiUxyRgWSuBBSOvCWKzToA-kUpcoQWdV4UoV4,997
+joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.gzip,sha256=Jpv3iGcDgKTv-O4nZsUreIbUK7qnt2cugZ-VMgNeEDQ,798
+joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.lzma,sha256=c0wu0x8pPv4BcStj7pE61rZpf68FLG_pNzQZ4e82zH8,660
+joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz,sha256=77FG1FDG0GHQav-1bxc4Tn9ky6ubUW_MbE0_iGmz5wc,712
+joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl,sha256=4GTC7s_cWNVShERn2nvVbspZYJgyK_0man4TEqvdVzU,1068
+joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.bz2,sha256=6G1vbs_iYmz2kYJ6w4qB1k7D67UnxUMus0S4SWeBtFo,1000
+joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.gzip,sha256=tlRUWeJS1BXmcwtLNSNK9L0hDHekFl07CqWxTShinmY,831
+joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.lzma,sha256=CorPwnfv3rR5hjNtJI01-sEBMOnkSxNlRVaWTszMopA,694
+joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz,sha256=Dppj3MffOKsKETeptEtDaxPOv6MA6xnbpK5LzlDQ-oE,752
+joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl,sha256=HL5Fb1uR9aPLjjhoOPJ2wwM1Qyo1FCZoYYd2HVw0Fos,1068
+joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2,sha256=Pyr2fqZnwfUxXdyrBr-kRwBYY8HA_Yi7fgSguKy5pUs,1021
+joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.gzip,sha256=os8NJjQI9FhnlZM-Ay9dX_Uo35gZnoJCgQSIVvcBPfE,831
+joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.lzma,sha256=Q_0y43qU7_GqAabJ8y3PWVhOisurnCAq3GzuCu04V58,697
+joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz,sha256=BNfmiQfpeLVpdfkwlJK4hJ5Cpgl0vreVyekyc5d_PNM,752
+joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl,sha256=l7nvLolhBDIdPFznOz3lBHiMOPBPCMi1bXop1tFSCpY,1068
+joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2,sha256=pqGpuIS-ZU4uP8mkglHs8MaSDiVcPy7l3XHYJSppRgY,1005
+joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.gzip,sha256=YRFXE6LEb6qK72yPqnXdqQVY8Ts8xKUS9PWQKhLxWvk,833
+joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.lzma,sha256=Bf7gCUeTuTjCkbcIdyZYz69irblX4SAVQEzxCnMQhNU,701
+joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz,sha256=As8w2LGWwwNmKy3QNdKljK63Yq46gjRf_RJ0lh5_WqA,752
+joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz,sha256=1WrnXDqDoNEPYOZX1Q5Wr2463b8vVV6fw4Wm5S4bMt4,800
+joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl,sha256=XmsOFxeC1f1aYdGETclG6yfF9rLoB11DayOAhDMULrw,1068
+joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2,sha256=vI2yWb50LKL_NgZyd_XkoD5teIg93uI42mWnx9ee-AQ,991
+joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.gzip,sha256=1WrnXDqDoNEPYOZX1Q5Wr2463b8vVV6fw4Wm5S4bMt4,800
+joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.lzma,sha256=IWA0JlZG2ur53HgTUDl1m7q79dcVq6b0VOq33gKoJU0,715
+joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz,sha256=3Xh_NbMZdBjYx7ynfJ3Fyke28izSRSSzzNB0z5D4k9Y,752
+joblib/test/data/joblib_0.8.4_compressed_pickle_py27_np17.gz,sha256=Sp-ZT7i6pj5on2gbptszu7RarzJpOmHJ67UKOmCPQMg,659
+joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np16.gz,sha256=NLtDrvo2XIH0KvUUAvhOqMeoXEjGW0IuTk_osu5XiDw,658
+joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np17.gz,sha256=NLtDrvo2XIH0KvUUAvhOqMeoXEjGW0IuTk_osu5XiDw,658
+joblib/test/data/joblib_0.9.2_compressed_pickle_py34_np19.gz,sha256=nzO9iiGkG3KbBdrF3usOho8higkrDj_lmICUzxZyF_Y,673
+joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz,sha256=nzO9iiGkG3KbBdrF3usOho8higkrDj_lmICUzxZyF_Y,673
+joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl,sha256=naijdk2xIeKdIa3mfJw0JlmOdtiN6uRM1yOJg6-M73M,670
+joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
+joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
+joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy,sha256=oMRa4qKJhBy-uiRDt-uqOzHAqencxzKUrKVynaAJJAU,236
+joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
+joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl,sha256=LynX8dLOygfxDfFywOgm7wgWOhSxLG7z-oDsU6X83Dw,670
+joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
+joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
+joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_03.npy,sha256=oMRa4qKJhBy-uiRDt-uqOzHAqencxzKUrKVynaAJJAU,236
+joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
+joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl,sha256=w9TLxpDTzp5TI6cU6lRvMsAasXEChcQgGE9s30sm_CU,691
+joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
+joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
+joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
+joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
+joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl,sha256=ilOBAOaulLFvKrD32S1NfnpiK-LfzA9rC3O2I7xROuI,691
+joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
+joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
+joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
+joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
+joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl,sha256=WfDVIqKcMzzh1gSAshIfzBoIpdLdZQuG79yYf5kfpOo,691
+joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
+joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
+joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
+joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
+joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz,sha256=8jYfWJsx0oY2J-3LlmEigK5cClnJSW2J2rfeSTZw-Ts,802
+joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_01.npy.z,sha256=YT9VvT3sEl2uWlOyvH2CkyE9Sok4od9O3kWtgeuUUqE,43
+joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_02.npy.z,sha256=txA5RDI0PRuiU_UNKY8pGp-zQgQQ9vaVvMi60hOPaVs,43
+joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_03.npy.z,sha256=d3AwICvU2MpSNjh2aPIsdJeGZLlDjANAF1Soa6uM0Po,37
+joblib/test/test_backports.py,sha256=Y9bhGa6H-K_FgLkDyXaSHzpaWk148Rjn8R9IKCKdy-k,1175
+joblib/test/test_cloudpickle_wrapper.py,sha256=GNaOG8SygvHfWNdhV5nirM3uo4F-5OB3yuGlg7xtrSY,749
+joblib/test/test_dask.py,sha256=LmHYrjNKa8v7I3hnEV1nmSzVoG6Ip5gOcBBrxlZDy0M,18004
+joblib/test/test_deprecated_objects.py,sha256=r5Y_Bcomk-CXvwCDlNrIN7eqXytVeQ4h_sMPinkPkrE,1077
+joblib/test/test_disk.py,sha256=wJd1o9nLzqEjLqxxkgB9S7-UcKjHPQ8qK5l0czcNp0o,2205
+joblib/test/test_format_stack.py,sha256=wTtjRlp0edNv7_NzxZU6DAVJQoebL-lnGsUEMwVZXpM,4250
+joblib/test/test_func_inspect.py,sha256=KDvLtRziyA_r6GiNEh05_zhlx9ntJW7abSuQ6cqJajU,8935
+joblib/test/test_func_inspect_special_encoding.py,sha256=oHbMTPOK3XI0YVoS0GsouJ-GfM_neP4GOIJC-TKnNgU,146
+joblib/test/test_hashing.py,sha256=bW7F8gLQwDpCOFRCAWlDx1iyGjQ3BDEYBol3vpEztaE,16078
+joblib/test/test_init.py,sha256=bgNF-9CIJl1MFNA75LBWOaiNtvduVfuvglz_u9Tt8Uc,422
+joblib/test/test_logger.py,sha256=WjxDzpRmdwj_Uyt2R-S3DFRT9CGTk7G2DWucU3sqbu8,985
+joblib/test/test_memmapping.py,sha256=l7uIhxgbcLh1WepMdB2IBEamZ_RisbVK38BQtdGPB1o,42512
+joblib/test/test_memory.py,sha256=sgoBhXWgZjWTb3GiV21RAn34ehpku5aaZjzWR6338Ow,43864
+joblib/test/test_missing_multiprocessing.py,sha256=oeneMgi6iUVIbkfazGvXmOp6fqa7ok9uhj902Qjs_nk,1123
+joblib/test/test_module.py,sha256=HTHQSgnwa-1blkvhL_oVBO5yYdw8IrQTIJCK_QCsMtM,1936
+joblib/test/test_my_exceptions.py,sha256=4_1xlIwbgEt6_bqaQ8lGyTfUAV7RhLMRRbQKIyYOTA8,2066
+joblib/test/test_numpy_pickle.py,sha256=dzt4F53-ANNEr0jWqCeppePIaHp7uh8vuCu7rx9-CtE,42357
+joblib/test/test_numpy_pickle_compat.py,sha256=C5OiaFrqmxYD57fr_LpmItd6OOZPeOMfo9RVr6ZZIkk,624
+joblib/test/test_numpy_pickle_utils.py,sha256=PJVVgr-v3so9oAf9LblASRCpt-wXAo19FvsUpw-fZjI,421
+joblib/test/test_parallel.py,sha256=WAnr1vHXnEN8muI-txTOXZ2AMv8hWVOoTxKqCgputhg,61231
+joblib/test/test_store_backends.py,sha256=fZh0_E5Rj5VTJ_UzH3autHpWwEaWQvWTiQB8felVAN4,1942
+joblib/test/test_testing.py,sha256=I-EkdKHWdHu8m5fo2NnyB0AqR8zAOJ01WKKvyZYRneY,2467
+joblib/test/test_utils.py,sha256=L6aBHiZrF6TUFbPGmQXGyNMnoAy5pEhOJoH5CAG_6CU,584
+joblib/test/testutils.py,sha256=6a7zVJm1kg6M-t4CH9tz8A6rMdC6ZY9sU6wBB8C7Zzo,251
+joblib/testing.py,sha256=JqQDWEkN76ZPmt65EswiERMofFre_JUFzBJgfmw2k2w,2260
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/WHEEL b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.37.1)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/runtime/Lib/site-packages/joblib-1.2.0.dist-info/top_level.txt b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ca4af27e2b6e9917d9600060588a18cc9e3cc78c
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib-1.2.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+joblib
diff --git a/runtime/Lib/site-packages/joblib/__init__.py b/runtime/Lib/site-packages/joblib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb124c45265a221578aa1e562334aabb76068438
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/__init__.py
@@ -0,0 +1,138 @@
+"""Joblib is a set of tools to provide **lightweight pipelining in
+Python**. In particular:
+
+1. transparent disk-caching of functions and lazy re-evaluation
+ (memoize pattern)
+
+2. easy simple parallel computing
+
+Joblib is optimized to be **fast** and **robust** on large
+data in particular and has specific optimizations for `numpy` arrays. It is
+**BSD-licensed**.
+
+
+ ==================== ===============================================
+ **Documentation:** https://joblib.readthedocs.io
+
+ **Download:** https://pypi.python.org/pypi/joblib#downloads
+
+ **Source code:** https://github.com/joblib/joblib
+
+ **Report issues:** https://github.com/joblib/joblib/issues
+ ==================== ===============================================
+
+
+Vision
+--------
+
+The vision is to provide tools to easily achieve better performance and
+reproducibility when working with long running jobs.
+
+ * **Avoid computing the same thing twice**: code is often rerun again and
+ again, for instance when prototyping computational-heavy jobs (as in
+ scientific development), but hand-crafted solutions to alleviate this
+ issue are error-prone and often lead to unreproducible results.
+
+ * **Persist to disk transparently**: efficiently persisting
+ arbitrary objects containing large data is hard. Using
+ joblib's caching mechanism avoids hand-written persistence and
+ implicitly links the file on disk to the execution context of
+ the original Python object. As a result, joblib's persistence is
+ good for resuming an application status or computational job, eg
+ after a crash.
+
+Joblib addresses these problems while **leaving your code and your flow
+control as unmodified as possible** (no framework, no new paradigms).
+
+Main features
+------------------
+
+1) **Transparent and fast disk-caching of output value:** a memoize or
+ make-like functionality for Python functions that works well for
+ arbitrary Python objects, including very large numpy arrays. Separate
+ persistence and flow-execution logic from domain logic or algorithmic
+ code by writing the operations as a set of steps with well-defined
+ inputs and outputs: Python functions. Joblib can save their
+ computation to disk and rerun it only if necessary::
+
+ >>> from joblib import Memory
+ >>> cachedir = 'your_cache_dir_goes_here'
+ >>> mem = Memory(cachedir)
+ >>> import numpy as np
+ >>> a = np.vander(np.arange(3)).astype(float)
+ >>> square = mem.cache(np.square)
+ >>> b = square(a) # doctest: +ELLIPSIS
+ ________________________________________________________________________________
+ [Memory] Calling square...
+ square(array([[0., 0., 1.],
+ [1., 1., 1.],
+ [4., 2., 1.]]))
+ ___________________________________________________________square - 0...s, 0.0min
+
+ >>> c = square(a)
+ >>> # The above call did not trigger an evaluation
+
+2) **Embarrassingly parallel helper:** to make it easy to write readable
+ parallel code and debug it quickly::
+
+ >>> from joblib import Parallel, delayed
+ >>> from math import sqrt
+ >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
+ [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
+
+
+3) **Fast compressed Persistence**: a replacement for pickle to work
+ efficiently on Python objects containing large data (
+ *joblib.dump* & *joblib.load* ).
+
+..
+ >>> import shutil ; shutil.rmtree(cachedir)
+
+"""
+
+# PEP0440 compatible formatted version, see:
+# https://www.python.org/dev/peps/pep-0440/
+#
+# Generic release markers:
+# X.Y
+# X.Y.Z # For bugfix releases
+#
+# Admissible pre-release markers:
+# X.YaN # Alpha release
+# X.YbN # Beta release
+# X.YrcN # Release Candidate
+# X.Y # Final release
+#
+# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
+# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
+#
+__version__ = '1.2.0'
+
+
+import os
+from .memory import Memory, MemorizedResult, register_store_backend
+from .logger import PrintTime
+from .logger import Logger
+from .hashing import hash
+from .numpy_pickle import dump
+from .numpy_pickle import load
+from .compressor import register_compressor
+from .parallel import Parallel
+from .parallel import delayed
+from .parallel import cpu_count
+from .parallel import register_parallel_backend
+from .parallel import parallel_backend
+from .parallel import effective_n_jobs
+from ._cloudpickle_wrapper import wrap_non_picklable_objects
+
+
+__all__ = ['Memory', 'MemorizedResult', 'PrintTime', 'Logger', 'hash', 'dump',
+ 'load', 'Parallel', 'delayed', 'cpu_count', 'effective_n_jobs',
+ 'register_parallel_backend', 'parallel_backend',
+ 'register_store_backend', 'register_compressor',
+ 'wrap_non_picklable_objects']
+
+
+# Workaround issue discovered in intel-openmp 2019.5:
+# https://github.com/ContinuumIO/anaconda-issues/issues/11294
+os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE")
diff --git a/runtime/Lib/site-packages/joblib/_cloudpickle_wrapper.py b/runtime/Lib/site-packages/joblib/_cloudpickle_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..3dbe3ae71acb539e4859a272e4ae936589b81890
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_cloudpickle_wrapper.py
@@ -0,0 +1,17 @@
+"""
+Small shim of loky's cloudpickle_wrapper to avoid failure when
+multiprocessing is not available.
+"""
+
+
+from ._multiprocessing_helpers import mp
+
+
+def my_wrap_non_picklable_objects(obj, keep_wrapper=True):
+ return obj
+
+
+if mp is None:
+ wrap_non_picklable_objects = my_wrap_non_picklable_objects
+else:
+ from .externals.loky import wrap_non_picklable_objects # noqa
diff --git a/runtime/Lib/site-packages/joblib/_dask.py b/runtime/Lib/site-packages/joblib/_dask.py
new file mode 100644
index 0000000000000000000000000000000000000000..57e247e91044e51a2c9a3553eacceb0a8b4daaa6
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_dask.py
@@ -0,0 +1,368 @@
+from __future__ import print_function, division, absolute_import
+
+import asyncio
+import concurrent.futures
+import contextlib
+
+import time
+from uuid import uuid4
+import weakref
+
+from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls
+from .parallel import parallel_backend
+
+try:
+ import dask
+ import distributed
+except ImportError:
+ dask = None
+ distributed = None
+
+if dask is not None and distributed is not None:
+ from dask.utils import funcname, itemgetter
+ from dask.sizeof import sizeof
+ from dask.distributed import (
+ Client,
+ as_completed,
+ get_client,
+ secede,
+ rejoin,
+ get_worker
+ )
+ from distributed.utils import thread_state
+
+
+ try:
+ # asyncio.TimeoutError, Python3-only error thrown by recent versions of
+ # distributed
+ from distributed.utils import TimeoutError as _TimeoutError
+ except ImportError:
+ from tornado.gen import TimeoutError as _TimeoutError
+
+
+def is_weakrefable(obj):
+ try:
+ weakref.ref(obj)
+ return True
+ except TypeError:
+ return False
+
+
+class _WeakKeyDictionary:
+ """A variant of weakref.WeakKeyDictionary for unhashable objects.
+
+ This datastructure is used to store futures for broadcasted data objects
+ such as large numpy arrays or pandas dataframes that are not hashable and
+ therefore cannot be used as keys of traditional python dicts.
+
+ Furthermore using a dict with id(array) as key is not safe because the
+ Python is likely to reuse id of recently collected arrays.
+ """
+
+ def __init__(self):
+ self._data = {}
+
+ def __getitem__(self, obj):
+ ref, val = self._data[id(obj)]
+ if ref() is not obj:
+ # In case of a race condition with on_destroy.
+ raise KeyError(obj)
+ return val
+
+ def __setitem__(self, obj, value):
+ key = id(obj)
+ try:
+ ref, _ = self._data[key]
+ if ref() is not obj:
+ # In case of race condition with on_destroy.
+ raise KeyError(obj)
+ except KeyError:
+ # Insert the new entry in the mapping along with a weakref
+ # callback to automatically delete the entry from the mapping
+ # as soon as the object used as key is garbage collected.
+ def on_destroy(_):
+ del self._data[key]
+ ref = weakref.ref(obj, on_destroy)
+ self._data[key] = ref, value
+
+ def __len__(self):
+ return len(self._data)
+
+ def clear(self):
+ self._data.clear()
+
+
+def _funcname(x):
+ try:
+ if isinstance(x, list):
+ x = x[0][0]
+ except Exception:
+ pass
+ return funcname(x)
+
+
+def _make_tasks_summary(tasks):
+ """Summarize of list of (func, args, kwargs) function calls"""
+ unique_funcs = {func for func, args, kwargs in tasks}
+
+ if len(unique_funcs) == 1:
+ mixed = False
+ else:
+ mixed = True
+ return len(tasks), mixed, _funcname(tasks)
+
+
+class Batch:
+ """dask-compatible wrapper that executes a batch of tasks"""
+ def __init__(self, tasks):
+ # collect some metadata from the tasks to ease Batch calls
+ # introspection when debugging
+ self._num_tasks, self._mixed, self._funcname = _make_tasks_summary(
+ tasks
+ )
+
+ def __call__(self, tasks=None):
+ results = []
+ with parallel_backend('dask'):
+ for func, args, kwargs in tasks:
+ results.append(func(*args, **kwargs))
+ return results
+
+ def __repr__(self):
+ descr = f"batch_of_{self._funcname}_{self._num_tasks}_calls"
+ if self._mixed:
+ descr = "mixed_" + descr
+ return descr
+
+
+def _joblib_probe_task():
+ # Noop used by the joblib connector to probe when workers are ready.
+ pass
+
+
+class DaskDistributedBackend(AutoBatchingMixin, ParallelBackendBase):
+ MIN_IDEAL_BATCH_DURATION = 0.2
+ MAX_IDEAL_BATCH_DURATION = 1.0
+ supports_timeout = True
+
+ def __init__(self, scheduler_host=None, scatter=None,
+ client=None, loop=None, wait_for_workers_timeout=10,
+ **submit_kwargs):
+ super().__init__()
+
+ if distributed is None:
+ msg = ("You are trying to use 'dask' as a joblib parallel backend "
+ "but dask is not installed. Please install dask "
+ "to fix this error.")
+ raise ValueError(msg)
+
+ if client is None:
+ if scheduler_host:
+ client = Client(scheduler_host, loop=loop,
+ set_as_default=False)
+ else:
+ try:
+ client = get_client()
+ except ValueError as e:
+ msg = ("To use Joblib with Dask first create a Dask Client"
+ "\n\n"
+ " from dask.distributed import Client\n"
+ " client = Client()\n"
+ "or\n"
+ " client = Client('scheduler-address:8786')")
+ raise ValueError(msg) from e
+
+ self.client = client
+
+ if scatter is not None and not isinstance(scatter, (list, tuple)):
+ raise TypeError("scatter must be a list/tuple, got "
+ "`%s`" % type(scatter).__name__)
+
+ if scatter is not None and len(scatter) > 0:
+ # Keep a reference to the scattered data to keep the ids the same
+ self._scatter = list(scatter)
+ scattered = self.client.scatter(scatter, broadcast=True)
+ self.data_futures = {id(x): f for x, f in zip(scatter, scattered)}
+ else:
+ self._scatter = []
+ self.data_futures = {}
+ self.wait_for_workers_timeout = wait_for_workers_timeout
+ self.submit_kwargs = submit_kwargs
+ self.waiting_futures = as_completed(
+ [],
+ loop=client.loop,
+ with_results=True,
+ raise_errors=False
+ )
+ self._results = {}
+ self._callbacks = {}
+
+ async def _collect(self):
+ while self._continue:
+ async for future, result in self.waiting_futures:
+ cf_future = self._results.pop(future)
+ callback = self._callbacks.pop(future)
+ if future.status == "error":
+ typ, exc, tb = result
+ cf_future.set_exception(exc)
+ else:
+ cf_future.set_result(result)
+ callback(result)
+ await asyncio.sleep(0.01)
+
+ def __reduce__(self):
+ return (DaskDistributedBackend, ())
+
+ def get_nested_backend(self):
+ return DaskDistributedBackend(client=self.client), -1
+
+ def configure(self, n_jobs=1, parallel=None, **backend_args):
+ self.parallel = parallel
+ return self.effective_n_jobs(n_jobs)
+
+ def start_call(self):
+ self._continue = True
+ self.client.loop.add_callback(self._collect)
+ self.call_data_futures = _WeakKeyDictionary()
+
+ def stop_call(self):
+ # The explicit call to clear is required to break a cycling reference
+ # to the futures.
+ self._continue = False
+ # wait for the future collection routine (self._backend._collect) to
+ # finish in order to limit asyncio warnings due to aborting _collect
+ # during a following backend termination call
+ time.sleep(0.01)
+ self.call_data_futures.clear()
+
+ def effective_n_jobs(self, n_jobs):
+ effective_n_jobs = sum(self.client.ncores().values())
+ if effective_n_jobs != 0 or not self.wait_for_workers_timeout:
+ return effective_n_jobs
+
+ # If there is no worker, schedule a probe task to wait for the workers
+ # to come up and be available. If the dask cluster is in adaptive mode
+ # task might cause the cluster to provision some workers.
+ try:
+ self.client.submit(_joblib_probe_task).result(
+ timeout=self.wait_for_workers_timeout)
+ except _TimeoutError as e:
+ error_msg = (
+ "DaskDistributedBackend has no worker after {} seconds. "
+ "Make sure that workers are started and can properly connect "
+ "to the scheduler and increase the joblib/dask connection "
+ "timeout with:\n\n"
+ "parallel_backend('dask', wait_for_workers_timeout={})"
+ ).format(self.wait_for_workers_timeout,
+ max(10, 2 * self.wait_for_workers_timeout))
+ raise TimeoutError(error_msg) from e
+ return sum(self.client.ncores().values())
+
+ async def _to_func_args(self, func):
+ itemgetters = dict()
+
+ # Futures that are dynamically generated during a single call to
+ # Parallel.__call__.
+ call_data_futures = getattr(self, 'call_data_futures', None)
+
+ async def maybe_to_futures(args):
+ out = []
+ for arg in args:
+ arg_id = id(arg)
+ if arg_id in itemgetters:
+ out.append(itemgetters[arg_id])
+ continue
+
+ f = self.data_futures.get(arg_id, None)
+ if f is None and call_data_futures is not None:
+ try:
+ f = await call_data_futures[arg]
+ except KeyError:
+ pass
+ if f is None:
+ if is_weakrefable(arg) and sizeof(arg) > 1e3:
+ # Automatically scatter large objects to some of
+ # the workers to avoid duplicated data transfers.
+ # Rely on automated inter-worker data stealing if
+ # more workers need to reuse this data
+ # concurrently.
+ # set hash=False - nested scatter calls (i.e
+ # calling client.scatter inside a dask worker)
+ # using hash=True often raise CancelledError,
+ # see dask/distributed#3703
+ _coro = self.client.scatter(
+ arg,
+ asynchronous=True,
+ hash=False
+ )
+ # Centralize the scattering of identical arguments
+ # between concurrent apply_async callbacks by
+ # exposing the running coroutine in
+ # call_data_futures before it completes.
+ t = asyncio.Task(_coro)
+ call_data_futures[arg] = t
+
+ f = await t
+
+ if f is not None:
+ out.append(f)
+ else:
+ out.append(arg)
+ return out
+
+ tasks = []
+ for f, args, kwargs in func.items:
+ args = list(await maybe_to_futures(args))
+ kwargs = dict(zip(kwargs.keys(),
+ await maybe_to_futures(kwargs.values())))
+ tasks.append((f, args, kwargs))
+
+ return (Batch(tasks), tasks)
+
+ def apply_async(self, func, callback=None):
+
+ cf_future = concurrent.futures.Future()
+ cf_future.get = cf_future.result # achieve AsyncResult API
+
+ async def f(func, callback):
+ batch, tasks = await self._to_func_args(func)
+ key = f'{repr(batch)}-{uuid4().hex}'
+
+ dask_future = self.client.submit(
+ batch, tasks=tasks, key=key, **self.submit_kwargs
+ )
+ self.waiting_futures.add(dask_future)
+ self._callbacks[dask_future] = callback
+ self._results[dask_future] = cf_future
+
+ self.client.loop.add_callback(f, func, callback)
+
+ return cf_future
+
+ def abort_everything(self, ensure_ready=True):
+ """ Tell the client to cancel any task submitted via this instance
+
+ joblib.Parallel will never access those results
+ """
+ with self.waiting_futures.lock:
+ self.waiting_futures.futures.clear()
+ while not self.waiting_futures.queue.empty():
+ self.waiting_futures.queue.get()
+
+ @contextlib.contextmanager
+ def retrieval_context(self):
+ """Override ParallelBackendBase.retrieval_context to avoid deadlocks.
+
+ This removes thread from the worker's thread pool (using 'secede').
+ Seceding avoids deadlock in nested parallelism settings.
+ """
+ # See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how
+ # this is used.
+ if hasattr(thread_state, 'execution_state'):
+ # we are in a worker. Secede to avoid deadlock.
+ secede()
+
+ yield
+
+ if hasattr(thread_state, 'execution_state'):
+ rejoin()
diff --git a/runtime/Lib/site-packages/joblib/_deprecated_format_stack.py b/runtime/Lib/site-packages/joblib/_deprecated_format_stack.py
new file mode 100644
index 0000000000000000000000000000000000000000..0593b87a88844e889937087c49c514e751a3f883
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_deprecated_format_stack.py
@@ -0,0 +1,397 @@
+"""
+Represent an exception with a lot of information.
+
+Provides 2 useful functions:
+
+format_exc: format an exception into a complete traceback, with full
+ debugging instruction.
+
+format_outer_frames: format the current position in the stack call.
+
+Adapted from IPython's VerboseTB.
+"""
+# Authors: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
+# Nathaniel Gray
+# Fernando Perez
+# Copyright: 2010, Gael Varoquaux
+# 2001-2004, Fernando Perez
+# 2001 Nathaniel Gray
+# License: BSD 3 clause
+# flake8: noqa
+
+
+import inspect
+import keyword
+import linecache
+import os
+import pydoc
+import sys
+import time
+import tokenize
+import traceback
+
+INDENT = ' ' * 8
+
+
+###############################################################################
+# some internal-use functions
+def safe_repr(value):
+ """Hopefully pretty robust repr equivalent."""
+ # this is pretty horrible but should always return *something*
+ try:
+ return pydoc.text.repr(value)
+ except KeyboardInterrupt:
+ raise
+ except:
+ try:
+ return repr(value)
+ except KeyboardInterrupt:
+ raise
+ except:
+ try:
+ # all still in an except block so we catch
+ # getattr raising
+ name = getattr(value, '__name__', None)
+ if name:
+ # ick, recursion
+ return safe_repr(name)
+ klass = getattr(value, '__class__', None)
+ if klass:
+ return '%s instance' % safe_repr(klass)
+ except KeyboardInterrupt:
+ raise
+ except:
+ return 'UNRECOVERABLE REPR FAILURE'
+
+
+def eq_repr(value, repr=safe_repr):
+ return '=%s' % repr(value)
+
+
+###############################################################################
+def uniq_stable(elems):
+ """uniq_stable(elems) -> list
+
+ Return from an iterable, a list of all the unique elements in the input,
+ but maintaining the order in which they first appear.
+
+ A naive solution to this problem which just makes a dictionary with the
+ elements as keys fails to respect the stability condition, since
+ dictionaries are unsorted by nature.
+
+ Note: All elements in the input must be hashable.
+ """
+ unique = []
+ unique_set = set()
+ for nn in elems:
+ if nn not in unique_set:
+ unique.append(nn)
+ unique_set.add(nn)
+ return unique
+
+
+###############################################################################
+def fix_frame_records_filenames(records):
+ """Try to fix the filenames in each record from inspect.getinnerframes().
+
+ Particularly, modules loaded from within zip files have useless filenames
+ attached to their code object, and inspect.getinnerframes() just uses it.
+ """
+ fixed_records = []
+ for frame, filename, line_no, func_name, lines, index in records:
+ # Look inside the frame's globals dictionary for __file__, which should
+ # be better.
+ better_fn = frame.f_globals.get('__file__', None)
+ if isinstance(better_fn, str):
+ # Check the type just in case someone did something weird with
+ # __file__. It might also be None if the error occurred during
+ # import.
+ filename = better_fn
+ fixed_records.append((frame, filename, line_no, func_name, lines,
+ index))
+ return fixed_records
+
+
+def _fixed_getframes(etb, context=1, tb_offset=0):
+ LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
+
+ records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
+
+ # If the error is at the console, don't build any context, since it would
+ # otherwise produce 5 blank lines printed out (there is no file at the
+ # console)
+ rec_check = records[tb_offset:]
+ try:
+ rname = rec_check[0][1]
+ if rname == '' or rname.endswith(''):
+ return rec_check
+ except IndexError:
+ pass
+
+ aux = traceback.extract_tb(etb)
+ assert len(records) == len(aux)
+ for i, (file, lnum, _, _) in enumerate(aux):
+ maybe_start = lnum - 1 - context // 2
+ start = max(maybe_start, 0)
+ end = start + context
+ lines = linecache.getlines(file)[start:end]
+ buf = list(records[i])
+ buf[LNUM_POS] = lnum
+ buf[INDEX_POS] = lnum - 1 - start
+ buf[LINES_POS] = lines
+ records[i] = tuple(buf)
+ return records[tb_offset:]
+
+
+def _format_traceback_lines(lnum, index, lines, lvals=None):
+ numbers_width = 7
+ res = []
+ i = lnum - index
+
+ for line in lines:
+ if i == lnum:
+ # This is the line with the error
+ pad = numbers_width - len(str(i))
+ if pad >= 3:
+ marker = '-' * (pad - 3) + '-> '
+ elif pad == 2:
+ marker = '> '
+ elif pad == 1:
+ marker = '>'
+ else:
+ marker = ''
+ num = marker + str(i)
+ else:
+ num = '%*s' % (numbers_width, i)
+ line = '%s %s' % (num, line)
+
+ res.append(line)
+ if lvals and i == lnum:
+ res.append(lvals + '\n')
+ i = i + 1
+ return res
+
+
+def format_records(records): # , print_globals=False):
+ # Loop over all records printing context and info
+ frames = []
+ abspath = os.path.abspath
+ for frame, file, lnum, func, lines, index in records:
+ try:
+ file = file and abspath(file) or '?'
+ except OSError:
+ # if file is '' or something not in the filesystem,
+ # the abspath call will throw an OSError. Just ignore it and
+ # keep the original file string.
+ pass
+
+ if file.endswith('.pyc'):
+ file = file[:-4] + '.py'
+
+ link = file
+
+ args, varargs, varkw, locals = inspect.getargvalues(frame)
+
+ if func == '?':
+ call = ''
+ else:
+ # Decide whether to include variable details or not
+ try:
+ call = 'in %s%s' % (func, inspect.formatargvalues(args,
+ varargs, varkw, locals,
+ formatvalue=eq_repr))
+ except KeyError:
+ # Very odd crash from inspect.formatargvalues(). The
+ # scenario under which it appeared was a call to
+ # view(array,scale) in NumTut.view.view(), where scale had
+ # been defined as a scalar (it should be a tuple). Somehow
+ # inspect messes up resolving the argument list of view()
+ # and barfs out. At some point I should dig into this one
+ # and file a bug report about it.
+ print("\nJoblib's exception reporting continues...\n")
+ call = 'in %s(***failed resolving arguments***)' % func
+
+ # Initialize a list of names on the current line, which the
+ # tokenizer below will populate.
+ names = []
+
+ def tokeneater(token_type, token, start, end, line):
+ """Stateful tokeneater which builds dotted names.
+
+ The list of names it appends to (from the enclosing scope) can
+ contain repeated composite names. This is unavoidable, since
+ there is no way to disambiguate partial dotted structures until
+ the full list is known. The caller is responsible for pruning
+ the final list of duplicates before using it."""
+
+ # build composite names
+ if token == '.':
+ try:
+ names[-1] += '.'
+ # store state so the next token is added for x.y.z names
+ tokeneater.name_cont = True
+ return
+ except IndexError:
+ pass
+ if token_type == tokenize.NAME and token not in keyword.kwlist:
+ if tokeneater.name_cont:
+ # Dotted names
+ names[-1] += token
+ tokeneater.name_cont = False
+ else:
+ # Regular new names. We append everything, the caller
+ # will be responsible for pruning the list later. It's
+ # very tricky to try to prune as we go, b/c composite
+ # names can fool us. The pruning at the end is easy
+ # to do (or the caller can print a list with repeated
+ # names if so desired.
+ names.append(token)
+ elif token_type == tokenize.NEWLINE:
+ raise IndexError
+ # we need to store a bit of state in the tokenizer to build
+ # dotted names
+ tokeneater.name_cont = False
+
+ def linereader(file=file, lnum=[lnum], getline=linecache.getline):
+ line = getline(file, lnum[0])
+ lnum[0] += 1
+ return line
+
+ # Build the list of names on this line of code where the exception
+ # occurred.
+ try:
+ # This builds the names list in-place by capturing it from the
+ # enclosing scope.
+ for token in tokenize.generate_tokens(linereader):
+ tokeneater(*token)
+ except (IndexError, UnicodeDecodeError, SyntaxError):
+ # signals exit of tokenizer
+ # SyntaxError can happen when trying to tokenize
+ # a compiled (e.g. .so or .pyd) extension
+ pass
+ except tokenize.TokenError as msg:
+ _m = ("An unexpected error occurred while tokenizing input file %s\n"
+ "The following traceback may be corrupted or invalid\n"
+ "The error message is: %s\n" % (file, msg))
+ print(_m)
+
+ # prune names list of duplicates, but keep the right order
+ unique_names = uniq_stable(names)
+
+ # Start loop over vars
+ lvals = []
+ for name_full in unique_names:
+ name_base = name_full.split('.', 1)[0]
+ if name_base in frame.f_code.co_varnames:
+ if name_base in locals.keys():
+ try:
+ value = safe_repr(eval(name_full, locals))
+ except:
+ value = "undefined"
+ else:
+ value = "undefined"
+ name = name_full
+ lvals.append('%s = %s' % (name, value))
+ #elif print_globals:
+ # if frame.f_globals.has_key(name_base):
+ # try:
+ # value = safe_repr(eval(name_full,frame.f_globals))
+ # except:
+ # value = "undefined"
+ # else:
+ # value = "undefined"
+ # name = 'global %s' % name_full
+ # lvals.append('%s = %s' % (name,value))
+ if lvals:
+ lvals = '%s%s' % (INDENT, ('\n%s' % INDENT).join(lvals))
+ else:
+ lvals = ''
+
+ level = '%s\n%s %s\n' % (75 * '.', link, call)
+
+ if index is None:
+ frames.append(level)
+ else:
+ frames.append('%s%s' % (level, ''.join(
+ _format_traceback_lines(lnum, index, lines, lvals))))
+
+ return frames
+
+
+###############################################################################
+def format_exc(etype, evalue, etb, context=5, tb_offset=0):
+ """ Return a nice text document describing the traceback.
+
+ Parameters
+ -----------
+ etype, evalue, etb: as returned by sys.exc_info
+ context: number of lines of the source file to plot
+ tb_offset: the number of stack frame not to use (0 = use all)
+
+ """
+ # some locals
+ try:
+ etype = etype.__name__
+ except AttributeError:
+ pass
+
+ # Header with the exception type, python version, and date
+ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
+ date = time.ctime(time.time())
+ pid = 'PID: %i' % os.getpid()
+
+ head = '%s%s%s\n%s%s%s' % (
+ etype, ' ' * (75 - len(str(etype)) - len(date)),
+ date, pid, ' ' * (75 - len(str(pid)) - len(pyver)),
+ pyver)
+
+ # Drop topmost frames if requested
+ records = _fixed_getframes(etb, context, tb_offset)
+
+ # Get (safely) a string form of the exception info
+ try:
+ etype_str, evalue_str = map(str, (etype, evalue))
+ except BaseException:
+ # User exception is improperly defined.
+ etype, evalue = str, sys.exc_info()[:2]
+ etype_str, evalue_str = map(str, (etype, evalue))
+ # ... and format it
+ exception = ['%s: %s' % (etype_str, evalue_str)]
+ frames = format_records(records)
+ return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))
+
+
+###############################################################################
+def format_outer_frames(context=5, stack_start=None, stack_end=None,
+ ignore_ipython=True):
+ LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
+ records = inspect.getouterframes(inspect.currentframe())
+ output = list()
+
+ for i, (frame, filename, line_no, func_name, lines, index) \
+ in enumerate(records):
+ # Look inside the frame's globals dictionary for __file__, which should
+ # be better.
+ better_fn = frame.f_globals.get('__file__', None)
+ if isinstance(better_fn, str):
+ # Check the type just in case someone did something weird with
+ # __file__. It might also be None if the error occurred during
+ # import.
+ filename = better_fn
+ if filename.endswith('.pyc'):
+ filename = filename[:-4] + '.py'
+ if ignore_ipython:
+ # Hack to avoid printing the internals of IPython
+ if (os.path.basename(filename) in ('iplib.py', 'py3compat.py')
+ and func_name in ('execfile', 'safe_execfile', 'runcode')):
+ break
+ maybe_start = line_no - 1 - context // 2
+ start = max(maybe_start, 0)
+ end = start + context
+ lines = linecache.getlines(filename)[start:end]
+ buf = list(records[i])
+ buf[LNUM_POS] = line_no
+ buf[INDEX_POS] = line_no - 1 - start
+ buf[LINES_POS] = lines
+ output.append(tuple(buf))
+ return '\n'.join(format_records(output[stack_end:stack_start:-1]))
diff --git a/runtime/Lib/site-packages/joblib/_deprecated_my_exceptions.py b/runtime/Lib/site-packages/joblib/_deprecated_my_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b879d2bcf554e7e016d490a0523663f68be5dfe
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_deprecated_my_exceptions.py
@@ -0,0 +1,115 @@
+"""
+Exceptions
+
+This module is deprecated and will be removed in joblib 0.16.
+"""
+# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
+# Copyright: 2010, Gael Varoquaux
+# License: BSD 3 clause
+
+
+class JoblibException(Exception):
+ """A simple exception with an error message that you can get to."""
+ def __init__(self, *args):
+ # We need to implement __init__ so that it is picked in the
+ # multiple heritance hierarchy in the class created in
+ # _mk_exception. Note: in Python 2, if you implement __init__
+ # in your exception class you need to set .args correctly,
+ # otherwise you can dump an exception instance with pickle but
+ # not load it (at load time an empty .args will be passed to
+ # the constructor). Also we want to be explicit and not use
+ # 'super' here. Using 'super' can cause a sibling class method
+ # to be called and we have no control the sibling class method
+ # constructor signature in the exception returned by
+ # _mk_exception.
+ Exception.__init__(self, *args)
+
+ def __repr__(self):
+ if hasattr(self, 'args') and len(self.args) > 0:
+ message = self.args[0]
+ else:
+ message = ''
+
+ name = self.__class__.__name__
+ return '%s\n%s\n%s\n%s' % (name, 75 * '_', message, 75 * '_')
+
+ __str__ = __repr__
+
+
+class TransportableException(JoblibException):
+ """An exception containing all the info to wrap an original
+ exception and recreate it.
+ """
+
+ def __init__(self, message, etype):
+ # The next line set the .args correctly. This is needed to
+ # make the exception loadable with pickle
+ JoblibException.__init__(self, message, etype)
+ self.message = message
+ self.etype = etype
+
+ def unwrap(self, context_message=""):
+ report = """\
+%s
+---------------------------------------------------------------------------
+Joblib worker traceback:
+---------------------------------------------------------------------------
+%s""" % (context_message, self.message)
+ # Unwrap the exception to a JoblibException
+ exception_type = _mk_exception(self.etype)[0]
+ return exception_type(report)
+
+
+_exception_mapping = dict()
+
+
+def _mk_exception(exception, name=None):
+ if issubclass(exception, JoblibException):
+ # No need to wrap recursively JoblibException
+ return exception, exception.__name__
+
+ # Create an exception inheriting from both JoblibException
+ # and that exception
+ if name is None:
+ name = exception.__name__
+ this_name = 'Joblib%s' % name
+ if this_name in _exception_mapping:
+ # Avoid creating twice the same exception
+ this_exception = _exception_mapping[this_name]
+ else:
+ if exception is Exception:
+ # JoblibException is already a subclass of Exception. No
+ # need to use multiple inheritance
+ return JoblibException, this_name
+ try:
+ this_exception = type(
+ this_name, (JoblibException, exception), {})
+ _exception_mapping[this_name] = this_exception
+ except TypeError:
+ # This happens if "Cannot create a consistent method
+ # resolution order", e.g. because 'exception' is a
+ # subclass of JoblibException or 'exception' is not an
+ # acceptable base class
+ this_exception = JoblibException
+
+ return this_exception, this_name
+
+
+def _mk_common_exceptions():
+ namespace = dict()
+ import builtins as _builtin_exceptions
+ common_exceptions = filter(
+ lambda x: x.endswith('Error'),
+ dir(_builtin_exceptions))
+
+ for name in common_exceptions:
+ obj = getattr(_builtin_exceptions, name)
+ if isinstance(obj, type) and issubclass(obj, BaseException):
+ this_obj, this_name = _mk_exception(obj, name=name)
+ namespace[this_name] = this_obj
+ return namespace
+
+
+# Updating module locals so that the exceptions pickle right. AFAIK this
+# works only at module-creation time
+locals().update(_mk_common_exceptions())
diff --git a/runtime/Lib/site-packages/joblib/_memmapping_reducer.py b/runtime/Lib/site-packages/joblib/_memmapping_reducer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d350c0320caf5b718425b3d4e5b8c4776298b4b
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_memmapping_reducer.py
@@ -0,0 +1,668 @@
+"""
+Reducer using memory mapping for numpy arrays
+"""
+# Author: Thomas Moreau
+# Copyright: 2017, Thomas Moreau
+# License: BSD 3 clause
+
+from mmap import mmap
+import errno
+import os
+import stat
+import threading
+import atexit
+import tempfile
+import time
+import warnings
+import weakref
+from uuid import uuid4
+from multiprocessing import util
+
+from pickle import whichmodule, loads, dumps, HIGHEST_PROTOCOL, PicklingError
+
+try:
+ WindowsError
+except NameError:
+ WindowsError = type(None)
+
+try:
+ import numpy as np
+ from numpy.lib.stride_tricks import as_strided
+except ImportError:
+ np = None
+
+from .numpy_pickle import dump, load, load_temporary_memmap
+from .backports import make_memmap
+from .disk import delete_folder
+from .externals.loky.backend import resource_tracker
+
+# Some system have a ramdisk mounted by default, we can use it instead of /tmp
+# as the default folder to dump big arrays to share with subprocesses.
+SYSTEM_SHARED_MEM_FS = '/dev/shm'
+
+# Minimal number of bytes available on SYSTEM_SHARED_MEM_FS to consider using
+# it as the default folder to dump big arrays to share with subprocesses.
+SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(2e9)
+
+# Folder and file permissions to chmod temporary files generated by the
+# memmapping pool. Only the owner of the Python process can access the
+# temporary files and folder.
+FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
+FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR
+
+# Set used in joblib workers, referencing the filenames of temporary memmaps
+# created by joblib to speed up data communication. In child processes, we add
+# a finalizer to these memmaps that sends a maybe_unlink call to the
+# resource_tracker, in order to free main memory as fast as possible.
+JOBLIB_MMAPS = set()
+
+
+def _log_and_unlink(filename):
+ from .externals.loky.backend.resource_tracker import _resource_tracker
+ util.debug(
+ "[FINALIZER CALL] object mapping to {} about to be deleted,"
+ " decrementing the refcount of the file (pid: {})".format(
+ os.path.basename(filename), os.getpid()))
+ _resource_tracker.maybe_unlink(filename, "file")
+
+
+def add_maybe_unlink_finalizer(memmap):
+ util.debug(
+ "[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})"
+ "".format(type(memmap), id(memmap), os.path.basename(memmap.filename),
+ os.getpid()))
+ weakref.finalize(memmap, _log_and_unlink, memmap.filename)
+
+
+def unlink_file(filename):
+ """Wrapper around os.unlink with a retry mechanism.
+
+ The retry mechanism has been implemented primarily to overcome a race
+ condition happening during the finalizer of a np.memmap: when a process
+ holding the last reference to a mmap-backed np.memmap/np.array is about to
+ delete this array (and close the reference), it sends a maybe_unlink
+ request to the resource_tracker. This request can be processed faster than
+ it takes for the last reference of the memmap to be closed, yielding (on
+ Windows) a PermissionError in the resource_tracker loop.
+ """
+ NUM_RETRIES = 10
+ for retry_no in range(1, NUM_RETRIES + 1):
+ try:
+ os.unlink(filename)
+ break
+ except PermissionError:
+ util.debug(
+ '[ResourceTracker] tried to unlink {}, got '
+ 'PermissionError'.format(filename)
+ )
+ if retry_no == NUM_RETRIES:
+ raise
+ else:
+ time.sleep(.2)
+ except FileNotFoundError:
+ # In case of a race condition when deleting the temporary folder,
+ # avoid noisy FileNotFoundError exception in the resource tracker.
+ pass
+
+
+resource_tracker._CLEANUP_FUNCS['file'] = unlink_file
+
+
+class _WeakArrayKeyMap:
+ """A variant of weakref.WeakKeyDictionary for unhashable numpy arrays.
+
+ This datastructure will be used with numpy arrays as obj keys, therefore we
+ do not use the __get__ / __set__ methods to avoid any conflict with the
+ numpy fancy indexing syntax.
+ """
+
+ def __init__(self):
+ self._data = {}
+
+ def get(self, obj):
+ ref, val = self._data[id(obj)]
+ if ref() is not obj:
+ # In case of race condition with on_destroy: could never be
+ # triggered by the joblib tests with CPython.
+ raise KeyError(obj)
+ return val
+
+ def set(self, obj, value):
+ key = id(obj)
+ try:
+ ref, _ = self._data[key]
+ if ref() is not obj:
+ # In case of race condition with on_destroy: could never be
+ # triggered by the joblib tests with CPython.
+ raise KeyError(obj)
+ except KeyError:
+ # Insert the new entry in the mapping along with a weakref
+ # callback to automatically delete the entry from the mapping
+ # as soon as the object used as key is garbage collected.
+ def on_destroy(_):
+ del self._data[key]
+ ref = weakref.ref(obj, on_destroy)
+ self._data[key] = ref, value
+
+ def __getstate__(self):
+ raise PicklingError("_WeakArrayKeyMap is not pickleable")
+
+
+###############################################################################
+# Support for efficient transient pickling of numpy data structures
+
+
+def _get_backing_memmap(a):
+ """Recursively look up the original np.memmap instance base if any."""
+ b = getattr(a, 'base', None)
+ if b is None:
+ # TODO: check scipy sparse datastructure if scipy is installed
+ # a nor its descendants do not have a memmap base
+ return None
+
+ elif isinstance(b, mmap):
+ # a is already a real memmap instance.
+ return a
+
+ else:
+ # Recursive exploration of the base ancestry
+ return _get_backing_memmap(b)
+
+
+def _get_temp_dir(pool_folder_name, temp_folder=None):
+ """Get the full path to a subfolder inside the temporary folder.
+
+ Parameters
+ ----------
+ pool_folder_name : str
+ Sub-folder name used for the serialization of a pool instance.
+
+ temp_folder: str, optional
+ Folder to be used by the pool for memmapping large arrays
+ for sharing memory with worker processes. If None, this will try in
+ order:
+
+ - a folder pointed by the JOBLIB_TEMP_FOLDER environment
+ variable,
+ - /dev/shm if the folder exists and is writable: this is a
+ RAMdisk filesystem available by default on modern Linux
+ distributions,
+ - the default system temporary folder that can be
+ overridden with TMP, TMPDIR or TEMP environment
+ variables, typically /tmp under Unix operating systems.
+
+ Returns
+ -------
+ pool_folder : str
+ full path to the temporary folder
+ use_shared_mem : bool
+ whether the temporary folder is written to the system shared memory
+ folder or some other temporary folder.
+ """
+ use_shared_mem = False
+ if temp_folder is None:
+ temp_folder = os.environ.get('JOBLIB_TEMP_FOLDER', None)
+ if temp_folder is None:
+ if os.path.exists(SYSTEM_SHARED_MEM_FS):
+ try:
+ shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS)
+ available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail
+ if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE:
+ # Try to see if we have write access to the shared mem
+ # folder only if it is reasonably large (that is 2GB or
+ # more).
+ temp_folder = SYSTEM_SHARED_MEM_FS
+ pool_folder = os.path.join(temp_folder, pool_folder_name)
+ if not os.path.exists(pool_folder):
+ os.makedirs(pool_folder)
+ use_shared_mem = True
+ except (IOError, OSError):
+ # Missing rights in the /dev/shm partition, fallback to regular
+ # temp folder.
+ temp_folder = None
+ if temp_folder is None:
+ # Fallback to the default tmp folder, typically /tmp
+ temp_folder = tempfile.gettempdir()
+ temp_folder = os.path.abspath(os.path.expanduser(temp_folder))
+ pool_folder = os.path.join(temp_folder, pool_folder_name)
+ return pool_folder, use_shared_mem
+
+
+def has_shareable_memory(a):
+ """Return True if a is backed by some mmap buffer directly or not."""
+ return _get_backing_memmap(a) is not None
+
+
+def _strided_from_memmap(filename, dtype, mode, offset, order, shape, strides,
+ total_buffer_len, unlink_on_gc_collect):
+ """Reconstruct an array view on a memory mapped file."""
+ if mode == 'w+':
+ # Do not zero the original data when unpickling
+ mode = 'r+'
+
+ if strides is None:
+ # Simple, contiguous memmap
+ return make_memmap(
+ filename, dtype=dtype, shape=shape, mode=mode, offset=offset,
+ order=order, unlink_on_gc_collect=unlink_on_gc_collect
+ )
+ else:
+ # For non-contiguous data, memmap the total enclosing buffer and then
+ # extract the non-contiguous view with the stride-tricks API
+ base = make_memmap(
+ filename, dtype=dtype, shape=total_buffer_len, offset=offset,
+ mode=mode, order=order, unlink_on_gc_collect=unlink_on_gc_collect
+ )
+ return as_strided(base, shape=shape, strides=strides)
+
+
+def _reduce_memmap_backed(a, m):
+ """Pickling reduction for memmap backed arrays.
+
+ a is expected to be an instance of np.ndarray (or np.memmap)
+ m is expected to be an instance of np.memmap on the top of the ``base``
+ attribute ancestry of a. ``m.base`` should be the real python mmap object.
+ """
+ # offset that comes from the striding differences between a and m
+ util.debug('[MEMMAP REDUCE] reducing a memmap-backed array '
+ '(shape, {}, pid: {})'.format(a.shape, os.getpid()))
+ a_start, a_end = np.byte_bounds(a)
+ m_start = np.byte_bounds(m)[0]
+ offset = a_start - m_start
+
+ # offset from the backing memmap
+ offset += m.offset
+
+ if m.flags['F_CONTIGUOUS']:
+ order = 'F'
+ else:
+ # The backing memmap buffer is necessarily contiguous hence C if not
+ # Fortran
+ order = 'C'
+
+ if a.flags['F_CONTIGUOUS'] or a.flags['C_CONTIGUOUS']:
+ # If the array is a contiguous view, no need to pass the strides
+ strides = None
+ total_buffer_len = None
+ else:
+ # Compute the total number of items to map from which the strided
+ # view will be extracted.
+ strides = a.strides
+ total_buffer_len = (a_end - a_start) // a.itemsize
+
+ return (_strided_from_memmap,
+ (m.filename, a.dtype, m.mode, offset, order, a.shape, strides,
+ total_buffer_len, False))
+
+
+def reduce_array_memmap_backward(a):
+ """reduce a np.array or a np.memmap from a child process"""
+ m = _get_backing_memmap(a)
+ if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS:
+ # if a is backed by a memmaped file, reconstruct a using the
+ # memmaped file.
+ return _reduce_memmap_backed(a, m)
+ else:
+ # a is either a regular (not memmap-backed) numpy array, or an array
+ # backed by a shared temporary file created by joblib. In the latter
+ # case, in order to limit the lifespan of these temporary files, we
+ # serialize the memmap as a regular numpy array, and decref the
+ # file backing the memmap (done implicitly in a previously registered
+ # finalizer, see ``unlink_on_gc_collect`` for more details)
+ return (
+ loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL), )
+ )
+
+
+class ArrayMemmapForwardReducer(object):
+ """Reducer callable to dump large arrays to memmap files.
+
+ Parameters
+ ----------
+ max_nbytes: int
+ Threshold to trigger memmapping of large arrays to files created
+ a folder.
+ temp_folder_resolver: callable
+ An callable in charge of resolving a temporary folder name where files
+ for backing memmapped arrays are created.
+ mmap_mode: 'r', 'r+' or 'c'
+ Mode for the created memmap datastructure. See the documentation of
+ numpy.memmap for more details. Note: 'w+' is coerced to 'r+'
+ automatically to avoid zeroing the data on unpickling.
+ verbose: int, optional, 0 by default
+ If verbose > 0, memmap creations are logged.
+ If verbose > 1, both memmap creations, reuse and array pickling are
+ logged.
+ prewarm: bool, optional, False by default.
+ Force a read on newly memmapped array to make sure that OS pre-cache it
+ memory. This can be useful to avoid concurrent disk access when the
+ same data array is passed to different worker processes.
+ """
+
+ def __init__(self, max_nbytes, temp_folder_resolver, mmap_mode,
+ unlink_on_gc_collect, verbose=0, prewarm=True):
+ self._max_nbytes = max_nbytes
+ self._temp_folder_resolver = temp_folder_resolver
+ self._mmap_mode = mmap_mode
+ self.verbose = int(verbose)
+ if prewarm == "auto":
+ self._prewarm = not self._temp_folder.startswith(
+ SYSTEM_SHARED_MEM_FS
+ )
+ else:
+ self._prewarm = prewarm
+ self._prewarm = prewarm
+ self._memmaped_arrays = _WeakArrayKeyMap()
+ self._temporary_memmaped_filenames = set()
+ self._unlink_on_gc_collect = unlink_on_gc_collect
+
+ @property
+ def _temp_folder(self):
+ return self._temp_folder_resolver()
+
+ def __reduce__(self):
+ # The ArrayMemmapForwardReducer is passed to the children processes: it
+ # needs to be pickled but the _WeakArrayKeyMap need to be skipped as
+ # it's only guaranteed to be consistent with the parent process memory
+ # garbage collection.
+ # Although this reducer is pickled, it is not needed in its destination
+ # process (child processes), as we only use this reducer to send
+ # memmaps from the parent process to the children processes. For this
+ # reason, we can afford skipping the resolver, (which would otherwise
+ # be unpicklable), and pass it as None instead.
+ args = (self._max_nbytes, None, self._mmap_mode,
+ self._unlink_on_gc_collect)
+ kwargs = {
+ 'verbose': self.verbose,
+ 'prewarm': self._prewarm,
+ }
+ return ArrayMemmapForwardReducer, args, kwargs
+
+ def __call__(self, a):
+ m = _get_backing_memmap(a)
+ if m is not None and isinstance(m, np.memmap):
+ # a is already backed by a memmap file, let's reuse it directly
+ return _reduce_memmap_backed(a, m)
+
+ if (not a.dtype.hasobject and self._max_nbytes is not None and
+ a.nbytes > self._max_nbytes):
+ # check that the folder exists (lazily create the pool temp folder
+ # if required)
+ try:
+ os.makedirs(self._temp_folder)
+ os.chmod(self._temp_folder, FOLDER_PERMISSIONS)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise e
+
+ try:
+ basename = self._memmaped_arrays.get(a)
+ except KeyError:
+ # Generate a new unique random filename. The process and thread
+ # ids are only useful for debugging purpose and to make it
+ # easier to cleanup orphaned files in case of hard process
+ # kill (e.g. by "kill -9" or segfault).
+ basename = "{}-{}-{}.pkl".format(
+ os.getpid(), id(threading.current_thread()), uuid4().hex)
+ self._memmaped_arrays.set(a, basename)
+ filename = os.path.join(self._temp_folder, basename)
+
+ # In case the same array with the same content is passed several
+ # times to the pool subprocess children, serialize it only once
+
+ is_new_memmap = filename not in self._temporary_memmaped_filenames
+
+ # add the memmap to the list of temporary memmaps created by joblib
+ self._temporary_memmaped_filenames.add(filename)
+
+ if self._unlink_on_gc_collect:
+ # Bump reference count of the memmap by 1 to account for
+ # shared usage of the memmap by a child process. The
+ # corresponding decref call will be executed upon calling
+ # resource_tracker.maybe_unlink, registered as a finalizer in
+ # the child.
+ # the incref/decref calls here are only possible when the child
+ # and the parent share the same resource_tracker. It is not the
+ # case for the multiprocessing backend, but it does not matter
+ # because unlinking a memmap from a child process is only
+ # useful to control the memory usage of long-lasting child
+ # processes, while the multiprocessing-based pools terminate
+ # their workers at the end of a map() call.
+ resource_tracker.register(filename, "file")
+
+ if is_new_memmap:
+ # Incref each temporary memmap created by joblib one extra
+ # time. This means that these memmaps will only be deleted
+ # once an extra maybe_unlink() is called, which is done once
+ # all the jobs have completed (or been canceled) in the
+ # Parallel._terminate_backend() method.
+ resource_tracker.register(filename, "file")
+
+ if not os.path.exists(filename):
+ util.debug(
+ "[ARRAY DUMP] Pickling new array (shape={}, dtype={}) "
+ "creating a new memmap at {}".format(
+ a.shape, a.dtype, filename))
+ for dumped_filename in dump(a, filename):
+ os.chmod(dumped_filename, FILE_PERMISSIONS)
+
+ if self._prewarm:
+ # Warm up the data by accessing it. This operation ensures
+ # that the disk access required to create the memmapping
+ # file are performed in the reducing process and avoids
+ # concurrent memmap creation in multiple children
+ # processes.
+ load(filename, mmap_mode=self._mmap_mode).max()
+
+ else:
+ util.debug(
+ "[ARRAY DUMP] Pickling known array (shape={}, dtype={}) "
+ "reusing memmap file: {}".format(
+ a.shape, a.dtype, os.path.basename(filename)))
+
+ # The worker process will use joblib.load to memmap the data
+ return (
+ (load_temporary_memmap, (filename, self._mmap_mode,
+ self._unlink_on_gc_collect))
+ )
+ else:
+ # do not convert a into memmap, let pickler do its usual copy with
+ # the default system pickler
+ util.debug(
+ '[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={}, '
+ ' dtype={}).'.format(a.shape, a.dtype))
+ return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),))
+
+
+def get_memmapping_reducers(
+ forward_reducers=None, backward_reducers=None,
+ temp_folder_resolver=None, max_nbytes=1e6, mmap_mode='r', verbose=0,
+ prewarm=False, unlink_on_gc_collect=True, **kwargs):
+ """Construct a pair of memmapping reducer linked to a tmpdir.
+
+ This function manage the creation and the clean up of the temporary folders
+ underlying the memory maps and should be use to get the reducers necessary
+ to construct joblib pool or executor.
+ """
+ if forward_reducers is None:
+ forward_reducers = dict()
+ if backward_reducers is None:
+ backward_reducers = dict()
+
+ if np is not None:
+ # Register smart numpy.ndarray reducers that detects memmap backed
+ # arrays and that is also able to dump to memmap large in-memory
+ # arrays over the max_nbytes threshold
+ forward_reduce_ndarray = ArrayMemmapForwardReducer(
+ max_nbytes, temp_folder_resolver, mmap_mode, unlink_on_gc_collect,
+ verbose, prewarm=prewarm)
+ forward_reducers[np.ndarray] = forward_reduce_ndarray
+ forward_reducers[np.memmap] = forward_reduce_ndarray
+
+ # Communication from child process to the parent process always
+ # pickles in-memory numpy.ndarray without dumping them as memmap
+ # to avoid confusing the caller and make it tricky to collect the
+ # temporary folder
+ backward_reducers[np.ndarray] = reduce_array_memmap_backward
+ backward_reducers[np.memmap] = reduce_array_memmap_backward
+
+ return forward_reducers, backward_reducers
+
+
+class TemporaryResourcesManager(object):
+ """Stateful object able to manage temporary folder and pickles
+
+ It exposes:
+ - a per-context folder name resolving API that memmap-based reducers will
+ rely on to know where to pickle the temporary memmaps
+ - a temporary file/folder management API that internally uses the
+ resource_tracker.
+ """
+
+ def __init__(self, temp_folder_root=None, context_id=None):
+ self._current_temp_folder = None
+ self._temp_folder_root = temp_folder_root
+ self._use_shared_mem = None
+ self._cached_temp_folders = dict()
+ self._id = uuid4().hex
+ self._finalizers = {}
+ if context_id is None:
+ # It would be safer to not assign a default context id (less silent
+ # bugs), but doing this while maintaining backward compatibility
+ # with the previous, context-unaware version get_memmaping_executor
+ # exposes exposes too many low-level details.
+ context_id = uuid4().hex
+ self.set_current_context(context_id)
+
+ def set_current_context(self, context_id):
+ self._current_context_id = context_id
+ self.register_new_context(context_id)
+
+ def register_new_context(self, context_id):
+ # Prepare a sub-folder name specific to a context (usually a unique id
+ # generated by each instance of the Parallel class). Do not create in
+ # advance to spare FS write access if no array is to be dumped).
+ if context_id in self._cached_temp_folders:
+ return
+ else:
+ # During its lifecycle, one Parallel object can have several
+ # executors associated to it (for instance, if a loky worker raises
+ # an exception, joblib shutdowns the executor and instantly
+ # recreates a new one before raising the error - see
+ # ``ensure_ready``. Because we don't want two executors tied to
+ # the same Parallel object (and thus the same context id) to
+ # register/use/delete the same folder, we also add an id specific
+ # to the current Manager (and thus specific to its associated
+ # executor) to the folder name.
+ new_folder_name = (
+ "joblib_memmapping_folder_{}_{}_{}".format(
+ os.getpid(), self._id, context_id)
+ )
+ new_folder_path, _ = _get_temp_dir(
+ new_folder_name, self._temp_folder_root
+ )
+ self.register_folder_finalizer(new_folder_path, context_id)
+ self._cached_temp_folders[context_id] = new_folder_path
+
+ def resolve_temp_folder_name(self):
+ """Return a folder name specific to the currently activated context"""
+ return self._cached_temp_folders[self._current_context_id]
+
+ def _unregister_context(self, context_id=None):
+ if context_id is None:
+ for context_id in list(self._cached_temp_folders):
+ self._unregister_context(context_id)
+ else:
+ temp_folder = self._cached_temp_folders[context_id]
+ finalizer = self._finalizers[context_id]
+
+ resource_tracker.unregister(temp_folder, "folder")
+ atexit.unregister(finalizer)
+
+ self._cached_temp_folders.pop(context_id)
+ self._finalizers.pop(context_id)
+
+ # resource management API
+
+ def register_folder_finalizer(self, pool_subfolder, context_id):
+ # Register the garbage collector at program exit in case caller forgets
+ # to call terminate explicitly: note we do not pass any reference to
+ # ensure that this callback won't prevent garbage collection of
+ # parallel instance and related file handler resources such as POSIX
+ # semaphores and pipes
+ pool_module_name = whichmodule(delete_folder, 'delete_folder')
+ resource_tracker.register(pool_subfolder, "folder")
+
+ def _cleanup():
+ # In some cases the Python runtime seems to set delete_folder to
+ # None just before exiting when accessing the delete_folder
+ # function from the closure namespace. So instead we reimport
+ # the delete_folder function explicitly.
+ # https://github.com/joblib/joblib/issues/328
+ # We cannot just use from 'joblib.pool import delete_folder'
+ # because joblib should only use relative imports to allow
+ # easy vendoring.
+ delete_folder = __import__(
+ pool_module_name, fromlist=['delete_folder']).delete_folder
+ try:
+ delete_folder(pool_subfolder, allow_non_empty=True)
+ resource_tracker.unregister(pool_subfolder, "folder")
+ except OSError:
+ warnings.warn("Failed to delete temporary folder: {}"
+ .format(pool_subfolder))
+
+ self._finalizers[context_id] = atexit.register(_cleanup)
+
+ def _unlink_temporary_resources(self, context_id=None):
+ """Unlink temporary resources created by a process-based pool"""
+ if context_id is None:
+ # iterate over a copy of the cache keys because
+ # unlink_temporary_resources further deletes an entry in this
+ # cache
+ for context_id in self._cached_temp_folders.copy():
+ self._unlink_temporary_resources(context_id)
+ else:
+ temp_folder = self._cached_temp_folders[context_id]
+ if os.path.exists(temp_folder):
+ for filename in os.listdir(temp_folder):
+ resource_tracker.maybe_unlink(
+ os.path.join(temp_folder, filename), "file"
+ )
+ self._try_delete_folder(
+ allow_non_empty=False, context_id=context_id
+ )
+
+ def _unregister_temporary_resources(self, context_id=None):
+ """Unregister temporary resources created by a process-based pool"""
+ if context_id is None:
+ for context_id in self._cached_temp_folders:
+ self._unregister_temporary_resources(context_id)
+ else:
+ temp_folder = self._cached_temp_folders[context_id]
+ if os.path.exists(temp_folder):
+ for filename in os.listdir(temp_folder):
+ resource_tracker.unregister(
+ os.path.join(temp_folder, filename), "file"
+ )
+
+ def _try_delete_folder(self, allow_non_empty, context_id=None):
+ if context_id is None:
+ # ditto
+ for context_id in self._cached_temp_folders.copy():
+ self._try_delete_folder(
+ allow_non_empty=allow_non_empty, context_id=context_id
+ )
+ else:
+ temp_folder = self._cached_temp_folders[context_id]
+ try:
+ delete_folder(
+ temp_folder, allow_non_empty=allow_non_empty
+ )
+ # Now that this folder is deleted, we can forget about it
+ self._unregister_context(context_id)
+
+ except OSError:
+ # Temporary folder cannot be deleted right now. No need to
+ # handle it though, as this folder will be cleaned up by an
+ # atexit finalizer registered by the memmapping_reducer.
+ pass
diff --git a/runtime/Lib/site-packages/joblib/_multiprocessing_helpers.py b/runtime/Lib/site-packages/joblib/_multiprocessing_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..bde4bc1905311cdc4cd337e9b72e3b24f50a3ed5
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_multiprocessing_helpers.py
@@ -0,0 +1,53 @@
+"""Helper module to factorize the conditional multiprocessing import logic
+
+We use a distinct module to simplify import statements and avoid introducing
+circular dependencies (for instance for the assert_spawning name).
+"""
+import os
+import warnings
+
+
+# Obtain possible configuration from the environment, assuming 1 (on)
+# by default, upon 0 set to None. Should instructively fail if some non
+# 0/1 value is set.
+mp = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None
+if mp:
+ try:
+ import multiprocessing as mp
+ import _multiprocessing # noqa
+ except ImportError:
+ mp = None
+
+# 2nd stage: validate that locking is available on the system and
+# issue a warning if not
+if mp is not None:
+ try:
+ # try to create a named semaphore using SemLock to make sure they are
+ # available on this platform. We use the low level object
+ # _multiprocessing.SemLock to avoid spawning a resource tracker on
+ # Unix system or changing the default backend.
+ import tempfile
+ from _multiprocessing import SemLock
+
+ _rand = tempfile._RandomNameSequence()
+ for i in range(100):
+ try:
+ name = '/joblib-{}-{}' .format(
+ os.getpid(), next(_rand))
+ _sem = SemLock(0, 0, 1, name=name, unlink=True)
+ del _sem # cleanup
+ break
+ except FileExistsError as e: # pragma: no cover
+ if i >= 99:
+ raise FileExistsError(
+ 'cannot find name for semaphore') from e
+ except (FileExistsError, AttributeError, ImportError, OSError) as e:
+ mp = None
+ warnings.warn('%s. joblib will operate in serial mode' % (e,))
+
+
+# 3rd stage: backward compat for the assert_spawning helper
+if mp is not None:
+ from multiprocessing.context import assert_spawning
+else:
+ assert_spawning = None
diff --git a/runtime/Lib/site-packages/joblib/_parallel_backends.py b/runtime/Lib/site-packages/joblib/_parallel_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6ec537e9777cd43d89cc27daa0949ed93cb6d92
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_parallel_backends.py
@@ -0,0 +1,653 @@
+"""
+Backends for embarrassingly parallel code.
+"""
+
+import gc
+import os
+import warnings
+import threading
+import functools
+import contextlib
+from abc import ABCMeta, abstractmethod
+
+from .my_exceptions import WorkerInterrupt
+from ._multiprocessing_helpers import mp
+
+if mp is not None:
+ from .pool import MemmappingPool
+ from multiprocessing.pool import ThreadPool
+ from .executor import get_memmapping_executor
+
+ # Compat between concurrent.futures and multiprocessing TimeoutError
+ from multiprocessing import TimeoutError
+ from concurrent.futures._base import TimeoutError as CfTimeoutError
+ from .externals.loky import process_executor, cpu_count
+
+
+class ParallelBackendBase(metaclass=ABCMeta):
+ """Helper abc which defines all methods a ParallelBackend must implement"""
+
+ supports_timeout = False
+ supports_inner_max_num_threads = False
+ nesting_level = None
+
+ def __init__(self, nesting_level=None, inner_max_num_threads=None,
+ **kwargs):
+ super().__init__(**kwargs)
+ self.nesting_level = nesting_level
+ self.inner_max_num_threads = inner_max_num_threads
+
+ MAX_NUM_THREADS_VARS = [
+ 'OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
+ 'BLIS_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMBA_NUM_THREADS',
+ 'NUMEXPR_NUM_THREADS',
+ ]
+
+ TBB_ENABLE_IPC_VAR = "ENABLE_IPC"
+
+ @abstractmethod
+ def effective_n_jobs(self, n_jobs):
+ """Determine the number of jobs that can actually run in parallel
+
+ n_jobs is the number of workers requested by the callers. Passing
+ n_jobs=-1 means requesting all available workers for instance matching
+ the number of CPU cores on the worker host(s).
+
+ This method should return a guesstimate of the number of workers that
+ can actually perform work concurrently. The primary use case is to make
+ it possible for the caller to know in how many chunks to slice the
+ work.
+
+ In general working on larger data chunks is more efficient (less
+ scheduling overhead and better use of CPU cache prefetching heuristics)
+ as long as all the workers have enough work to do.
+ """
+
+ @abstractmethod
+ def apply_async(self, func, callback=None):
+ """Schedule a func to be run"""
+
+ def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
+ **backend_args):
+ """Reconfigure the backend and return the number of workers.
+
+ This makes it possible to reuse an existing backend instance for
+ successive independent calls to Parallel with different parameters.
+ """
+ self.parallel = parallel
+ return self.effective_n_jobs(n_jobs)
+
+ def start_call(self):
+ """Call-back method called at the beginning of a Parallel call"""
+
+ def stop_call(self):
+ """Call-back method called at the end of a Parallel call"""
+
+ def terminate(self):
+ """Shutdown the workers and free the shared memory."""
+
+ def compute_batch_size(self):
+ """Determine the optimal batch size"""
+ return 1
+
+ def batch_completed(self, batch_size, duration):
+ """Callback indicate how long it took to run a batch"""
+
+ def get_exceptions(self):
+ """List of exception types to be captured."""
+ return []
+
+ def abort_everything(self, ensure_ready=True):
+ """Abort any running tasks
+
+ This is called when an exception has been raised when executing a tasks
+ and all the remaining tasks will be ignored and can therefore be
+ aborted to spare computation resources.
+
+ If ensure_ready is True, the backend should be left in an operating
+ state as future tasks might be re-submitted via that same backend
+ instance.
+
+ If ensure_ready is False, the implementer of this method can decide
+ to leave the backend in a closed / terminated state as no new task
+ are expected to be submitted to this backend.
+
+ Setting ensure_ready to False is an optimization that can be leveraged
+ when aborting tasks via killing processes from a local process pool
+ managed by the backend it-self: if we expect no new tasks, there is no
+ point in re-creating new workers.
+ """
+ # Does nothing by default: to be overridden in subclasses when
+ # canceling tasks is possible.
+ pass
+
+ def get_nested_backend(self):
+ """Backend instance to be used by nested Parallel calls.
+
+ By default a thread-based backend is used for the first level of
+ nesting. Beyond, switch to sequential backend to avoid spawning too
+ many threads on the host.
+ """
+ nesting_level = getattr(self, 'nesting_level', 0) + 1
+ if nesting_level > 1:
+ return SequentialBackend(nesting_level=nesting_level), None
+ else:
+ return ThreadingBackend(nesting_level=nesting_level), None
+
+ @contextlib.contextmanager
+ def retrieval_context(self):
+ """Context manager to manage an execution context.
+
+ Calls to Parallel.retrieve will be made inside this context.
+
+ By default, this does nothing. It may be useful for subclasses to
+ handle nested parallelism. In particular, it may be required to avoid
+ deadlocks if a backend manages a fixed number of workers, when those
+ workers may be asked to do nested Parallel calls. Without
+ 'retrieval_context' this could lead to deadlock, as all the workers
+ managed by the backend may be "busy" waiting for the nested parallel
+ calls to finish, but the backend has no free workers to execute those
+ tasks.
+ """
+ yield
+
+ def _prepare_worker_env(self, n_jobs):
+ """Return environment variables limiting threadpools in external libs.
+
+ This function return a dict containing environment variables to pass
+ when creating a pool of process. These environment variables limit the
+ number of threads to `n_threads` for OpenMP, MKL, Accelerated and
+ OpenBLAS libraries in the child processes.
+ """
+ explicit_n_threads = self.inner_max_num_threads
+ default_n_threads = str(max(cpu_count() // n_jobs, 1))
+
+ # Set the inner environment variables to self.inner_max_num_threads if
+ # it is given. Else, default to cpu_count // n_jobs unless the variable
+ # is already present in the parent process environment.
+ env = {}
+ for var in self.MAX_NUM_THREADS_VARS:
+ if explicit_n_threads is None:
+ var_value = os.environ.get(var, None)
+ if var_value is None:
+ var_value = default_n_threads
+ else:
+ var_value = str(explicit_n_threads)
+
+ env[var] = var_value
+
+ if self.TBB_ENABLE_IPC_VAR not in os.environ:
+ # To avoid over-subscription when using TBB, let the TBB schedulers
+ # use Inter Process Communication to coordinate:
+ env[self.TBB_ENABLE_IPC_VAR] = "1"
+ return env
+
+ @staticmethod
+ def in_main_thread():
+ return isinstance(threading.current_thread(), threading._MainThread)
+
+
+class SequentialBackend(ParallelBackendBase):
+ """A ParallelBackend which will execute all batches sequentially.
+
+ Does not use/create any threading objects, and hence has minimal
+ overhead. Used when n_jobs == 1.
+ """
+
+ uses_threads = True
+ supports_sharedmem = True
+
+ def effective_n_jobs(self, n_jobs):
+ """Determine the number of jobs which are going to run in parallel"""
+ if n_jobs == 0:
+ raise ValueError('n_jobs == 0 in Parallel has no meaning')
+ return 1
+
+ def apply_async(self, func, callback=None):
+ """Schedule a func to be run"""
+ result = ImmediateResult(func)
+ if callback:
+ callback(result)
+ return result
+
+ def get_nested_backend(self):
+ # import is not top level to avoid cyclic import errors.
+ from .parallel import get_active_backend
+
+ # SequentialBackend should neither change the nesting level, the
+ # default backend or the number of jobs. Just return the current one.
+ return get_active_backend()
+
+
+class PoolManagerMixin(object):
+ """A helper class for managing pool of workers."""
+
+ _pool = None
+
+ def effective_n_jobs(self, n_jobs):
+ """Determine the number of jobs which are going to run in parallel"""
+ if n_jobs == 0:
+ raise ValueError('n_jobs == 0 in Parallel has no meaning')
+ elif mp is None or n_jobs is None:
+ # multiprocessing is not available or disabled, fallback
+ # to sequential mode
+ return 1
+ elif n_jobs < 0:
+ n_jobs = max(cpu_count() + 1 + n_jobs, 1)
+ return n_jobs
+
+ def terminate(self):
+ """Shutdown the process or thread pool"""
+ if self._pool is not None:
+ self._pool.close()
+ self._pool.terminate() # terminate does a join()
+ self._pool = None
+
+ def _get_pool(self):
+ """Used by apply_async to make it possible to implement lazy init"""
+ return self._pool
+
+ def apply_async(self, func, callback=None):
+ """Schedule a func to be run"""
+ return self._get_pool().apply_async(
+ SafeFunction(func), callback=callback)
+
+ def abort_everything(self, ensure_ready=True):
+ """Shutdown the pool and restart a new one with the same parameters"""
+ self.terminate()
+ if ensure_ready:
+ self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel,
+ **self.parallel._backend_args)
+
+
+class AutoBatchingMixin(object):
+ """A helper class for automagically batching jobs."""
+
+ # In seconds, should be big enough to hide multiprocessing dispatching
+ # overhead.
+ # This settings was found by running benchmarks/bench_auto_batching.py
+ # with various parameters on various platforms.
+ MIN_IDEAL_BATCH_DURATION = .2
+
+ # Should not be too high to avoid stragglers: long jobs running alone
+ # on a single worker while other workers have no work to process any more.
+ MAX_IDEAL_BATCH_DURATION = 2
+
+ # Batching counters default values
+ _DEFAULT_EFFECTIVE_BATCH_SIZE = 1
+ _DEFAULT_SMOOTHED_BATCH_DURATION = 0.0
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
+ self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
+
+ def compute_batch_size(self):
+ """Determine the optimal batch size"""
+ old_batch_size = self._effective_batch_size
+ batch_duration = self._smoothed_batch_duration
+ if (batch_duration > 0 and
+ batch_duration < self.MIN_IDEAL_BATCH_DURATION):
+ # The current batch size is too small: the duration of the
+ # processing of a batch of task is not large enough to hide
+ # the scheduling overhead.
+ ideal_batch_size = int(old_batch_size *
+ self.MIN_IDEAL_BATCH_DURATION /
+ batch_duration)
+ # Multiply by two to limit oscilations between min and max.
+ ideal_batch_size *= 2
+
+ # dont increase the batch size too fast to limit huge batch sizes
+ # potentially leading to starving worker
+ batch_size = min(2 * old_batch_size, ideal_batch_size)
+
+ batch_size = max(batch_size, 1)
+
+ self._effective_batch_size = batch_size
+ if self.parallel.verbose >= 10:
+ self.parallel._print(
+ "Batch computation too fast (%.4fs.) "
+ "Setting batch_size=%d.", (batch_duration, batch_size))
+ elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and
+ old_batch_size >= 2):
+ # The current batch size is too big. If we schedule overly long
+ # running batches some CPUs might wait with nothing left to do
+ # while a couple of CPUs a left processing a few long running
+ # batches. Better reduce the batch size a bit to limit the
+ # likelihood of scheduling such stragglers.
+
+ # decrease the batch size quickly to limit potential starving
+ ideal_batch_size = int(
+ old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration
+ )
+ # Multiply by two to limit oscilations between min and max.
+ batch_size = max(2 * ideal_batch_size, 1)
+ self._effective_batch_size = batch_size
+ if self.parallel.verbose >= 10:
+ self.parallel._print(
+ "Batch computation too slow (%.4fs.) "
+ "Setting batch_size=%d.", (batch_duration, batch_size))
+ else:
+ # No batch size adjustment
+ batch_size = old_batch_size
+
+ if batch_size != old_batch_size:
+ # Reset estimation of the smoothed mean batch duration: this
+ # estimate is updated in the multiprocessing apply_async
+ # CallBack as long as the batch_size is constant. Therefore
+ # we need to reset the estimate whenever we re-tune the batch
+ # size.
+ self._smoothed_batch_duration = \
+ self._DEFAULT_SMOOTHED_BATCH_DURATION
+
+ return batch_size
+
+ def batch_completed(self, batch_size, duration):
+ """Callback indicate how long it took to run a batch"""
+ if batch_size == self._effective_batch_size:
+ # Update the smoothed streaming estimate of the duration of a batch
+ # from dispatch to completion
+ old_duration = self._smoothed_batch_duration
+ if old_duration == self._DEFAULT_SMOOTHED_BATCH_DURATION:
+ # First record of duration for this batch size after the last
+ # reset.
+ new_duration = duration
+ else:
+ # Update the exponentially weighted average of the duration of
+ # batch for the current effective size.
+ new_duration = 0.8 * old_duration + 0.2 * duration
+ self._smoothed_batch_duration = new_duration
+
+ def reset_batch_stats(self):
+ """Reset batch statistics to default values.
+
+ This avoids interferences with future jobs.
+ """
+ self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
+ self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
+
+
+class ThreadingBackend(PoolManagerMixin, ParallelBackendBase):
+ """A ParallelBackend which will use a thread pool to execute batches in.
+
+ This is a low-overhead backend but it suffers from the Python Global
+ Interpreter Lock if the called function relies a lot on Python objects.
+ Mostly useful when the execution bottleneck is a compiled extension that
+ explicitly releases the GIL (for instance a Cython loop wrapped in a "with
+ nogil" block or an expensive call to a library such as NumPy).
+
+ The actual thread pool is lazily initialized: the actual thread pool
+ construction is delayed to the first call to apply_async.
+
+ ThreadingBackend is used as the default backend for nested calls.
+ """
+
+ supports_timeout = True
+ uses_threads = True
+ supports_sharedmem = True
+
+ def configure(self, n_jobs=1, parallel=None, **backend_args):
+ """Build a process or thread pool and return the number of workers"""
+ n_jobs = self.effective_n_jobs(n_jobs)
+ if n_jobs == 1:
+ # Avoid unnecessary overhead and use sequential backend instead.
+ raise FallbackToBackend(
+ SequentialBackend(nesting_level=self.nesting_level))
+ self.parallel = parallel
+ self._n_jobs = n_jobs
+ return n_jobs
+
+ def _get_pool(self):
+ """Lazily initialize the thread pool
+
+ The actual pool of worker threads is only initialized at the first
+ call to apply_async.
+ """
+ if self._pool is None:
+ self._pool = ThreadPool(self._n_jobs)
+ return self._pool
+
+
+class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin,
+ ParallelBackendBase):
+ """A ParallelBackend which will use a multiprocessing.Pool.
+
+ Will introduce some communication and memory overhead when exchanging
+ input and output data with the with the worker Python processes.
+ However, does not suffer from the Python Global Interpreter Lock.
+ """
+
+ supports_timeout = True
+
+ def effective_n_jobs(self, n_jobs):
+ """Determine the number of jobs which are going to run in parallel.
+
+ This also checks if we are attempting to create a nested parallel
+ loop.
+ """
+ if mp is None:
+ return 1
+
+ if mp.current_process().daemon:
+ # Daemonic processes cannot have children
+ if n_jobs != 1:
+ if inside_dask_worker():
+ msg = (
+ "Inside a Dask worker with daemon=True, "
+ "setting n_jobs=1.\nPossible work-arounds:\n"
+ "- dask.config.set("
+ "{'distributed.worker.daemon': False})"
+ "- set the environment variable "
+ "DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
+ "before creating your Dask cluster."
+ )
+ else:
+ msg = (
+ 'Multiprocessing-backed parallel loops '
+ 'cannot be nested, setting n_jobs=1'
+ )
+ warnings.warn(msg, stacklevel=3)
+ return 1
+
+ if process_executor._CURRENT_DEPTH > 0:
+ # Mixing loky and multiprocessing in nested loop is not supported
+ if n_jobs != 1:
+ warnings.warn(
+ 'Multiprocessing-backed parallel loops cannot be nested,'
+ ' below loky, setting n_jobs=1',
+ stacklevel=3)
+ return 1
+
+ elif not (self.in_main_thread() or self.nesting_level == 0):
+ # Prevent posix fork inside in non-main posix threads
+ if n_jobs != 1:
+ warnings.warn(
+ 'Multiprocessing-backed parallel loops cannot be nested'
+ ' below threads, setting n_jobs=1',
+ stacklevel=3)
+ return 1
+
+ return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs)
+
+ def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
+ **memmappingpool_args):
+ """Build a process or thread pool and return the number of workers"""
+ n_jobs = self.effective_n_jobs(n_jobs)
+ if n_jobs == 1:
+ raise FallbackToBackend(
+ SequentialBackend(nesting_level=self.nesting_level))
+
+ # Make sure to free as much memory as possible before forking
+ gc.collect()
+ self._pool = MemmappingPool(n_jobs, **memmappingpool_args)
+ self.parallel = parallel
+ return n_jobs
+
+ def terminate(self):
+ """Shutdown the process or thread pool"""
+ super(MultiprocessingBackend, self).terminate()
+ self.reset_batch_stats()
+
+
+class LokyBackend(AutoBatchingMixin, ParallelBackendBase):
+ """Managing pool of workers with loky instead of multiprocessing."""
+
+ supports_timeout = True
+ supports_inner_max_num_threads = True
+
+ def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
+ idle_worker_timeout=300, **memmappingexecutor_args):
+ """Build a process executor and return the number of workers"""
+ n_jobs = self.effective_n_jobs(n_jobs)
+ if n_jobs == 1:
+ raise FallbackToBackend(
+ SequentialBackend(nesting_level=self.nesting_level))
+
+ self._workers = get_memmapping_executor(
+ n_jobs, timeout=idle_worker_timeout,
+ env=self._prepare_worker_env(n_jobs=n_jobs),
+ context_id=parallel._id, **memmappingexecutor_args)
+ self.parallel = parallel
+ return n_jobs
+
+ def effective_n_jobs(self, n_jobs):
+ """Determine the number of jobs which are going to run in parallel"""
+ if n_jobs == 0:
+ raise ValueError('n_jobs == 0 in Parallel has no meaning')
+ elif mp is None or n_jobs is None:
+ # multiprocessing is not available or disabled, fallback
+ # to sequential mode
+ return 1
+ elif mp.current_process().daemon:
+ # Daemonic processes cannot have children
+ if n_jobs != 1:
+ if inside_dask_worker():
+ msg = (
+ "Inside a Dask worker with daemon=True, "
+ "setting n_jobs=1.\nPossible work-arounds:\n"
+ "- dask.config.set("
+ "{'distributed.worker.daemon': False})\n"
+ "- set the environment variable "
+ "DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
+ "before creating your Dask cluster."
+ )
+ else:
+ msg = (
+ 'Loky-backed parallel loops cannot be called in a'
+ ' multiprocessing, setting n_jobs=1'
+ )
+ warnings.warn(msg, stacklevel=3)
+
+ return 1
+ elif not (self.in_main_thread() or self.nesting_level == 0):
+ # Prevent posix fork inside in non-main posix threads
+ if n_jobs != 1:
+ warnings.warn(
+ 'Loky-backed parallel loops cannot be nested below '
+ 'threads, setting n_jobs=1',
+ stacklevel=3)
+ return 1
+ elif n_jobs < 0:
+ n_jobs = max(cpu_count() + 1 + n_jobs, 1)
+ return n_jobs
+
+ def apply_async(self, func, callback=None):
+ """Schedule a func to be run"""
+ future = self._workers.submit(SafeFunction(func))
+ future.get = functools.partial(self.wrap_future_result, future)
+ if callback is not None:
+ future.add_done_callback(callback)
+ return future
+
+ @staticmethod
+ def wrap_future_result(future, timeout=None):
+ """Wrapper for Future.result to implement the same behaviour as
+ AsyncResults.get from multiprocessing."""
+ try:
+ return future.result(timeout=timeout)
+ except CfTimeoutError as e:
+ raise TimeoutError from e
+
+ def terminate(self):
+ if self._workers is not None:
+ # Don't terminate the workers as we want to reuse them in later
+ # calls, but cleanup the temporary resources that the Parallel call
+ # created. This 'hack' requires a private, low-level operation.
+ self._workers._temp_folder_manager._unlink_temporary_resources(
+ context_id=self.parallel._id
+ )
+ self._workers = None
+
+ self.reset_batch_stats()
+
+ def abort_everything(self, ensure_ready=True):
+ """Shutdown the workers and restart a new one with the same parameters
+ """
+ self._workers.terminate(kill_workers=True)
+ self._workers = None
+
+ if ensure_ready:
+ self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel)
+
+
+class ImmediateResult(object):
+ def __init__(self, batch):
+ # Don't delay the application, to avoid keeping the input
+ # arguments in memory
+ self.results = batch()
+
+ def get(self):
+ return self.results
+
+
+class SafeFunction(object):
+ """Wrapper that handles the serialization of exception tracebacks.
+
+ TODO python2_drop: check whether SafeFunction is still needed since we
+ dropped support for Python 2. If not needed anymore it should be
+ deprecated.
+
+ If an exception is triggered when calling the inner function, a copy of
+ the full traceback is captured to make it possible to serialize
+ it so that it can be rendered in a different Python process.
+
+ """
+ def __init__(self, func):
+ self.func = func
+
+ def __call__(self, *args, **kwargs):
+ try:
+ return self.func(*args, **kwargs)
+ except KeyboardInterrupt as e:
+ # We capture the KeyboardInterrupt and reraise it as
+ # something different, as multiprocessing does not
+ # interrupt processing for a KeyboardInterrupt
+ raise WorkerInterrupt() from e
+ except BaseException:
+ # Rely on Python 3 built-in Remote Traceback reporting
+ raise
+
+
+class FallbackToBackend(Exception):
+ """Raised when configuration should fallback to another backend"""
+
+ def __init__(self, backend):
+ self.backend = backend
+
+
+def inside_dask_worker():
+ """Check whether the current function is executed inside a Dask worker.
+ """
+ # This function can not be in joblib._dask because there would be a
+ # circular import:
+ # _dask imports _parallel_backend that imports _dask ...
+ try:
+ from distributed import get_worker
+ except ImportError:
+ return False
+
+ try:
+ get_worker()
+ return True
+ except ValueError:
+ return False
diff --git a/runtime/Lib/site-packages/joblib/_store_backends.py b/runtime/Lib/site-packages/joblib/_store_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..e96f306106a52bfc21fbbc16e85680f0f1d02cd3
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_store_backends.py
@@ -0,0 +1,414 @@
+"""Storage providers backends for Memory caching."""
+
+import re
+import os
+import os.path
+import datetime
+import json
+import shutil
+import warnings
+import collections
+import operator
+import threading
+from abc import ABCMeta, abstractmethod
+
+from .backports import concurrency_safe_rename
+from .disk import mkdirp, memstr_to_bytes, rm_subdirs
+from . import numpy_pickle
+
+CacheItemInfo = collections.namedtuple('CacheItemInfo',
+ 'path size last_access')
+
+
+def concurrency_safe_write(object_to_write, filename, write_func):
+ """Writes an object into a unique file in a concurrency-safe way."""
+ thread_id = id(threading.current_thread())
+ temporary_filename = '{}.thread-{}-pid-{}'.format(
+ filename, thread_id, os.getpid())
+ write_func(object_to_write, temporary_filename)
+
+ return temporary_filename
+
+
+class StoreBackendBase(metaclass=ABCMeta):
+ """Helper Abstract Base Class which defines all methods that
+ a StorageBackend must implement."""
+
+ location = None
+
+ @abstractmethod
+ def _open_item(self, f, mode):
+ """Opens an item on the store and return a file-like object.
+
+ This method is private and only used by the StoreBackendMixin object.
+
+ Parameters
+ ----------
+ f: a file-like object
+ The file-like object where an item is stored and retrieved
+ mode: string, optional
+ the mode in which the file-like object is opened allowed valued are
+ 'rb', 'wb'
+
+ Returns
+ -------
+ a file-like object
+ """
+
+ @abstractmethod
+ def _item_exists(self, location):
+ """Checks if an item location exists in the store.
+
+ This method is private and only used by the StoreBackendMixin object.
+
+ Parameters
+ ----------
+ location: string
+ The location of an item. On a filesystem, this corresponds to the
+ absolute path, including the filename, of a file.
+
+ Returns
+ -------
+ True if the item exists, False otherwise
+ """
+
+ @abstractmethod
+ def _move_item(self, src, dst):
+ """Moves an item from src to dst in the store.
+
+ This method is private and only used by the StoreBackendMixin object.
+
+ Parameters
+ ----------
+ src: string
+ The source location of an item
+ dst: string
+ The destination location of an item
+ """
+
+ @abstractmethod
+ def create_location(self, location):
+ """Creates a location on the store.
+
+ Parameters
+ ----------
+ location: string
+ The location in the store. On a filesystem, this corresponds to a
+ directory.
+ """
+
+ @abstractmethod
+ def clear_location(self, location):
+ """Clears a location on the store.
+
+ Parameters
+ ----------
+ location: string
+ The location in the store. On a filesystem, this corresponds to a
+ directory or a filename absolute path
+ """
+
+ @abstractmethod
+ def get_items(self):
+ """Returns the whole list of items available in the store.
+
+ Returns
+ -------
+ The list of items identified by their ids (e.g filename in a
+ filesystem).
+ """
+
+ @abstractmethod
+ def configure(self, location, verbose=0, backend_options=dict()):
+ """Configures the store.
+
+ Parameters
+ ----------
+ location: string
+ The base location used by the store. On a filesystem, this
+ corresponds to a directory.
+ verbose: int
+ The level of verbosity of the store
+ backend_options: dict
+ Contains a dictionary of named parameters used to configure the
+ store backend.
+ """
+
+
+class StoreBackendMixin(object):
+ """Class providing all logic for managing the store in a generic way.
+
+ The StoreBackend subclass has to implement 3 methods: create_location,
+ clear_location and configure. The StoreBackend also has to provide
+ a private _open_item, _item_exists and _move_item methods. The _open_item
+ method has to have the same signature as the builtin open and return a
+ file-like object.
+ """
+
+ def load_item(self, path, verbose=1, msg=None):
+ """Load an item from the store given its path as a list of
+ strings."""
+ full_path = os.path.join(self.location, *path)
+
+ if verbose > 1:
+ if verbose < 10:
+ print('{0}...'.format(msg))
+ else:
+ print('{0} from {1}'.format(msg, full_path))
+
+ mmap_mode = (None if not hasattr(self, 'mmap_mode')
+ else self.mmap_mode)
+
+ filename = os.path.join(full_path, 'output.pkl')
+ if not self._item_exists(filename):
+ raise KeyError("Non-existing item (may have been "
+ "cleared).\nFile %s does not exist" % filename)
+
+ # file-like object cannot be used when mmap_mode is set
+ if mmap_mode is None:
+ with self._open_item(filename, "rb") as f:
+ item = numpy_pickle.load(f)
+ else:
+ item = numpy_pickle.load(filename, mmap_mode=mmap_mode)
+ return item
+
+ def dump_item(self, path, item, verbose=1):
+ """Dump an item in the store at the path given as a list of
+ strings."""
+ try:
+ item_path = os.path.join(self.location, *path)
+ if not self._item_exists(item_path):
+ self.create_location(item_path)
+ filename = os.path.join(item_path, 'output.pkl')
+ if verbose > 10:
+ print('Persisting in %s' % item_path)
+
+ def write_func(to_write, dest_filename):
+ with self._open_item(dest_filename, "wb") as f:
+ numpy_pickle.dump(to_write, f,
+ compress=self.compress)
+
+ self._concurrency_safe_write(item, filename, write_func)
+ except: # noqa: E722
+ " Race condition in the creation of the directory "
+
+ def clear_item(self, path):
+ """Clear the item at the path, given as a list of strings."""
+ item_path = os.path.join(self.location, *path)
+ if self._item_exists(item_path):
+ self.clear_location(item_path)
+
+ def contains_item(self, path):
+ """Check if there is an item at the path, given as a list of
+ strings"""
+ item_path = os.path.join(self.location, *path)
+ filename = os.path.join(item_path, 'output.pkl')
+
+ return self._item_exists(filename)
+
+ def get_item_info(self, path):
+ """Return information about item."""
+ return {'location': os.path.join(self.location,
+ *path)}
+
+ def get_metadata(self, path):
+ """Return actual metadata of an item."""
+ try:
+ item_path = os.path.join(self.location, *path)
+ filename = os.path.join(item_path, 'metadata.json')
+ with self._open_item(filename, 'rb') as f:
+ return json.loads(f.read().decode('utf-8'))
+ except: # noqa: E722
+ return {}
+
+ def store_metadata(self, path, metadata):
+ """Store metadata of a computation."""
+ try:
+ item_path = os.path.join(self.location, *path)
+ self.create_location(item_path)
+ filename = os.path.join(item_path, 'metadata.json')
+
+ def write_func(to_write, dest_filename):
+ with self._open_item(dest_filename, "wb") as f:
+ f.write(json.dumps(to_write).encode('utf-8'))
+
+ self._concurrency_safe_write(metadata, filename, write_func)
+ except: # noqa: E722
+ pass
+
+ def contains_path(self, path):
+ """Check cached function is available in store."""
+ func_path = os.path.join(self.location, *path)
+ return self.object_exists(func_path)
+
+ def clear_path(self, path):
+ """Clear all items with a common path in the store."""
+ func_path = os.path.join(self.location, *path)
+ if self._item_exists(func_path):
+ self.clear_location(func_path)
+
+ def store_cached_func_code(self, path, func_code=None):
+ """Store the code of the cached function."""
+ func_path = os.path.join(self.location, *path)
+ if not self._item_exists(func_path):
+ self.create_location(func_path)
+
+ if func_code is not None:
+ filename = os.path.join(func_path, "func_code.py")
+ with self._open_item(filename, 'wb') as f:
+ f.write(func_code.encode('utf-8'))
+
+ def get_cached_func_code(self, path):
+ """Store the code of the cached function."""
+ path += ['func_code.py', ]
+ filename = os.path.join(self.location, *path)
+ try:
+ with self._open_item(filename, 'rb') as f:
+ return f.read().decode('utf-8')
+ except: # noqa: E722
+ raise
+
+ def get_cached_func_info(self, path):
+ """Return information related to the cached function if it exists."""
+ return {'location': os.path.join(self.location, *path)}
+
+ def clear(self):
+ """Clear the whole store content."""
+ self.clear_location(self.location)
+
+ def reduce_store_size(self, bytes_limit):
+ """Reduce store size to keep it under the given bytes limit."""
+ items_to_delete = self._get_items_to_delete(bytes_limit)
+
+ for item in items_to_delete:
+ if self.verbose > 10:
+ print('Deleting item {0}'.format(item))
+ try:
+ self.clear_location(item.path)
+ except OSError:
+ # Even with ignore_errors=True shutil.rmtree can raise OSError
+ # with:
+ # [Errno 116] Stale file handle if another process has deleted
+ # the folder already.
+ pass
+
+ def _get_items_to_delete(self, bytes_limit):
+ """Get items to delete to keep the store under a size limit."""
+ if isinstance(bytes_limit, str):
+ bytes_limit = memstr_to_bytes(bytes_limit)
+
+ items = self.get_items()
+ size = sum(item.size for item in items)
+
+ to_delete_size = size - bytes_limit
+ if to_delete_size < 0:
+ return []
+
+ # We want to delete first the cache items that were accessed a
+ # long time ago
+ items.sort(key=operator.attrgetter('last_access'))
+
+ items_to_delete = []
+ size_so_far = 0
+
+ for item in items:
+ if size_so_far > to_delete_size:
+ break
+
+ items_to_delete.append(item)
+ size_so_far += item.size
+
+ return items_to_delete
+
+ def _concurrency_safe_write(self, to_write, filename, write_func):
+ """Writes an object into a file in a concurrency-safe way."""
+ temporary_filename = concurrency_safe_write(to_write,
+ filename, write_func)
+ self._move_item(temporary_filename, filename)
+
+ def __repr__(self):
+ """Printable representation of the store location."""
+ return '{class_name}(location="{location}")'.format(
+ class_name=self.__class__.__name__, location=self.location)
+
+
+class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin):
+ """A StoreBackend used with local or network file systems."""
+
+ _open_item = staticmethod(open)
+ _item_exists = staticmethod(os.path.exists)
+ _move_item = staticmethod(concurrency_safe_rename)
+
+ def clear_location(self, location):
+ """Delete location on store."""
+ if (location == self.location):
+ rm_subdirs(location)
+ else:
+ shutil.rmtree(location, ignore_errors=True)
+
+ def create_location(self, location):
+ """Create object location on store"""
+ mkdirp(location)
+
+ def get_items(self):
+ """Returns the whole list of items available in the store."""
+ items = []
+
+ for dirpath, _, filenames in os.walk(self.location):
+ is_cache_hash_dir = re.match('[a-f0-9]{32}',
+ os.path.basename(dirpath))
+
+ if is_cache_hash_dir:
+ output_filename = os.path.join(dirpath, 'output.pkl')
+ try:
+ last_access = os.path.getatime(output_filename)
+ except OSError:
+ try:
+ last_access = os.path.getatime(dirpath)
+ except OSError:
+ # The directory has already been deleted
+ continue
+
+ last_access = datetime.datetime.fromtimestamp(last_access)
+ try:
+ full_filenames = [os.path.join(dirpath, fn)
+ for fn in filenames]
+ dirsize = sum(os.path.getsize(fn)
+ for fn in full_filenames)
+ except OSError:
+ # Either output_filename or one of the files in
+ # dirpath does not exist any more. We assume this
+ # directory is being cleaned by another process already
+ continue
+
+ items.append(CacheItemInfo(dirpath, dirsize,
+ last_access))
+
+ return items
+
+ def configure(self, location, verbose=1, backend_options=None):
+ """Configure the store backend.
+
+ For this backend, valid store options are 'compress' and 'mmap_mode'
+ """
+ if backend_options is None:
+ backend_options = {}
+
+ # setup location directory
+ self.location = location
+ if not os.path.exists(self.location):
+ mkdirp(self.location)
+
+ # item can be stored compressed for faster I/O
+ self.compress = backend_options.get('compress', False)
+
+ # FileSystemStoreBackend can be used with mmap_mode options under
+ # certain conditions.
+ mmap_mode = backend_options.get('mmap_mode')
+ if self.compress and mmap_mode is not None:
+ warnings.warn('Compressed items cannot be memmapped in a '
+ 'filesystem store. Option will be ignored.',
+ stacklevel=2)
+
+ self.mmap_mode = mmap_mode
+ self.verbose = verbose
diff --git a/runtime/Lib/site-packages/joblib/_utils.py b/runtime/Lib/site-packages/joblib/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dbd4f636669118c9933834940e82a1a4255e97f
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/_utils.py
@@ -0,0 +1,44 @@
+# Adapted from https://stackoverflow.com/a/9558001/2536294
+
+import ast
+import operator as op
+
+# supported operators
+operators = {
+ ast.Add: op.add,
+ ast.Sub: op.sub,
+ ast.Mult: op.mul,
+ ast.Div: op.truediv,
+ ast.FloorDiv: op.floordiv,
+ ast.Mod: op.mod,
+ ast.Pow: op.pow,
+ ast.USub: op.neg,
+}
+
+
+def eval_expr(expr):
+ """
+ >>> eval_expr('2*6')
+ 12
+ >>> eval_expr('2**6')
+ 64
+ >>> eval_expr('1 + 2*3**(4) / (6 + -7)')
+ -161.0
+ """
+ try:
+ return eval_(ast.parse(expr, mode="eval").body)
+ except (TypeError, SyntaxError, KeyError) as e:
+ raise ValueError(
+ f"{expr!r} is not a valid or supported arithmetic expression."
+ ) from e
+
+
+def eval_(node):
+ if isinstance(node, ast.Num): #
+ return node.n
+ elif isinstance(node, ast.BinOp): #
+ return operators[type(node.op)](eval_(node.left), eval_(node.right))
+ elif isinstance(node, ast.UnaryOp): # e.g., -1
+ return operators[type(node.op)](eval_(node.operand))
+ else:
+ raise TypeError(node)
diff --git a/runtime/Lib/site-packages/joblib/backports.py b/runtime/Lib/site-packages/joblib/backports.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9936faae64e496f230ed321e048fa89f0bf9d14
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/backports.py
@@ -0,0 +1,190 @@
+"""
+Backports of fixes for joblib dependencies
+"""
+import os
+import re
+import time
+
+from os.path import basename
+from multiprocessing import util
+
+# Prior to joblib 1.2, joblib used to import LooseVersion from
+# distutils.version. This import had a side-effect with setuptools that was
+# implicitly required in sklearn.show_versions() to work without raising an
+# exception for scikit-learn 1.0 and earlier. This has been fixed in
+# scikit-learn 1.1 (not yet released at the time of writing), see:
+# https://github.com/scikit-learn/scikit-learn/issues/22614
+#
+# To avoid unnecessary disruption for users who might update to joblib 1.2
+# prior to a release of scikit-learn that includes the fix, let's keep on
+# importing distutils here. TODO: Remove this for a future release of joblib,
+# e.g. 6 months after the release of scikit-learn 1.1.
+import distutils # noqa
+
+
+class Version:
+ """Backport from deprecated distutils
+
+ We maintain this backport to avoid introducing a new dependency on
+ `packaging`.
+
+ We might rexplore this choice in the future if all major Python projects
+ introduce a dependency on packaging anyway.
+ """
+
+ def __init__(self, vstring=None):
+ if vstring:
+ self.parse(vstring)
+
+ def __repr__(self):
+ return "%s ('%s')" % (self.__class__.__name__, str(self))
+
+ def __eq__(self, other):
+ c = self._cmp(other)
+ if c is NotImplemented:
+ return c
+ return c == 0
+
+ def __lt__(self, other):
+ c = self._cmp(other)
+ if c is NotImplemented:
+ return c
+ return c < 0
+
+ def __le__(self, other):
+ c = self._cmp(other)
+ if c is NotImplemented:
+ return c
+ return c <= 0
+
+ def __gt__(self, other):
+ c = self._cmp(other)
+ if c is NotImplemented:
+ return c
+ return c > 0
+
+ def __ge__(self, other):
+ c = self._cmp(other)
+ if c is NotImplemented:
+ return c
+ return c >= 0
+
+
+class LooseVersion(Version):
+ """Backport from deprecated distutils
+
+ We maintain this backport to avoid introducing a new dependency on
+ `packaging`.
+
+ We might rexplore this choice in the future if all major Python projects
+ introduce a dependency on packaging anyway.
+ """
+
+ component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
+
+ def __init__(self, vstring=None):
+ if vstring:
+ self.parse(vstring)
+
+ def parse(self, vstring):
+ # I've given up on thinking I can reconstruct the version string
+ # from the parsed tuple -- so I just store the string here for
+ # use by __str__
+ self.vstring = vstring
+ components = [x for x in self.component_re.split(vstring)
+ if x and x != '.']
+ for i, obj in enumerate(components):
+ try:
+ components[i] = int(obj)
+ except ValueError:
+ pass
+
+ self.version = components
+
+ def __str__(self):
+ return self.vstring
+
+ def __repr__(self):
+ return "LooseVersion ('%s')" % str(self)
+
+ def _cmp(self, other):
+ if isinstance(other, str):
+ other = LooseVersion(other)
+ elif not isinstance(other, LooseVersion):
+ return NotImplemented
+
+ if self.version == other.version:
+ return 0
+ if self.version < other.version:
+ return -1
+ if self.version > other.version:
+ return 1
+
+
+try:
+ import numpy as np
+
+ def make_memmap(filename, dtype='uint8', mode='r+', offset=0,
+ shape=None, order='C', unlink_on_gc_collect=False):
+ """Custom memmap constructor compatible with numpy.memmap.
+
+ This function:
+ - is a backport the numpy memmap offset fix (See
+ https://github.com/numpy/numpy/pull/8443 for more details.
+ The numpy fix is available starting numpy 1.13)
+ - adds ``unlink_on_gc_collect``, which specifies explicitly whether
+ the process re-constructing the memmap owns a reference to the
+ underlying file. If set to True, it adds a finalizer to the
+ newly-created memmap that sends a maybe_unlink request for the
+ memmaped file to resource_tracker.
+ """
+ util.debug(
+ "[MEMMAP READ] creating a memmap (shape {}, filename {}, "
+ "pid {})".format(shape, basename(filename), os.getpid())
+ )
+
+ mm = np.memmap(filename, dtype=dtype, mode=mode, offset=offset,
+ shape=shape, order=order)
+ if LooseVersion(np.__version__) < '1.13':
+ mm.offset = offset
+ if unlink_on_gc_collect:
+ from ._memmapping_reducer import add_maybe_unlink_finalizer
+ add_maybe_unlink_finalizer(mm)
+ return mm
+except ImportError:
+ def make_memmap(filename, dtype='uint8', mode='r+', offset=0,
+ shape=None, order='C', unlink_on_gc_collect=False):
+ raise NotImplementedError(
+ "'joblib.backports.make_memmap' should not be used "
+ 'if numpy is not installed.')
+
+
+if os.name == 'nt':
+ # https://github.com/joblib/joblib/issues/540
+ access_denied_errors = (5, 13)
+ from os import replace
+
+ def concurrency_safe_rename(src, dst):
+ """Renames ``src`` into ``dst`` overwriting ``dst`` if it exists.
+
+ On Windows os.replace can yield permission errors if executed by two
+ different processes.
+ """
+ max_sleep_time = 1
+ total_sleep_time = 0
+ sleep_time = 0.001
+ while total_sleep_time < max_sleep_time:
+ try:
+ replace(src, dst)
+ break
+ except Exception as exc:
+ if getattr(exc, 'winerror', None) in access_denied_errors:
+ time.sleep(sleep_time)
+ total_sleep_time += sleep_time
+ sleep_time *= 2
+ else:
+ raise
+ else:
+ raise
+else:
+ from os import replace as concurrency_safe_rename # noqa
diff --git a/runtime/Lib/site-packages/joblib/compressor.py b/runtime/Lib/site-packages/joblib/compressor.py
new file mode 100644
index 0000000000000000000000000000000000000000..8361d37d4d914d617466c4e0010af7bcc1ae63f7
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/compressor.py
@@ -0,0 +1,570 @@
+"""Classes and functions for managing compressors."""
+
+import io
+import zlib
+from joblib.backports import LooseVersion
+
+try:
+ from threading import RLock
+except ImportError:
+ from dummy_threading import RLock
+
+try:
+ import bz2
+except ImportError:
+ bz2 = None
+
+try:
+ import lz4
+ from lz4.frame import LZ4FrameFile
+except ImportError:
+ lz4 = None
+
+try:
+ import lzma
+except ImportError:
+ lzma = None
+
+
+LZ4_NOT_INSTALLED_ERROR = ('LZ4 is not installed. Install it with pip: '
+ 'https://python-lz4.readthedocs.io/')
+
+# Registered compressors
+_COMPRESSORS = {}
+
+# Magic numbers of supported compression file formats.
+_ZFILE_PREFIX = b'ZF' # used with pickle files created before 0.9.3.
+_ZLIB_PREFIX = b'\x78'
+_GZIP_PREFIX = b'\x1f\x8b'
+_BZ2_PREFIX = b'BZ'
+_XZ_PREFIX = b'\xfd\x37\x7a\x58\x5a'
+_LZMA_PREFIX = b'\x5d\x00'
+_LZ4_PREFIX = b'\x04\x22\x4D\x18'
+
+
+def register_compressor(compressor_name, compressor,
+ force=False):
+ """Register a new compressor.
+
+ Parameters
+ -----------
+ compressor_name: str.
+ The name of the compressor.
+ compressor: CompressorWrapper
+ An instance of a 'CompressorWrapper'.
+ """
+ global _COMPRESSORS
+ if not isinstance(compressor_name, str):
+ raise ValueError("Compressor name should be a string, "
+ "'{}' given.".format(compressor_name))
+
+ if not isinstance(compressor, CompressorWrapper):
+ raise ValueError("Compressor should implement the CompressorWrapper "
+ "interface, '{}' given.".format(compressor))
+
+ if (compressor.fileobj_factory is not None and
+ (not hasattr(compressor.fileobj_factory, 'read') or
+ not hasattr(compressor.fileobj_factory, 'write') or
+ not hasattr(compressor.fileobj_factory, 'seek') or
+ not hasattr(compressor.fileobj_factory, 'tell'))):
+ raise ValueError("Compressor 'fileobj_factory' attribute should "
+ "implement the file object interface, '{}' given."
+ .format(compressor.fileobj_factory))
+
+ if compressor_name in _COMPRESSORS and not force:
+ raise ValueError("Compressor '{}' already registered."
+ .format(compressor_name))
+
+ _COMPRESSORS[compressor_name] = compressor
+
+
+class CompressorWrapper():
+ """A wrapper around a compressor file object.
+
+ Attributes
+ ----------
+ obj: a file-like object
+ The object must implement the buffer interface and will be used
+ internally to compress/decompress the data.
+ prefix: bytestring
+ A bytestring corresponding to the magic number that identifies the
+ file format associated to the compressor.
+ extension: str
+ The file extension used to automatically select this compressor during
+ a dump to a file.
+ """
+
+ def __init__(self, obj, prefix=b'', extension=''):
+ self.fileobj_factory = obj
+ self.prefix = prefix
+ self.extension = extension
+
+ def compressor_file(self, fileobj, compresslevel=None):
+ """Returns an instance of a compressor file object."""
+ if compresslevel is None:
+ return self.fileobj_factory(fileobj, 'wb')
+ else:
+ return self.fileobj_factory(fileobj, 'wb',
+ compresslevel=compresslevel)
+
+ def decompressor_file(self, fileobj):
+ """Returns an instance of a decompressor file object."""
+ return self.fileobj_factory(fileobj, 'rb')
+
+
+class BZ2CompressorWrapper(CompressorWrapper):
+
+ prefix = _BZ2_PREFIX
+ extension = '.bz2'
+
+ def __init__(self):
+ if bz2 is not None:
+ self.fileobj_factory = bz2.BZ2File
+ else:
+ self.fileobj_factory = None
+
+ def _check_versions(self):
+ if bz2 is None:
+ raise ValueError('bz2 module is not compiled on your python '
+ 'standard library.')
+
+ def compressor_file(self, fileobj, compresslevel=None):
+ """Returns an instance of a compressor file object."""
+ self._check_versions()
+ if compresslevel is None:
+ return self.fileobj_factory(fileobj, 'wb')
+ else:
+ return self.fileobj_factory(fileobj, 'wb',
+ compresslevel=compresslevel)
+
+ def decompressor_file(self, fileobj):
+ """Returns an instance of a decompressor file object."""
+ self._check_versions()
+ fileobj = self.fileobj_factory(fileobj, 'rb')
+ return fileobj
+
+
+class LZMACompressorWrapper(CompressorWrapper):
+
+ prefix = _LZMA_PREFIX
+ extension = '.lzma'
+ _lzma_format_name = 'FORMAT_ALONE'
+
+ def __init__(self):
+ if lzma is not None:
+ self.fileobj_factory = lzma.LZMAFile
+ self._lzma_format = getattr(lzma, self._lzma_format_name)
+ else:
+ self.fileobj_factory = None
+
+ def _check_versions(self):
+ if lzma is None:
+ raise ValueError('lzma module is not compiled on your python '
+ 'standard library.')
+
+ def compressor_file(self, fileobj, compresslevel=None):
+ """Returns an instance of a compressor file object."""
+ if compresslevel is None:
+ return self.fileobj_factory(fileobj, 'wb',
+ format=self._lzma_format)
+ else:
+ return self.fileobj_factory(fileobj, 'wb',
+ format=self._lzma_format,
+ preset=compresslevel)
+
+ def decompressor_file(self, fileobj):
+ """Returns an instance of a decompressor file object."""
+ return lzma.LZMAFile(fileobj, 'rb')
+
+
+class XZCompressorWrapper(LZMACompressorWrapper):
+
+ prefix = _XZ_PREFIX
+ extension = '.xz'
+ _lzma_format_name = 'FORMAT_XZ'
+
+
+class LZ4CompressorWrapper(CompressorWrapper):
+
+ prefix = _LZ4_PREFIX
+ extension = '.lz4'
+
+ def __init__(self):
+ if lz4 is not None:
+ self.fileobj_factory = LZ4FrameFile
+ else:
+ self.fileobj_factory = None
+
+ def _check_versions(self):
+ if lz4 is None:
+ raise ValueError(LZ4_NOT_INSTALLED_ERROR)
+ lz4_version = lz4.__version__
+ if lz4_version.startswith("v"):
+ lz4_version = lz4_version[1:]
+ if LooseVersion(lz4_version) < LooseVersion('0.19'):
+ raise ValueError(LZ4_NOT_INSTALLED_ERROR)
+
+ def compressor_file(self, fileobj, compresslevel=None):
+ """Returns an instance of a compressor file object."""
+ self._check_versions()
+ if compresslevel is None:
+ return self.fileobj_factory(fileobj, 'wb')
+ else:
+ return self.fileobj_factory(fileobj, 'wb',
+ compression_level=compresslevel)
+
+ def decompressor_file(self, fileobj):
+ """Returns an instance of a decompressor file object."""
+ self._check_versions()
+ return self.fileobj_factory(fileobj, 'rb')
+
+
+###############################################################################
+# base file compression/decompression object definition
+_MODE_CLOSED = 0
+_MODE_READ = 1
+_MODE_READ_EOF = 2
+_MODE_WRITE = 3
+_BUFFER_SIZE = 8192
+
+
+class BinaryZlibFile(io.BufferedIOBase):
+ """A file object providing transparent zlib (de)compression.
+
+ TODO python2_drop: is it still needed since we dropped Python 2 support A
+ BinaryZlibFile can act as a wrapper for an existing file object, or refer
+ directly to a named file on disk.
+
+ Note that BinaryZlibFile provides only a *binary* file interface: data read
+ is returned as bytes, and data to be written should be given as bytes.
+
+ This object is an adaptation of the BZ2File object and is compatible with
+ versions of python >= 2.7.
+
+ If filename is a str or bytes object, it gives the name
+ of the file to be opened. Otherwise, it should be a file object,
+ which will be used to read or write the compressed data.
+
+ mode can be 'rb' for reading (default) or 'wb' for (over)writing
+
+ If mode is 'wb', compresslevel can be a number between 1
+ and 9 specifying the level of compression: 1 produces the least
+ compression, and 9 produces the most compression. 3 is the default.
+ """
+
+ wbits = zlib.MAX_WBITS
+
+ def __init__(self, filename, mode="rb", compresslevel=3):
+ # This lock must be recursive, so that BufferedIOBase's
+ # readline(), readlines() and writelines() don't deadlock.
+ self._lock = RLock()
+ self._fp = None
+ self._closefp = False
+ self._mode = _MODE_CLOSED
+ self._pos = 0
+ self._size = -1
+ self.compresslevel = compresslevel
+
+ if not isinstance(compresslevel, int) or not (1 <= compresslevel <= 9):
+ raise ValueError("'compresslevel' must be an integer "
+ "between 1 and 9. You provided 'compresslevel={}'"
+ .format(compresslevel))
+
+ if mode == "rb":
+ self._mode = _MODE_READ
+ self._decompressor = zlib.decompressobj(self.wbits)
+ self._buffer = b""
+ self._buffer_offset = 0
+ elif mode == "wb":
+ self._mode = _MODE_WRITE
+ self._compressor = zlib.compressobj(self.compresslevel,
+ zlib.DEFLATED, self.wbits,
+ zlib.DEF_MEM_LEVEL, 0)
+ else:
+ raise ValueError("Invalid mode: %r" % (mode,))
+
+ if isinstance(filename, str):
+ self._fp = io.open(filename, mode)
+ self._closefp = True
+ elif hasattr(filename, "read") or hasattr(filename, "write"):
+ self._fp = filename
+ else:
+ raise TypeError("filename must be a str or bytes object, "
+ "or a file")
+
+ def close(self):
+ """Flush and close the file.
+
+ May be called more than once without error. Once the file is
+ closed, any other operation on it will raise a ValueError.
+ """
+ with self._lock:
+ if self._mode == _MODE_CLOSED:
+ return
+ try:
+ if self._mode in (_MODE_READ, _MODE_READ_EOF):
+ self._decompressor = None
+ elif self._mode == _MODE_WRITE:
+ self._fp.write(self._compressor.flush())
+ self._compressor = None
+ finally:
+ try:
+ if self._closefp:
+ self._fp.close()
+ finally:
+ self._fp = None
+ self._closefp = False
+ self._mode = _MODE_CLOSED
+ self._buffer = b""
+ self._buffer_offset = 0
+
+ @property
+ def closed(self):
+ """True if this file is closed."""
+ return self._mode == _MODE_CLOSED
+
+ def fileno(self):
+ """Return the file descriptor for the underlying file."""
+ self._check_not_closed()
+ return self._fp.fileno()
+
+ def seekable(self):
+ """Return whether the file supports seeking."""
+ return self.readable() and self._fp.seekable()
+
+ def readable(self):
+ """Return whether the file was opened for reading."""
+ self._check_not_closed()
+ return self._mode in (_MODE_READ, _MODE_READ_EOF)
+
+ def writable(self):
+ """Return whether the file was opened for writing."""
+ self._check_not_closed()
+ return self._mode == _MODE_WRITE
+
+ # Mode-checking helper functions.
+
+ def _check_not_closed(self):
+ if self.closed:
+ fname = getattr(self._fp, 'name', None)
+ msg = "I/O operation on closed file"
+ if fname is not None:
+ msg += " {}".format(fname)
+ msg += "."
+ raise ValueError(msg)
+
+ def _check_can_read(self):
+ if self._mode not in (_MODE_READ, _MODE_READ_EOF):
+ self._check_not_closed()
+ raise io.UnsupportedOperation("File not open for reading")
+
+ def _check_can_write(self):
+ if self._mode != _MODE_WRITE:
+ self._check_not_closed()
+ raise io.UnsupportedOperation("File not open for writing")
+
+ def _check_can_seek(self):
+ if self._mode not in (_MODE_READ, _MODE_READ_EOF):
+ self._check_not_closed()
+ raise io.UnsupportedOperation("Seeking is only supported "
+ "on files open for reading")
+ if not self._fp.seekable():
+ raise io.UnsupportedOperation("The underlying file object "
+ "does not support seeking")
+
+ # Fill the readahead buffer if it is empty. Returns False on EOF.
+ def _fill_buffer(self):
+ if self._mode == _MODE_READ_EOF:
+ return False
+ # Depending on the input data, our call to the decompressor may not
+ # return any data. In this case, try again after reading another block.
+ while self._buffer_offset == len(self._buffer):
+ try:
+ rawblock = (self._decompressor.unused_data or
+ self._fp.read(_BUFFER_SIZE))
+ if not rawblock:
+ raise EOFError
+ except EOFError:
+ # End-of-stream marker and end of file. We're good.
+ self._mode = _MODE_READ_EOF
+ self._size = self._pos
+ return False
+ else:
+ self._buffer = self._decompressor.decompress(rawblock)
+ self._buffer_offset = 0
+ return True
+
+ # Read data until EOF.
+ # If return_data is false, consume the data without returning it.
+ def _read_all(self, return_data=True):
+ # The loop assumes that _buffer_offset is 0. Ensure that this is true.
+ self._buffer = self._buffer[self._buffer_offset:]
+ self._buffer_offset = 0
+
+ blocks = []
+ while self._fill_buffer():
+ if return_data:
+ blocks.append(self._buffer)
+ self._pos += len(self._buffer)
+ self._buffer = b""
+ if return_data:
+ return b"".join(blocks)
+
+ # Read a block of up to n bytes.
+ # If return_data is false, consume the data without returning it.
+ def _read_block(self, n_bytes, return_data=True):
+ # If we have enough data buffered, return immediately.
+ end = self._buffer_offset + n_bytes
+ if end <= len(self._buffer):
+ data = self._buffer[self._buffer_offset: end]
+ self._buffer_offset = end
+ self._pos += len(data)
+ return data if return_data else None
+
+ # The loop assumes that _buffer_offset is 0. Ensure that this is true.
+ self._buffer = self._buffer[self._buffer_offset:]
+ self._buffer_offset = 0
+
+ blocks = []
+ while n_bytes > 0 and self._fill_buffer():
+ if n_bytes < len(self._buffer):
+ data = self._buffer[:n_bytes]
+ self._buffer_offset = n_bytes
+ else:
+ data = self._buffer
+ self._buffer = b""
+ if return_data:
+ blocks.append(data)
+ self._pos += len(data)
+ n_bytes -= len(data)
+ if return_data:
+ return b"".join(blocks)
+
+ def read(self, size=-1):
+ """Read up to size uncompressed bytes from the file.
+
+ If size is negative or omitted, read until EOF is reached.
+ Returns b'' if the file is already at EOF.
+ """
+ with self._lock:
+ self._check_can_read()
+ if size == 0:
+ return b""
+ elif size < 0:
+ return self._read_all()
+ else:
+ return self._read_block(size)
+
+ def readinto(self, b):
+ """Read up to len(b) bytes into b.
+
+ Returns the number of bytes read (0 for EOF).
+ """
+ with self._lock:
+ return io.BufferedIOBase.readinto(self, b)
+
+ def write(self, data):
+ """Write a byte string to the file.
+
+ Returns the number of uncompressed bytes written, which is
+ always len(data). Note that due to buffering, the file on disk
+ may not reflect the data written until close() is called.
+ """
+ with self._lock:
+ self._check_can_write()
+ # Convert data type if called by io.BufferedWriter.
+ if isinstance(data, memoryview):
+ data = data.tobytes()
+
+ compressed = self._compressor.compress(data)
+ self._fp.write(compressed)
+ self._pos += len(data)
+ return len(data)
+
+ # Rewind the file to the beginning of the data stream.
+ def _rewind(self):
+ self._fp.seek(0, 0)
+ self._mode = _MODE_READ
+ self._pos = 0
+ self._decompressor = zlib.decompressobj(self.wbits)
+ self._buffer = b""
+ self._buffer_offset = 0
+
+ def seek(self, offset, whence=0):
+ """Change the file position.
+
+ The new position is specified by offset, relative to the
+ position indicated by whence. Values for whence are:
+
+ 0: start of stream (default); offset must not be negative
+ 1: current stream position
+ 2: end of stream; offset must not be positive
+
+ Returns the new file position.
+
+ Note that seeking is emulated, so depending on the parameters,
+ this operation may be extremely slow.
+ """
+ with self._lock:
+ self._check_can_seek()
+
+ # Recalculate offset as an absolute file position.
+ if whence == 0:
+ pass
+ elif whence == 1:
+ offset = self._pos + offset
+ elif whence == 2:
+ # Seeking relative to EOF - we need to know the file's size.
+ if self._size < 0:
+ self._read_all(return_data=False)
+ offset = self._size + offset
+ else:
+ raise ValueError("Invalid value for whence: %s" % (whence,))
+
+ # Make it so that offset is the number of bytes to skip forward.
+ if offset < self._pos:
+ self._rewind()
+ else:
+ offset -= self._pos
+
+ # Read and discard data until we reach the desired position.
+ self._read_block(offset, return_data=False)
+
+ return self._pos
+
+ def tell(self):
+ """Return the current file position."""
+ with self._lock:
+ self._check_not_closed()
+ return self._pos
+
+
+class ZlibCompressorWrapper(CompressorWrapper):
+
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=BinaryZlibFile,
+ prefix=_ZLIB_PREFIX, extension='.z')
+
+
+class BinaryGzipFile(BinaryZlibFile):
+ """A file object providing transparent gzip (de)compression.
+
+ If filename is a str or bytes object, it gives the name
+ of the file to be opened. Otherwise, it should be a file object,
+ which will be used to read or write the compressed data.
+
+ mode can be 'rb' for reading (default) or 'wb' for (over)writing
+
+ If mode is 'wb', compresslevel can be a number between 1
+ and 9 specifying the level of compression: 1 produces the least
+ compression, and 9 produces the most compression. 3 is the default.
+ """
+
+ wbits = 31 # zlib compressor/decompressor wbits value for gzip format.
+
+
+class GzipCompressorWrapper(CompressorWrapper):
+
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=BinaryGzipFile,
+ prefix=_GZIP_PREFIX, extension='.gz')
diff --git a/runtime/Lib/site-packages/joblib/disk.py b/runtime/Lib/site-packages/joblib/disk.py
new file mode 100644
index 0000000000000000000000000000000000000000..32fbb89f6dc6c9c7df532c5fefa14934f16321f6
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/disk.py
@@ -0,0 +1,136 @@
+"""
+Disk management utilities.
+"""
+
+# Authors: Gael Varoquaux
+# Lars Buitinck
+# Copyright (c) 2010 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+
+import os
+import sys
+import time
+import errno
+import shutil
+
+from multiprocessing import util
+
+
+try:
+ WindowsError
+except NameError:
+ WindowsError = OSError
+
+
+def disk_used(path):
+ """ Return the disk usage in a directory."""
+ size = 0
+ for file in os.listdir(path) + ['.']:
+ stat = os.stat(os.path.join(path, file))
+ if hasattr(stat, 'st_blocks'):
+ size += stat.st_blocks * 512
+ else:
+ # on some platform st_blocks is not available (e.g., Windows)
+ # approximate by rounding to next multiple of 512
+ size += (stat.st_size // 512 + 1) * 512
+ # We need to convert to int to avoid having longs on some systems (we
+ # don't want longs to avoid problems we SQLite)
+ return int(size / 1024.)
+
+
+def memstr_to_bytes(text):
+ """ Convert a memory text to its value in bytes.
+ """
+ kilo = 1024
+ units = dict(K=kilo, M=kilo ** 2, G=kilo ** 3)
+ try:
+ size = int(units[text[-1]] * float(text[:-1]))
+ except (KeyError, ValueError) as e:
+ raise ValueError(
+ "Invalid literal for size give: %s (type %s) should be "
+ "alike '10G', '500M', '50K'." % (text, type(text))) from e
+ return size
+
+
+def mkdirp(d):
+ """Ensure directory d exists (like mkdir -p on Unix)
+ No guarantee that the directory is writable.
+ """
+ try:
+ os.makedirs(d)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+
+
+# if a rmtree operation fails in rm_subdirs, wait for this much time (in secs),
+# then retry up to RM_SUBDIRS_N_RETRY times. If it still fails, raise the
+# exception. this mechanism ensures that the sub-process gc have the time to
+# collect and close the memmaps before we fail.
+RM_SUBDIRS_RETRY_TIME = 0.1
+RM_SUBDIRS_N_RETRY = 10
+
+
+def rm_subdirs(path, onerror=None):
+ """Remove all subdirectories in this path.
+
+ The directory indicated by `path` is left in place, and its subdirectories
+ are erased.
+
+ If onerror is set, it is called to handle the error with arguments (func,
+ path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
+ path is the argument to that function that caused it to fail; and
+ exc_info is a tuple returned by sys.exc_info(). If onerror is None,
+ an exception is raised.
+ """
+
+ # NOTE this code is adapted from the one in shutil.rmtree, and is
+ # just as fast
+
+ names = []
+ try:
+ names = os.listdir(path)
+ except os.error:
+ if onerror is not None:
+ onerror(os.listdir, path, sys.exc_info())
+ else:
+ raise
+
+ for name in names:
+ fullname = os.path.join(path, name)
+ delete_folder(fullname, onerror=onerror)
+
+
+def delete_folder(folder_path, onerror=None, allow_non_empty=True):
+ """Utility function to cleanup a temporary folder if it still exists."""
+ if os.path.isdir(folder_path):
+ if onerror is not None:
+ shutil.rmtree(folder_path, False, onerror)
+ else:
+ # allow the rmtree to fail once, wait and re-try.
+ # if the error is raised again, fail
+ err_count = 0
+ while True:
+ files = os.listdir(folder_path)
+ try:
+ if len(files) == 0 or allow_non_empty:
+ shutil.rmtree(
+ folder_path, ignore_errors=False, onerror=None
+ )
+ util.debug(
+ "Successfully deleted {}".format(folder_path))
+ break
+ else:
+ raise OSError(
+ "Expected empty folder {} but got {} "
+ "files.".format(folder_path, len(files))
+ )
+ except (OSError, WindowsError):
+ err_count += 1
+ if err_count > RM_SUBDIRS_N_RETRY:
+ # the folder cannot be deleted right now. It maybe
+ # because some temporary files have not been deleted
+ # yet.
+ raise
+ time.sleep(RM_SUBDIRS_RETRY_TIME)
diff --git a/runtime/Lib/site-packages/joblib/executor.py b/runtime/Lib/site-packages/joblib/executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..9273fedec0a2130f35e2e70da8c3ebddb6fe37f8
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/executor.py
@@ -0,0 +1,120 @@
+"""Utility function to construct a loky.ReusableExecutor with custom pickler.
+
+This module provides efficient ways of working with data stored in
+shared memory with numpy.memmap arrays without inducing any memory
+copy between the parent and child processes.
+"""
+# Author: Thomas Moreau
+# Copyright: 2017, Thomas Moreau
+# License: BSD 3 clause
+
+from ._memmapping_reducer import get_memmapping_reducers
+from ._memmapping_reducer import TemporaryResourcesManager
+from .externals.loky.reusable_executor import _ReusablePoolExecutor
+
+
+_executor_args = None
+
+
+def get_memmapping_executor(n_jobs, **kwargs):
+ return MemmappingExecutor.get_memmapping_executor(n_jobs, **kwargs)
+
+
+class MemmappingExecutor(_ReusablePoolExecutor):
+
+ @classmethod
+ def get_memmapping_executor(cls, n_jobs, timeout=300, initializer=None,
+ initargs=(), env=None, temp_folder=None,
+ context_id=None, **backend_args):
+ """Factory for ReusableExecutor with automatic memmapping for large numpy
+ arrays.
+ """
+ global _executor_args
+ # Check if we can reuse the executor here instead of deferring the test
+ # to loky as the reducers are objects that changes at each call.
+ executor_args = backend_args.copy()
+ executor_args.update(env if env else {})
+ executor_args.update(dict(
+ timeout=timeout, initializer=initializer, initargs=initargs))
+ reuse = _executor_args is None or _executor_args == executor_args
+ _executor_args = executor_args
+
+ manager = TemporaryResourcesManager(temp_folder)
+
+ # reducers access the temporary folder in which to store temporary
+ # pickles through a call to manager.resolve_temp_folder_name. resolving
+ # the folder name dynamically is useful to use different folders across
+ # calls of a same reusable executor
+ job_reducers, result_reducers = get_memmapping_reducers(
+ unlink_on_gc_collect=True,
+ temp_folder_resolver=manager.resolve_temp_folder_name,
+ **backend_args)
+ _executor, executor_is_reused = super().get_reusable_executor(
+ n_jobs, job_reducers=job_reducers, result_reducers=result_reducers,
+ reuse=reuse, timeout=timeout, initializer=initializer,
+ initargs=initargs, env=env
+ )
+
+ if not executor_is_reused:
+ # Only set a _temp_folder_manager for new executors. Reused
+ # executors already have a _temporary_folder_manager that must not
+ # be re-assigned like that because it is referenced in various
+ # places in the reducing machinery of the executor.
+ _executor._temp_folder_manager = manager
+
+ if context_id is not None:
+ # Only register the specified context once we know which manager
+ # the current executor is using, in order to not register an atexit
+ # finalizer twice for the same folder.
+ _executor._temp_folder_manager.register_new_context(context_id)
+
+ return _executor
+
+ def terminate(self, kill_workers=False):
+ self.shutdown(kill_workers=kill_workers)
+ if kill_workers:
+ # When workers are killed in such a brutal manner, they cannot
+ # execute the finalizer of their shared memmaps. The refcount of
+ # those memmaps may be off by an unknown number, so instead of
+ # decref'ing them, we delete the whole temporary folder, and
+ # unregister them. There is no risk of PermissionError at folder
+ # deletion because because at this point, all child processes are
+ # dead, so all references to temporary memmaps are closed.
+
+ # unregister temporary resources from all contexts
+ with self._submit_resize_lock:
+ self._temp_folder_manager._unregister_temporary_resources()
+ self._temp_folder_manager._try_delete_folder(
+ allow_non_empty=True
+ )
+ else:
+ self._temp_folder_manager._unlink_temporary_resources()
+ self._temp_folder_manager._try_delete_folder(allow_non_empty=True)
+
+ @property
+ def _temp_folder(self):
+ # Legacy property in tests. could be removed if we refactored the
+ # memmapping tests. SHOULD ONLY BE USED IN TESTS!
+ # We cache this property because it is called late in the tests - at
+ # this point, all context have been unregistered, and
+ # resolve_temp_folder_name raises an error.
+ if getattr(self, '_cached_temp_folder', None) is not None:
+ return self._cached_temp_folder
+ else:
+ self._cached_temp_folder = self._temp_folder_manager.resolve_temp_folder_name() # noqa
+ return self._cached_temp_folder
+
+
+class _TestingMemmappingExecutor(MemmappingExecutor):
+ """Wrapper around ReusableExecutor to ease memmapping testing with Pool
+ and Executor. This is only for testing purposes.
+
+ """
+ def apply_async(self, func, args):
+ """Schedule a func to be run"""
+ future = self.submit(func, *args)
+ future.get = future.result
+ return future
+
+ def map(self, f, *args):
+ return list(super().map(f, *args))
diff --git a/runtime/Lib/site-packages/joblib/externals/__init__.py b/runtime/Lib/site-packages/joblib/externals/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/runtime/Lib/site-packages/joblib/externals/cloudpickle/__init__.py b/runtime/Lib/site-packages/joblib/externals/cloudpickle/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c802221efa2ba5974367e173379097c2e7215a64
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/cloudpickle/__init__.py
@@ -0,0 +1,8 @@
+from .cloudpickle import * # noqa
+from .cloudpickle_fast import CloudPickler, dumps, dump # noqa
+
+# Conform to the convention used by python serialization libraries, which
+# expose their Pickler subclass at top-level under the "Pickler" name.
+Pickler = CloudPickler
+
+__version__ = '2.2.0'
diff --git a/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle.py b/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..317be69151ac36393a0f919297c2a50786b5e1f0
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle.py
@@ -0,0 +1,948 @@
+"""
+This class is defined to override standard pickle functionality
+
+The goals of it follow:
+-Serialize lambdas and nested functions to compiled byte code
+-Deal with main module correctly
+-Deal with other non-serializable objects
+
+It does not include an unpickler, as standard python unpickling suffices.
+
+This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
+`_.
+
+Copyright (c) 2012, Regents of the University of California.
+Copyright (c) 2009 `PiCloud, Inc. `_.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the University of California, Berkeley nor the
+ names of its contributors may be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""
+
+import builtins
+import dis
+import opcode
+import platform
+import sys
+import types
+import weakref
+import uuid
+import threading
+import typing
+import warnings
+
+from .compat import pickle
+from collections import OrderedDict
+from typing import ClassVar, Generic, Union, Tuple, Callable
+from pickle import _getattribute
+from importlib._bootstrap import _find_spec
+
+try: # pragma: no branch
+ import typing_extensions as _typing_extensions
+ from typing_extensions import Literal, Final
+except ImportError:
+ _typing_extensions = Literal = Final = None
+
+if sys.version_info >= (3, 8):
+ from types import CellType
+else:
+ def f():
+ a = 1
+
+ def g():
+ return a
+ return g
+ CellType = type(f().__closure__[0])
+
+
+# cloudpickle is meant for inter process communication: we expect all
+# communicating processes to run the same Python version hence we favor
+# communication speed over compatibility:
+DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
+
+# Names of modules whose resources should be treated as dynamic.
+_PICKLE_BY_VALUE_MODULES = set()
+
+# Track the provenance of reconstructed dynamic classes to make it possible to
+# reconstruct instances from the matching singleton class definition when
+# appropriate and preserve the usual "isinstance" semantics of Python objects.
+_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
+_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
+_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
+
+PYPY = platform.python_implementation() == "PyPy"
+
+builtin_code_type = None
+if PYPY:
+ # builtin-code objects only exist in pypy
+ builtin_code_type = type(float.__new__.__code__)
+
+_extract_code_globals_cache = weakref.WeakKeyDictionary()
+
+
+def _get_or_create_tracker_id(class_def):
+ with _DYNAMIC_CLASS_TRACKER_LOCK:
+ class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
+ if class_tracker_id is None:
+ class_tracker_id = uuid.uuid4().hex
+ _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
+ _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
+ return class_tracker_id
+
+
+def _lookup_class_or_track(class_tracker_id, class_def):
+ if class_tracker_id is not None:
+ with _DYNAMIC_CLASS_TRACKER_LOCK:
+ class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
+ class_tracker_id, class_def)
+ _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
+ return class_def
+
+
+def register_pickle_by_value(module):
+ """Register a module to make it functions and classes picklable by value.
+
+ By default, functions and classes that are attributes of an importable
+ module are to be pickled by reference, that is relying on re-importing
+ the attribute from the module at load time.
+
+ If `register_pickle_by_value(module)` is called, all its functions and
+ classes are subsequently to be pickled by value, meaning that they can
+ be loaded in Python processes where the module is not importable.
+
+ This is especially useful when developing a module in a distributed
+ execution environment: restarting the client Python process with the new
+ source code is enough: there is no need to re-install the new version
+ of the module on all the worker nodes nor to restart the workers.
+
+ Note: this feature is considered experimental. See the cloudpickle
+ README.md file for more details and limitations.
+ """
+ if not isinstance(module, types.ModuleType):
+ raise ValueError(
+ f"Input should be a module object, got {str(module)} instead"
+ )
+ # In the future, cloudpickle may need a way to access any module registered
+ # for pickling by value in order to introspect relative imports inside
+ # functions pickled by value. (see
+ # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633).
+ # This access can be ensured by checking that module is present in
+ # sys.modules at registering time and assuming that it will still be in
+ # there when accessed during pickling. Another alternative would be to
+ # store a weakref to the module. Even though cloudpickle does not implement
+ # this introspection yet, in order to avoid a possible breaking change
+ # later, we still enforce the presence of module inside sys.modules.
+ if module.__name__ not in sys.modules:
+ raise ValueError(
+ f"{module} was not imported correctly, have you used an "
+ f"`import` statement to access it?"
+ )
+ _PICKLE_BY_VALUE_MODULES.add(module.__name__)
+
+
+def unregister_pickle_by_value(module):
+ """Unregister that the input module should be pickled by value."""
+ if not isinstance(module, types.ModuleType):
+ raise ValueError(
+ f"Input should be a module object, got {str(module)} instead"
+ )
+ if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
+ raise ValueError(f"{module} is not registered for pickle by value")
+ else:
+ _PICKLE_BY_VALUE_MODULES.remove(module.__name__)
+
+
+def list_registry_pickle_by_value():
+ return _PICKLE_BY_VALUE_MODULES.copy()
+
+
+def _is_registered_pickle_by_value(module):
+ module_name = module.__name__
+ if module_name in _PICKLE_BY_VALUE_MODULES:
+ return True
+ while True:
+ parent_name = module_name.rsplit(".", 1)[0]
+ if parent_name == module_name:
+ break
+ if parent_name in _PICKLE_BY_VALUE_MODULES:
+ return True
+ module_name = parent_name
+ return False
+
+
+def _whichmodule(obj, name):
+ """Find the module an object belongs to.
+
+ This function differs from ``pickle.whichmodule`` in two ways:
+ - it does not mangle the cases where obj's module is __main__ and obj was
+ not found in any module.
+ - Errors arising during module introspection are ignored, as those errors
+ are considered unwanted side effects.
+ """
+ if sys.version_info[:2] < (3, 7) and isinstance(obj, typing.TypeVar): # pragma: no branch # noqa
+ # Workaround bug in old Python versions: prior to Python 3.7,
+ # T.__module__ would always be set to "typing" even when the TypeVar T
+ # would be defined in a different module.
+ if name is not None and getattr(typing, name, None) is obj:
+ # Built-in TypeVar defined in typing such as AnyStr
+ return 'typing'
+ else:
+ # User defined or third-party TypeVar: __module__ attribute is
+ # irrelevant, thus trigger a exhaustive search for obj in all
+ # modules.
+ module_name = None
+ else:
+ module_name = getattr(obj, '__module__', None)
+
+ if module_name is not None:
+ return module_name
+ # Protect the iteration by using a copy of sys.modules against dynamic
+ # modules that trigger imports of other modules upon calls to getattr or
+ # other threads importing at the same time.
+ for module_name, module in sys.modules.copy().items():
+ # Some modules such as coverage can inject non-module objects inside
+ # sys.modules
+ if (
+ module_name == '__main__' or
+ module is None or
+ not isinstance(module, types.ModuleType)
+ ):
+ continue
+ try:
+ if _getattribute(module, name)[0] is obj:
+ return module_name
+ except Exception:
+ pass
+ return None
+
+
+def _should_pickle_by_reference(obj, name=None):
+ """Test whether an function or a class should be pickled by reference
+
+ Pickling by reference means by that the object (typically a function or a
+ class) is an attribute of a module that is assumed to be importable in the
+ target Python environment. Loading will therefore rely on importing the
+ module and then calling `getattr` on it to access the function or class.
+
+ Pickling by reference is the only option to pickle functions and classes
+ in the standard library. In cloudpickle the alternative option is to
+ pickle by value (for instance for interactively or locally defined
+ functions and classes or for attributes of modules that have been
+ explicitly registered to be pickled by value.
+ """
+ if isinstance(obj, types.FunctionType) or issubclass(type(obj), type):
+ module_and_name = _lookup_module_and_qualname(obj, name=name)
+ if module_and_name is None:
+ return False
+ module, name = module_and_name
+ return not _is_registered_pickle_by_value(module)
+
+ elif isinstance(obj, types.ModuleType):
+ # We assume that sys.modules is primarily used as a cache mechanism for
+ # the Python import machinery. Checking if a module has been added in
+ # is sys.modules therefore a cheap and simple heuristic to tell us
+ # whether we can assume that a given module could be imported by name
+ # in another Python process.
+ if _is_registered_pickle_by_value(obj):
+ return False
+ return obj.__name__ in sys.modules
+ else:
+ raise TypeError(
+ "cannot check importability of {} instances".format(
+ type(obj).__name__)
+ )
+
+
+def _lookup_module_and_qualname(obj, name=None):
+ if name is None:
+ name = getattr(obj, '__qualname__', None)
+ if name is None: # pragma: no cover
+ # This used to be needed for Python 2.7 support but is probably not
+ # needed anymore. However we keep the __name__ introspection in case
+ # users of cloudpickle rely on this old behavior for unknown reasons.
+ name = getattr(obj, '__name__', None)
+
+ module_name = _whichmodule(obj, name)
+
+ if module_name is None:
+ # In this case, obj.__module__ is None AND obj was not found in any
+ # imported module. obj is thus treated as dynamic.
+ return None
+
+ if module_name == "__main__":
+ return None
+
+ # Note: if module_name is in sys.modules, the corresponding module is
+ # assumed importable at unpickling time. See #357
+ module = sys.modules.get(module_name, None)
+ if module is None:
+ # The main reason why obj's module would not be imported is that this
+ # module has been dynamically created, using for example
+ # types.ModuleType. The other possibility is that module was removed
+ # from sys.modules after obj was created/imported. But this case is not
+ # supported, as the standard pickle does not support it either.
+ return None
+
+ try:
+ obj2, parent = _getattribute(module, name)
+ except AttributeError:
+ # obj was not found inside the module it points to
+ return None
+ if obj2 is not obj:
+ return None
+ return module, name
+
+
+def _extract_code_globals(co):
+ """
+ Find all globals names read or written to by codeblock co
+ """
+ out_names = _extract_code_globals_cache.get(co)
+ if out_names is None:
+ # We use a dict with None values instead of a set to get a
+ # deterministic order (assuming Python 3.6+) and avoid introducing
+ # non-deterministic pickle bytes as a results.
+ out_names = {name: None for name in _walk_global_ops(co)}
+
+ # Declaring a function inside another one using the "def ..."
+ # syntax generates a constant code object corresponding to the one
+ # of the nested function's As the nested function may itself need
+ # global variables, we need to introspect its code, extract its
+ # globals, (look for code object in it's co_consts attribute..) and
+ # add the result to code_globals
+ if co.co_consts:
+ for const in co.co_consts:
+ if isinstance(const, types.CodeType):
+ out_names.update(_extract_code_globals(const))
+
+ _extract_code_globals_cache[co] = out_names
+
+ return out_names
+
+
+def _find_imported_submodules(code, top_level_dependencies):
+ """
+ Find currently imported submodules used by a function.
+
+ Submodules used by a function need to be detected and referenced for the
+ function to work correctly at depickling time. Because submodules can be
+ referenced as attribute of their parent package (``package.submodule``), we
+ need a special introspection technique that does not rely on GLOBAL-related
+ opcodes to find references of them in a code object.
+
+ Example:
+ ```
+ import concurrent.futures
+ import cloudpickle
+ def func():
+ x = concurrent.futures.ThreadPoolExecutor
+ if __name__ == '__main__':
+ cloudpickle.dumps(func)
+ ```
+ The globals extracted by cloudpickle in the function's state include the
+ concurrent package, but not its submodule (here, concurrent.futures), which
+ is the module used by func. Find_imported_submodules will detect the usage
+ of concurrent.futures. Saving this module alongside with func will ensure
+ that calling func once depickled does not fail due to concurrent.futures
+ not being imported
+ """
+
+ subimports = []
+ # check if any known dependency is an imported package
+ for x in top_level_dependencies:
+ if (isinstance(x, types.ModuleType) and
+ hasattr(x, '__package__') and x.__package__):
+ # check if the package has any currently loaded sub-imports
+ prefix = x.__name__ + '.'
+ # A concurrent thread could mutate sys.modules,
+ # make sure we iterate over a copy to avoid exceptions
+ for name in list(sys.modules):
+ # Older versions of pytest will add a "None" module to
+ # sys.modules.
+ if name is not None and name.startswith(prefix):
+ # check whether the function can address the sub-module
+ tokens = set(name[len(prefix):].split('.'))
+ if not tokens - set(code.co_names):
+ subimports.append(sys.modules[name])
+ return subimports
+
+
+def cell_set(cell, value):
+ """Set the value of a closure cell.
+
+ The point of this function is to set the cell_contents attribute of a cell
+ after its creation. This operation is necessary in case the cell contains a
+ reference to the function the cell belongs to, as when calling the
+ function's constructor
+ ``f = types.FunctionType(code, globals, name, argdefs, closure)``,
+ closure will not be able to contain the yet-to-be-created f.
+
+ In Python3.7, cell_contents is writeable, so setting the contents of a cell
+ can be done simply using
+ >>> cell.cell_contents = value
+
+ In earlier Python3 versions, the cell_contents attribute of a cell is read
+ only, but this limitation can be worked around by leveraging the Python 3
+ ``nonlocal`` keyword.
+
+ In Python2 however, this attribute is read only, and there is no
+ ``nonlocal`` keyword. For this reason, we need to come up with more
+ complicated hacks to set this attribute.
+
+ The chosen approach is to create a function with a STORE_DEREF opcode,
+ which sets the content of a closure variable. Typically:
+
+ >>> def inner(value):
+ ... lambda: cell # the lambda makes cell a closure
+ ... cell = value # cell is a closure, so this triggers a STORE_DEREF
+
+ (Note that in Python2, A STORE_DEREF can never be triggered from an inner
+ function. The function g for example here
+ >>> def f(var):
+ ... def g():
+ ... var += 1
+ ... return g
+
+ will not modify the closure variable ``var```inplace, but instead try to
+ load a local variable var and increment it. As g does not assign the local
+ variable ``var`` any initial value, calling f(1)() will fail at runtime.)
+
+ Our objective is to set the value of a given cell ``cell``. So we need to
+ somewhat reference our ``cell`` object into the ``inner`` function so that
+ this object (and not the smoke cell of the lambda function) gets affected
+ by the STORE_DEREF operation.
+
+ In inner, ``cell`` is referenced as a cell variable (an enclosing variable
+ that is referenced by the inner function). If we create a new function
+ cell_set with the exact same code as ``inner``, but with ``cell`` marked as
+ a free variable instead, the STORE_DEREF will be applied on its closure -
+ ``cell``, which we can specify explicitly during construction! The new
+ cell_set variable thus actually sets the contents of a specified cell!
+
+ Note: we do not make use of the ``nonlocal`` keyword to set the contents of
+ a cell in early python3 versions to limit possible syntax errors in case
+ test and checker libraries decide to parse the whole file.
+ """
+
+ if sys.version_info[:2] >= (3, 7): # pragma: no branch
+ cell.cell_contents = value
+ else:
+ _cell_set = types.FunctionType(
+ _cell_set_template_code, {}, '_cell_set', (), (cell,),)
+ _cell_set(value)
+
+
+def _make_cell_set_template_code():
+ def _cell_set_factory(value):
+ lambda: cell
+ cell = value
+
+ co = _cell_set_factory.__code__
+
+ _cell_set_template_code = types.CodeType(
+ co.co_argcount,
+ co.co_kwonlyargcount, # Python 3 only argument
+ co.co_nlocals,
+ co.co_stacksize,
+ co.co_flags,
+ co.co_code,
+ co.co_consts,
+ co.co_names,
+ co.co_varnames,
+ co.co_filename,
+ co.co_name,
+ co.co_firstlineno,
+ co.co_lnotab,
+ co.co_cellvars, # co_freevars is initialized with co_cellvars
+ (), # co_cellvars is made empty
+ )
+ return _cell_set_template_code
+
+
+if sys.version_info[:2] < (3, 7):
+ _cell_set_template_code = _make_cell_set_template_code()
+
+# relevant opcodes
+STORE_GLOBAL = opcode.opmap['STORE_GLOBAL']
+DELETE_GLOBAL = opcode.opmap['DELETE_GLOBAL']
+LOAD_GLOBAL = opcode.opmap['LOAD_GLOBAL']
+GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL)
+HAVE_ARGUMENT = dis.HAVE_ARGUMENT
+EXTENDED_ARG = dis.EXTENDED_ARG
+
+
+_BUILTIN_TYPE_NAMES = {}
+for k, v in types.__dict__.items():
+ if type(v) is type:
+ _BUILTIN_TYPE_NAMES[v] = k
+
+
+def _builtin_type(name):
+ if name == "ClassType": # pragma: no cover
+ # Backward compat to load pickle files generated with cloudpickle
+ # < 1.3 even if loading pickle files from older versions is not
+ # officially supported.
+ return type
+ return getattr(types, name)
+
+
+def _walk_global_ops(code):
+ """
+ Yield referenced name for all global-referencing instructions in *code*.
+ """
+ for instr in dis.get_instructions(code):
+ op = instr.opcode
+ if op in GLOBAL_OPS:
+ yield instr.argval
+
+
+def _extract_class_dict(cls):
+ """Retrieve a copy of the dict of a class without the inherited methods"""
+ clsdict = dict(cls.__dict__) # copy dict proxy to a dict
+ if len(cls.__bases__) == 1:
+ inherited_dict = cls.__bases__[0].__dict__
+ else:
+ inherited_dict = {}
+ for base in reversed(cls.__bases__):
+ inherited_dict.update(base.__dict__)
+ to_remove = []
+ for name, value in clsdict.items():
+ try:
+ base_value = inherited_dict[name]
+ if value is base_value:
+ to_remove.append(name)
+ except KeyError:
+ pass
+ for name in to_remove:
+ clsdict.pop(name)
+ return clsdict
+
+
+if sys.version_info[:2] < (3, 7): # pragma: no branch
+ def _is_parametrized_type_hint(obj):
+ # This is very cheap but might generate false positives. So try to
+ # narrow it down is good as possible.
+ type_module = getattr(type(obj), '__module__', None)
+ from_typing_extensions = type_module == 'typing_extensions'
+ from_typing = type_module == 'typing'
+
+ # general typing Constructs
+ is_typing = getattr(obj, '__origin__', None) is not None
+
+ # typing_extensions.Literal
+ is_literal = (
+ (getattr(obj, '__values__', None) is not None)
+ and from_typing_extensions
+ )
+
+ # typing_extensions.Final
+ is_final = (
+ (getattr(obj, '__type__', None) is not None)
+ and from_typing_extensions
+ )
+
+ # typing.ClassVar
+ is_classvar = (
+ (getattr(obj, '__type__', None) is not None) and from_typing
+ )
+
+ # typing.Union/Tuple for old Python 3.5
+ is_union = getattr(obj, '__union_params__', None) is not None
+ is_tuple = getattr(obj, '__tuple_params__', None) is not None
+ is_callable = (
+ getattr(obj, '__result__', None) is not None and
+ getattr(obj, '__args__', None) is not None
+ )
+ return any((is_typing, is_literal, is_final, is_classvar, is_union,
+ is_tuple, is_callable))
+
+ def _create_parametrized_type_hint(origin, args):
+ return origin[args]
+else:
+ _is_parametrized_type_hint = None
+ _create_parametrized_type_hint = None
+
+
+def parametrized_type_hint_getinitargs(obj):
+ # The distorted type check sematic for typing construct becomes:
+ # ``type(obj) is type(TypeHint)``, which means "obj is a
+ # parametrized TypeHint"
+ if type(obj) is type(Literal): # pragma: no branch
+ initargs = (Literal, obj.__values__)
+ elif type(obj) is type(Final): # pragma: no branch
+ initargs = (Final, obj.__type__)
+ elif type(obj) is type(ClassVar):
+ initargs = (ClassVar, obj.__type__)
+ elif type(obj) is type(Generic):
+ initargs = (obj.__origin__, obj.__args__)
+ elif type(obj) is type(Union):
+ initargs = (Union, obj.__args__)
+ elif type(obj) is type(Tuple):
+ initargs = (Tuple, obj.__args__)
+ elif type(obj) is type(Callable):
+ (*args, result) = obj.__args__
+ if len(args) == 1 and args[0] is Ellipsis:
+ args = Ellipsis
+ else:
+ args = list(args)
+ initargs = (Callable, (args, result))
+ else: # pragma: no cover
+ raise pickle.PicklingError(
+ f"Cloudpickle Error: Unknown type {type(obj)}"
+ )
+ return initargs
+
+
+# Tornado support
+
+def is_tornado_coroutine(func):
+ """
+ Return whether *func* is a Tornado coroutine function.
+ Running coroutines are not supported.
+ """
+ if 'tornado.gen' not in sys.modules:
+ return False
+ gen = sys.modules['tornado.gen']
+ if not hasattr(gen, "is_coroutine_function"):
+ # Tornado version is too old
+ return False
+ return gen.is_coroutine_function(func)
+
+
+def _rebuild_tornado_coroutine(func):
+ from tornado import gen
+ return gen.coroutine(func)
+
+
+# including pickles unloading functions in this namespace
+load = pickle.load
+loads = pickle.loads
+
+
+def subimport(name):
+ # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is
+ # the name of a submodule, __import__ will return the top-level root module
+ # of this submodule. For instance, __import__('os.path') returns the `os`
+ # module.
+ __import__(name)
+ return sys.modules[name]
+
+
+def dynamic_subimport(name, vars):
+ mod = types.ModuleType(name)
+ mod.__dict__.update(vars)
+ mod.__dict__['__builtins__'] = builtins.__dict__
+ return mod
+
+
+def _gen_ellipsis():
+ return Ellipsis
+
+
+def _gen_not_implemented():
+ return NotImplemented
+
+
+def _get_cell_contents(cell):
+ try:
+ return cell.cell_contents
+ except ValueError:
+ # sentinel used by ``_fill_function`` which will leave the cell empty
+ return _empty_cell_value
+
+
+def instance(cls):
+ """Create a new instance of a class.
+
+ Parameters
+ ----------
+ cls : type
+ The class to create an instance of.
+
+ Returns
+ -------
+ instance : cls
+ A new instance of ``cls``.
+ """
+ return cls()
+
+
+@instance
+class _empty_cell_value:
+ """sentinel for empty closures
+ """
+ @classmethod
+ def __reduce__(cls):
+ return cls.__name__
+
+
+def _fill_function(*args):
+ """Fills in the rest of function data into the skeleton function object
+
+ The skeleton itself is create by _make_skel_func().
+ """
+ if len(args) == 2:
+ func = args[0]
+ state = args[1]
+ elif len(args) == 5:
+ # Backwards compat for cloudpickle v0.4.0, after which the `module`
+ # argument was introduced
+ func = args[0]
+ keys = ['globals', 'defaults', 'dict', 'closure_values']
+ state = dict(zip(keys, args[1:]))
+ elif len(args) == 6:
+ # Backwards compat for cloudpickle v0.4.1, after which the function
+ # state was passed as a dict to the _fill_function it-self.
+ func = args[0]
+ keys = ['globals', 'defaults', 'dict', 'module', 'closure_values']
+ state = dict(zip(keys, args[1:]))
+ else:
+ raise ValueError(f'Unexpected _fill_value arguments: {args!r}')
+
+ # - At pickling time, any dynamic global variable used by func is
+ # serialized by value (in state['globals']).
+ # - At unpickling time, func's __globals__ attribute is initialized by
+ # first retrieving an empty isolated namespace that will be shared
+ # with other functions pickled from the same original module
+ # by the same CloudPickler instance and then updated with the
+ # content of state['globals'] to populate the shared isolated
+ # namespace with all the global variables that are specifically
+ # referenced for this function.
+ func.__globals__.update(state['globals'])
+
+ func.__defaults__ = state['defaults']
+ func.__dict__ = state['dict']
+ if 'annotations' in state:
+ func.__annotations__ = state['annotations']
+ if 'doc' in state:
+ func.__doc__ = state['doc']
+ if 'name' in state:
+ func.__name__ = state['name']
+ if 'module' in state:
+ func.__module__ = state['module']
+ if 'qualname' in state:
+ func.__qualname__ = state['qualname']
+ if 'kwdefaults' in state:
+ func.__kwdefaults__ = state['kwdefaults']
+ # _cloudpickle_subimports is a set of submodules that must be loaded for
+ # the pickled function to work correctly at unpickling time. Now that these
+ # submodules are depickled (hence imported), they can be removed from the
+ # object's state (the object state only served as a reference holder to
+ # these submodules)
+ if '_cloudpickle_submodules' in state:
+ state.pop('_cloudpickle_submodules')
+
+ cells = func.__closure__
+ if cells is not None:
+ for cell, value in zip(cells, state['closure_values']):
+ if value is not _empty_cell_value:
+ cell_set(cell, value)
+
+ return func
+
+
+def _make_function(code, globals, name, argdefs, closure):
+ # Setting __builtins__ in globals is needed for nogil CPython.
+ globals["__builtins__"] = __builtins__
+ return types.FunctionType(code, globals, name, argdefs, closure)
+
+
+def _make_empty_cell():
+ if False:
+ # trick the compiler into creating an empty cell in our lambda
+ cell = None
+ raise AssertionError('this route should not be executed')
+
+ return (lambda: cell).__closure__[0]
+
+
+def _make_cell(value=_empty_cell_value):
+ cell = _make_empty_cell()
+ if value is not _empty_cell_value:
+ cell_set(cell, value)
+ return cell
+
+
+def _make_skel_func(code, cell_count, base_globals=None):
+ """ Creates a skeleton function object that contains just the provided
+ code and the correct number of cells in func_closure. All other
+ func attributes (e.g. func_globals) are empty.
+ """
+ # This function is deprecated and should be removed in cloudpickle 1.7
+ warnings.warn(
+ "A pickle file created using an old (<=1.4.1) version of cloudpickle "
+ "is currently being loaded. This is not supported by cloudpickle and "
+ "will break in cloudpickle 1.7", category=UserWarning
+ )
+ # This is backward-compatibility code: for cloudpickle versions between
+ # 0.5.4 and 0.7, base_globals could be a string or None. base_globals
+ # should now always be a dictionary.
+ if base_globals is None or isinstance(base_globals, str):
+ base_globals = {}
+
+ base_globals['__builtins__'] = __builtins__
+
+ closure = (
+ tuple(_make_empty_cell() for _ in range(cell_count))
+ if cell_count >= 0 else
+ None
+ )
+ return types.FunctionType(code, base_globals, None, None, closure)
+
+
+def _make_skeleton_class(type_constructor, name, bases, type_kwargs,
+ class_tracker_id, extra):
+ """Build dynamic class with an empty __dict__ to be filled once memoized
+
+ If class_tracker_id is not None, try to lookup an existing class definition
+ matching that id. If none is found, track a newly reconstructed class
+ definition under that id so that other instances stemming from the same
+ class id will also reuse this class definition.
+
+ The "extra" variable is meant to be a dict (or None) that can be used for
+ forward compatibility shall the need arise.
+ """
+ skeleton_class = types.new_class(
+ name, bases, {'metaclass': type_constructor},
+ lambda ns: ns.update(type_kwargs)
+ )
+ return _lookup_class_or_track(class_tracker_id, skeleton_class)
+
+
+def _rehydrate_skeleton_class(skeleton_class, class_dict):
+ """Put attributes from `class_dict` back on `skeleton_class`.
+
+ See CloudPickler.save_dynamic_class for more info.
+ """
+ registry = None
+ for attrname, attr in class_dict.items():
+ if attrname == "_abc_impl":
+ registry = attr
+ else:
+ setattr(skeleton_class, attrname, attr)
+ if registry is not None:
+ for subclass in registry:
+ skeleton_class.register(subclass)
+
+ return skeleton_class
+
+
+def _make_skeleton_enum(bases, name, qualname, members, module,
+ class_tracker_id, extra):
+ """Build dynamic enum with an empty __dict__ to be filled once memoized
+
+ The creation of the enum class is inspired by the code of
+ EnumMeta._create_.
+
+ If class_tracker_id is not None, try to lookup an existing enum definition
+ matching that id. If none is found, track a newly reconstructed enum
+ definition under that id so that other instances stemming from the same
+ class id will also reuse this enum definition.
+
+ The "extra" variable is meant to be a dict (or None) that can be used for
+ forward compatibility shall the need arise.
+ """
+ # enums always inherit from their base Enum class at the last position in
+ # the list of base classes:
+ enum_base = bases[-1]
+ metacls = enum_base.__class__
+ classdict = metacls.__prepare__(name, bases)
+
+ for member_name, member_value in members.items():
+ classdict[member_name] = member_value
+ enum_class = metacls.__new__(metacls, name, bases, classdict)
+ enum_class.__module__ = module
+ enum_class.__qualname__ = qualname
+
+ return _lookup_class_or_track(class_tracker_id, enum_class)
+
+
+def _make_typevar(name, bound, constraints, covariant, contravariant,
+ class_tracker_id):
+ tv = typing.TypeVar(
+ name, *constraints, bound=bound,
+ covariant=covariant, contravariant=contravariant
+ )
+ if class_tracker_id is not None:
+ return _lookup_class_or_track(class_tracker_id, tv)
+ else: # pragma: nocover
+ # Only for Python 3.5.3 compat.
+ return tv
+
+
+def _decompose_typevar(obj):
+ return (
+ obj.__name__, obj.__bound__, obj.__constraints__,
+ obj.__covariant__, obj.__contravariant__,
+ _get_or_create_tracker_id(obj),
+ )
+
+
+def _typevar_reduce(obj):
+ # TypeVar instances require the module information hence why we
+ # are not using the _should_pickle_by_reference directly
+ module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
+
+ if module_and_name is None:
+ return (_make_typevar, _decompose_typevar(obj))
+ elif _is_registered_pickle_by_value(module_and_name[0]):
+ return (_make_typevar, _decompose_typevar(obj))
+
+ return (getattr, module_and_name)
+
+
+def _get_bases(typ):
+ if '__orig_bases__' in getattr(typ, '__dict__', {}):
+ # For generic types (see PEP 560)
+ # Note that simply checking `hasattr(typ, '__orig_bases__')` is not
+ # correct. Subclasses of a fully-parameterized generic class does not
+ # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
+ # will return True because it's defined in the base class.
+ bases_attr = '__orig_bases__'
+ else:
+ # For regular class objects
+ bases_attr = '__bases__'
+ return getattr(typ, bases_attr)
+
+
+def _make_dict_keys(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict.fromkeys(obj).keys()
+ else:
+ return dict.fromkeys(obj).keys()
+
+
+def _make_dict_values(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
+ else:
+ return {i: _ for i, _ in enumerate(obj)}.values()
+
+
+def _make_dict_items(obj, is_ordered=False):
+ if is_ordered:
+ return OrderedDict(obj).items()
+ else:
+ return obj.items()
diff --git a/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py b/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..8741dcbdaaa41dda43196e43f219d78442fa189f
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py
@@ -0,0 +1,844 @@
+"""
+New, fast version of the CloudPickler.
+
+This new CloudPickler class can now extend the fast C Pickler instead of the
+previous Python implementation of the Pickler class. Because this functionality
+is only available for Python versions 3.8+, a lot of backward-compatibility
+code is also removed.
+
+Note that the C Pickler subclassing API is CPython-specific. Therefore, some
+guards present in cloudpickle.py that were written to handle PyPy specificities
+are not present in cloudpickle_fast.py
+"""
+import _collections_abc
+import abc
+import copyreg
+import io
+import itertools
+import logging
+import sys
+import struct
+import types
+import weakref
+import typing
+
+from enum import Enum
+from collections import ChainMap, OrderedDict
+
+from .compat import pickle, Pickler
+from .cloudpickle import (
+ _extract_code_globals, _BUILTIN_TYPE_NAMES, DEFAULT_PROTOCOL,
+ _find_imported_submodules, _get_cell_contents, _should_pickle_by_reference,
+ _builtin_type, _get_or_create_tracker_id, _make_skeleton_class,
+ _make_skeleton_enum, _extract_class_dict, dynamic_subimport, subimport,
+ _typevar_reduce, _get_bases, _make_cell, _make_empty_cell, CellType,
+ _is_parametrized_type_hint, PYPY, cell_set,
+ parametrized_type_hint_getinitargs, _create_parametrized_type_hint,
+ builtin_code_type,
+ _make_dict_keys, _make_dict_values, _make_dict_items, _make_function,
+)
+
+
+if pickle.HIGHEST_PROTOCOL >= 5:
+ # Shorthands similar to pickle.dump/pickle.dumps
+
+ def dump(obj, file, protocol=None, buffer_callback=None):
+ """Serialize obj as bytes streamed into file
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python.
+ """
+ CloudPickler(
+ file, protocol=protocol, buffer_callback=buffer_callback
+ ).dump(obj)
+
+ def dumps(obj, protocol=None, buffer_callback=None):
+ """Serialize obj as a string of bytes allocated in memory
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python.
+ """
+ with io.BytesIO() as file:
+ cp = CloudPickler(
+ file, protocol=protocol, buffer_callback=buffer_callback
+ )
+ cp.dump(obj)
+ return file.getvalue()
+
+else:
+ # Shorthands similar to pickle.dump/pickle.dumps
+ def dump(obj, file, protocol=None):
+ """Serialize obj as bytes streamed into file
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python.
+ """
+ CloudPickler(file, protocol=protocol).dump(obj)
+
+ def dumps(obj, protocol=None):
+ """Serialize obj as a string of bytes allocated in memory
+
+ protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
+ pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
+ speed between processes running the same Python version.
+
+ Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
+ compatibility with older versions of Python.
+ """
+ with io.BytesIO() as file:
+ cp = CloudPickler(file, protocol=protocol)
+ cp.dump(obj)
+ return file.getvalue()
+
+
+load, loads = pickle.load, pickle.loads
+
+
+# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
+# -------------------------------------------------
+
+def _class_getnewargs(obj):
+ type_kwargs = {}
+ if "__slots__" in obj.__dict__:
+ type_kwargs["__slots__"] = obj.__slots__
+
+ __dict__ = obj.__dict__.get('__dict__', None)
+ if isinstance(__dict__, property):
+ type_kwargs['__dict__'] = __dict__
+
+ return (type(obj), obj.__name__, _get_bases(obj), type_kwargs,
+ _get_or_create_tracker_id(obj), None)
+
+
+def _enum_getnewargs(obj):
+ members = {e.name: e.value for e in obj}
+ return (obj.__bases__, obj.__name__, obj.__qualname__, members,
+ obj.__module__, _get_or_create_tracker_id(obj), None)
+
+
+# COLLECTION OF OBJECTS RECONSTRUCTORS
+# ------------------------------------
+def _file_reconstructor(retval):
+ return retval
+
+
+# COLLECTION OF OBJECTS STATE GETTERS
+# -----------------------------------
+def _function_getstate(func):
+ # - Put func's dynamic attributes (stored in func.__dict__) in state. These
+ # attributes will be restored at unpickling time using
+ # f.__dict__.update(state)
+ # - Put func's members into slotstate. Such attributes will be restored at
+ # unpickling time by iterating over slotstate and calling setattr(func,
+ # slotname, slotvalue)
+ slotstate = {
+ "__name__": func.__name__,
+ "__qualname__": func.__qualname__,
+ "__annotations__": func.__annotations__,
+ "__kwdefaults__": func.__kwdefaults__,
+ "__defaults__": func.__defaults__,
+ "__module__": func.__module__,
+ "__doc__": func.__doc__,
+ "__closure__": func.__closure__,
+ }
+
+ f_globals_ref = _extract_code_globals(func.__code__)
+ f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in
+ func.__globals__}
+
+ closure_values = (
+ list(map(_get_cell_contents, func.__closure__))
+ if func.__closure__ is not None else ()
+ )
+
+ # Extract currently-imported submodules used by func. Storing these modules
+ # in a smoke _cloudpickle_subimports attribute of the object's state will
+ # trigger the side effect of importing these modules at unpickling time
+ # (which is necessary for func to work correctly once depickled)
+ slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
+ func.__code__, itertools.chain(f_globals.values(), closure_values))
+ slotstate["__globals__"] = f_globals
+
+ state = func.__dict__
+ return state, slotstate
+
+
+def _class_getstate(obj):
+ clsdict = _extract_class_dict(obj)
+ clsdict.pop('__weakref__', None)
+
+ if issubclass(type(obj), abc.ABCMeta):
+ # If obj is an instance of an ABCMeta subclass, don't pickle the
+ # cache/negative caches populated during isinstance/issubclass
+ # checks, but pickle the list of registered subclasses of obj.
+ clsdict.pop('_abc_cache', None)
+ clsdict.pop('_abc_negative_cache', None)
+ clsdict.pop('_abc_negative_cache_version', None)
+ registry = clsdict.pop('_abc_registry', None)
+ if registry is None:
+ # in Python3.7+, the abc caches and registered subclasses of a
+ # class are bundled into the single _abc_impl attribute
+ clsdict.pop('_abc_impl', None)
+ (registry, _, _, _) = abc._get_dump(obj)
+
+ clsdict["_abc_impl"] = [subclass_weakref()
+ for subclass_weakref in registry]
+ else:
+ # In the above if clause, registry is a set of weakrefs -- in
+ # this case, registry is a WeakSet
+ clsdict["_abc_impl"] = [type_ for type_ in registry]
+
+ if "__slots__" in clsdict:
+ # pickle string length optimization: member descriptors of obj are
+ # created automatically from obj's __slots__ attribute, no need to
+ # save them in obj's state
+ if isinstance(obj.__slots__, str):
+ clsdict.pop(obj.__slots__)
+ else:
+ for k in obj.__slots__:
+ clsdict.pop(k, None)
+
+ clsdict.pop('__dict__', None) # unpicklable property object
+
+ return (clsdict, {})
+
+
+def _enum_getstate(obj):
+ clsdict, slotstate = _class_getstate(obj)
+
+ members = {e.name: e.value for e in obj}
+ # Cleanup the clsdict that will be passed to _rehydrate_skeleton_class:
+ # Those attributes are already handled by the metaclass.
+ for attrname in ["_generate_next_value_", "_member_names_",
+ "_member_map_", "_member_type_",
+ "_value2member_map_"]:
+ clsdict.pop(attrname, None)
+ for member in members:
+ clsdict.pop(member)
+ # Special handling of Enum subclasses
+ return clsdict, slotstate
+
+
+# COLLECTIONS OF OBJECTS REDUCERS
+# -------------------------------
+# A reducer is a function taking a single argument (obj), and that returns a
+# tuple with all the necessary data to re-construct obj. Apart from a few
+# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
+# correctly pickle an object.
+# While many built-in objects (Exceptions objects, instances of the "object"
+# class, etc), are shipped with their own built-in reducer (invoked using
+# obj.__reduce__), some do not. The following methods were created to "fill
+# these holes".
+
+def _code_reduce(obj):
+ """codeobject reducer"""
+ # If you are not sure about the order of arguments, take a look at help
+ # of the specific type from types, for example:
+ # >>> from types import CodeType
+ # >>> help(CodeType)
+ if hasattr(obj, "co_exceptiontable"): # pragma: no branch
+ # Python 3.11 and later: there are some new attributes
+ # related to the enhanced exceptions.
+ args = (
+ obj.co_argcount, obj.co_posonlyargcount,
+ obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
+ obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
+ obj.co_varnames, obj.co_filename, obj.co_name, obj.co_qualname,
+ obj.co_firstlineno, obj.co_linetable, obj.co_exceptiontable,
+ obj.co_freevars, obj.co_cellvars,
+ )
+ elif hasattr(obj, "co_linetable"): # pragma: no branch
+ # Python 3.10 and later: obj.co_lnotab is deprecated and constructor
+ # expects obj.co_linetable instead.
+ args = (
+ obj.co_argcount, obj.co_posonlyargcount,
+ obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
+ obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
+ obj.co_varnames, obj.co_filename, obj.co_name,
+ obj.co_firstlineno, obj.co_linetable, obj.co_freevars,
+ obj.co_cellvars
+ )
+ elif hasattr(obj, "co_nmeta"): # pragma: no cover
+ # "nogil" Python: modified attributes from 3.9
+ args = (
+ obj.co_argcount, obj.co_posonlyargcount,
+ obj.co_kwonlyargcount, obj.co_nlocals, obj.co_framesize,
+ obj.co_ndefaultargs, obj.co_nmeta,
+ obj.co_flags, obj.co_code, obj.co_consts,
+ obj.co_varnames, obj.co_filename, obj.co_name,
+ obj.co_firstlineno, obj.co_lnotab, obj.co_exc_handlers,
+ obj.co_jump_table, obj.co_freevars, obj.co_cellvars,
+ obj.co_free2reg, obj.co_cell2reg
+ )
+ elif hasattr(obj, "co_posonlyargcount"):
+ # Backward compat for 3.9 and older
+ args = (
+ obj.co_argcount, obj.co_posonlyargcount,
+ obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
+ obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
+ obj.co_varnames, obj.co_filename, obj.co_name,
+ obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,
+ obj.co_cellvars
+ )
+ else:
+ # Backward compat for even older versions of Python
+ args = (
+ obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals,
+ obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts,
+ obj.co_names, obj.co_varnames, obj.co_filename,
+ obj.co_name, obj.co_firstlineno, obj.co_lnotab,
+ obj.co_freevars, obj.co_cellvars
+ )
+ return types.CodeType, args
+
+
+def _cell_reduce(obj):
+ """Cell (containing values of a function's free variables) reducer"""
+ try:
+ obj.cell_contents
+ except ValueError: # cell is empty
+ return _make_empty_cell, ()
+ else:
+ return _make_cell, (obj.cell_contents, )
+
+
+def _classmethod_reduce(obj):
+ orig_func = obj.__func__
+ return type(obj), (orig_func,)
+
+
+def _file_reduce(obj):
+ """Save a file"""
+ import io
+
+ if not hasattr(obj, "name") or not hasattr(obj, "mode"):
+ raise pickle.PicklingError(
+ "Cannot pickle files that do not map to an actual file"
+ )
+ if obj is sys.stdout:
+ return getattr, (sys, "stdout")
+ if obj is sys.stderr:
+ return getattr, (sys, "stderr")
+ if obj is sys.stdin:
+ raise pickle.PicklingError("Cannot pickle standard input")
+ if obj.closed:
+ raise pickle.PicklingError("Cannot pickle closed files")
+ if hasattr(obj, "isatty") and obj.isatty():
+ raise pickle.PicklingError(
+ "Cannot pickle files that map to tty objects"
+ )
+ if "r" not in obj.mode and "+" not in obj.mode:
+ raise pickle.PicklingError(
+ "Cannot pickle files that are not opened for reading: %s"
+ % obj.mode
+ )
+
+ name = obj.name
+
+ retval = io.StringIO()
+
+ try:
+ # Read the whole file
+ curloc = obj.tell()
+ obj.seek(0)
+ contents = obj.read()
+ obj.seek(curloc)
+ except IOError as e:
+ raise pickle.PicklingError(
+ "Cannot pickle file %s as it cannot be read" % name
+ ) from e
+ retval.write(contents)
+ retval.seek(curloc)
+
+ retval.name = name
+ return _file_reconstructor, (retval,)
+
+
+def _getset_descriptor_reduce(obj):
+ return getattr, (obj.__objclass__, obj.__name__)
+
+
+def _mappingproxy_reduce(obj):
+ return types.MappingProxyType, (dict(obj),)
+
+
+def _memoryview_reduce(obj):
+ return bytes, (obj.tobytes(),)
+
+
+def _module_reduce(obj):
+ if _should_pickle_by_reference(obj):
+ return subimport, (obj.__name__,)
+ else:
+ # Some external libraries can populate the "__builtins__" entry of a
+ # module's `__dict__` with unpicklable objects (see #316). For that
+ # reason, we do not attempt to pickle the "__builtins__" entry, and
+ # restore a default value for it at unpickling time.
+ state = obj.__dict__.copy()
+ state.pop('__builtins__', None)
+ return dynamic_subimport, (obj.__name__, state)
+
+
+def _method_reduce(obj):
+ return (types.MethodType, (obj.__func__, obj.__self__))
+
+
+def _logger_reduce(obj):
+ return logging.getLogger, (obj.name,)
+
+
+def _root_logger_reduce(obj):
+ return logging.getLogger, ()
+
+
+def _property_reduce(obj):
+ return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
+
+
+def _weakset_reduce(obj):
+ return weakref.WeakSet, (list(obj),)
+
+
+def _dynamic_class_reduce(obj):
+ """
+ Save a class that can't be stored as module global.
+
+ This method is used to serialize classes that are defined inside
+ functions, or that otherwise can't be serialized as attribute lookups
+ from global modules.
+ """
+ if Enum is not None and issubclass(obj, Enum):
+ return (
+ _make_skeleton_enum, _enum_getnewargs(obj), _enum_getstate(obj),
+ None, None, _class_setstate
+ )
+ else:
+ return (
+ _make_skeleton_class, _class_getnewargs(obj), _class_getstate(obj),
+ None, None, _class_setstate
+ )
+
+
+def _class_reduce(obj):
+ """Select the reducer depending on the dynamic nature of the class obj"""
+ if obj is type(None): # noqa
+ return type, (None,)
+ elif obj is type(Ellipsis):
+ return type, (Ellipsis,)
+ elif obj is type(NotImplemented):
+ return type, (NotImplemented,)
+ elif obj in _BUILTIN_TYPE_NAMES:
+ return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
+ elif not _should_pickle_by_reference(obj):
+ return _dynamic_class_reduce(obj)
+ return NotImplemented
+
+
+def _dict_keys_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_keys, (list(obj), )
+
+
+def _dict_values_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_values, (list(obj), )
+
+
+def _dict_items_reduce(obj):
+ return _make_dict_items, (dict(obj), )
+
+
+def _odict_keys_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_keys, (list(obj), True)
+
+
+def _odict_values_reduce(obj):
+ # Safer not to ship the full dict as sending the rest might
+ # be unintended and could potentially cause leaking of
+ # sensitive information
+ return _make_dict_values, (list(obj), True)
+
+
+def _odict_items_reduce(obj):
+ return _make_dict_items, (dict(obj), True)
+
+
+# COLLECTIONS OF OBJECTS STATE SETTERS
+# ------------------------------------
+# state setters are called at unpickling time, once the object is created and
+# it has to be updated to how it was at unpickling time.
+
+
+def _function_setstate(obj, state):
+ """Update the state of a dynamic function.
+
+ As __closure__ and __globals__ are readonly attributes of a function, we
+ cannot rely on the native setstate routine of pickle.load_build, that calls
+ setattr on items of the slotstate. Instead, we have to modify them inplace.
+ """
+ state, slotstate = state
+ obj.__dict__.update(state)
+
+ obj_globals = slotstate.pop("__globals__")
+ obj_closure = slotstate.pop("__closure__")
+ # _cloudpickle_subimports is a set of submodules that must be loaded for
+ # the pickled function to work correctly at unpickling time. Now that these
+ # submodules are depickled (hence imported), they can be removed from the
+ # object's state (the object state only served as a reference holder to
+ # these submodules)
+ slotstate.pop("_cloudpickle_submodules")
+
+ obj.__globals__.update(obj_globals)
+ obj.__globals__["__builtins__"] = __builtins__
+
+ if obj_closure is not None:
+ for i, cell in enumerate(obj_closure):
+ try:
+ value = cell.cell_contents
+ except ValueError: # cell is empty
+ continue
+ cell_set(obj.__closure__[i], value)
+
+ for k, v in slotstate.items():
+ setattr(obj, k, v)
+
+
+def _class_setstate(obj, state):
+ state, slotstate = state
+ registry = None
+ for attrname, attr in state.items():
+ if attrname == "_abc_impl":
+ registry = attr
+ else:
+ setattr(obj, attrname, attr)
+ if registry is not None:
+ for subclass in registry:
+ obj.register(subclass)
+
+ return obj
+
+
+class CloudPickler(Pickler):
+ # set of reducers defined and used by cloudpickle (private)
+ _dispatch_table = {}
+ _dispatch_table[classmethod] = _classmethod_reduce
+ _dispatch_table[io.TextIOWrapper] = _file_reduce
+ _dispatch_table[logging.Logger] = _logger_reduce
+ _dispatch_table[logging.RootLogger] = _root_logger_reduce
+ _dispatch_table[memoryview] = _memoryview_reduce
+ _dispatch_table[property] = _property_reduce
+ _dispatch_table[staticmethod] = _classmethod_reduce
+ _dispatch_table[CellType] = _cell_reduce
+ _dispatch_table[types.CodeType] = _code_reduce
+ _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce
+ _dispatch_table[types.ModuleType] = _module_reduce
+ _dispatch_table[types.MethodType] = _method_reduce
+ _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce
+ _dispatch_table[weakref.WeakSet] = _weakset_reduce
+ _dispatch_table[typing.TypeVar] = _typevar_reduce
+ _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce
+ _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce
+ _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce
+ _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce
+ _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce
+ _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce
+ _dispatch_table[abc.abstractmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce
+ _dispatch_table[abc.abstractproperty] = _property_reduce
+
+ dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table)
+
+ # function reducers are defined as instance methods of CloudPickler
+ # objects, as they rely on a CloudPickler attribute (globals_ref)
+ def _dynamic_function_reduce(self, func):
+ """Reduce a function that is not pickleable via attribute lookup."""
+ newargs = self._function_getnewargs(func)
+ state = _function_getstate(func)
+ return (_make_function, newargs, state, None, None,
+ _function_setstate)
+
+ def _function_reduce(self, obj):
+ """Reducer for function objects.
+
+ If obj is a top-level attribute of a file-backed module, this
+ reducer returns NotImplemented, making the CloudPickler fallback to
+ traditional _pickle.Pickler routines to save obj. Otherwise, it reduces
+ obj using a custom cloudpickle reducer designed specifically to handle
+ dynamic functions.
+
+ As opposed to cloudpickle.py, There no special handling for builtin
+ pypy functions because cloudpickle_fast is CPython-specific.
+ """
+ if _should_pickle_by_reference(obj):
+ return NotImplemented
+ else:
+ return self._dynamic_function_reduce(obj)
+
+ def _function_getnewargs(self, func):
+ code = func.__code__
+
+ # base_globals represents the future global namespace of func at
+ # unpickling time. Looking it up and storing it in
+ # CloudpiPickler.globals_ref allow functions sharing the same globals
+ # at pickling time to also share them once unpickled, at one condition:
+ # since globals_ref is an attribute of a CloudPickler instance, and
+ # that a new CloudPickler is created each time pickle.dump or
+ # pickle.dumps is called, functions also need to be saved within the
+ # same invocation of cloudpickle.dump/cloudpickle.dumps (for example:
+ # cloudpickle.dumps([f1, f2])). There is no such limitation when using
+ # CloudPickler.dump, as long as the multiple invocations are bound to
+ # the same CloudPickler.
+ base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
+
+ if base_globals == {}:
+ # Add module attributes used to resolve relative imports
+ # instructions inside func.
+ for k in ["__package__", "__name__", "__path__", "__file__"]:
+ if k in func.__globals__:
+ base_globals[k] = func.__globals__[k]
+
+ # Do not bind the free variables before the function is created to
+ # avoid infinite recursion.
+ if func.__closure__ is None:
+ closure = None
+ else:
+ closure = tuple(
+ _make_empty_cell() for _ in range(len(code.co_freevars)))
+
+ return code, base_globals, None, None, closure
+
+ def dump(self, obj):
+ try:
+ return Pickler.dump(self, obj)
+ except RuntimeError as e:
+ if "recursion" in e.args[0]:
+ msg = (
+ "Could not pickle object as excessively deep recursion "
+ "required."
+ )
+ raise pickle.PicklingError(msg) from e
+ else:
+ raise
+
+ if pickle.HIGHEST_PROTOCOL >= 5:
+ def __init__(self, file, protocol=None, buffer_callback=None):
+ if protocol is None:
+ protocol = DEFAULT_PROTOCOL
+ Pickler.__init__(
+ self, file, protocol=protocol, buffer_callback=buffer_callback
+ )
+ # map functions __globals__ attribute ids, to ensure that functions
+ # sharing the same global namespace at pickling time also share
+ # their global namespace at unpickling time.
+ self.globals_ref = {}
+ self.proto = int(protocol)
+ else:
+ def __init__(self, file, protocol=None):
+ if protocol is None:
+ protocol = DEFAULT_PROTOCOL
+ Pickler.__init__(self, file, protocol=protocol)
+ # map functions __globals__ attribute ids, to ensure that functions
+ # sharing the same global namespace at pickling time also share
+ # their global namespace at unpickling time.
+ self.globals_ref = {}
+ assert hasattr(self, 'proto')
+
+ if pickle.HIGHEST_PROTOCOL >= 5 and not PYPY:
+ # Pickler is the C implementation of the CPython pickler and therefore
+ # we rely on reduce_override method to customize the pickler behavior.
+
+ # `CloudPickler.dispatch` is only left for backward compatibility - note
+ # that when using protocol 5, `CloudPickler.dispatch` is not an
+ # extension of `Pickler.dispatch` dictionary, because CloudPickler
+ # subclasses the C-implemented Pickler, which does not expose a
+ # `dispatch` attribute. Earlier versions of the protocol 5 CloudPickler
+ # used `CloudPickler.dispatch` as a class-level attribute storing all
+ # reducers implemented by cloudpickle, but the attribute name was not a
+ # great choice given the meaning of `CloudPickler.dispatch` when
+ # `CloudPickler` extends the pure-python pickler.
+ dispatch = dispatch_table
+
+ # Implementation of the reducer_override callback, in order to
+ # efficiently serialize dynamic functions and classes by subclassing
+ # the C-implemented Pickler.
+ # TODO: decorrelate reducer_override (which is tied to CPython's
+ # implementation - would it make sense to backport it to pypy? - and
+ # pickle's protocol 5 which is implementation agnostic. Currently, the
+ # availability of both notions coincide on CPython's pickle and the
+ # pickle5 backport, but it may not be the case anymore when pypy
+ # implements protocol 5
+
+ def reducer_override(self, obj):
+ """Type-agnostic reducing callback for function and classes.
+
+ For performance reasons, subclasses of the C _pickle.Pickler class
+ cannot register custom reducers for functions and classes in the
+ dispatch_table. Reducer for such types must instead implemented in
+ the special reducer_override method.
+
+ Note that method will be called for any object except a few
+ builtin-types (int, lists, dicts etc.), which differs from reducers
+ in the Pickler's dispatch_table, each of them being invoked for
+ objects of a specific type only.
+
+ This property comes in handy for classes: although most classes are
+ instances of the ``type`` metaclass, some of them can be instances
+ of other custom metaclasses (such as enum.EnumMeta for example). In
+ particular, the metaclass will likely not be known in advance, and
+ thus cannot be special-cased using an entry in the dispatch_table.
+ reducer_override, among other things, allows us to register a
+ reducer that will be called for any class, independently of its
+ type.
+
+
+ Notes:
+
+ * reducer_override has the priority over dispatch_table-registered
+ reducers.
+ * reducer_override can be used to fix other limitations of
+ cloudpickle for other types that suffered from type-specific
+ reducers, such as Exceptions. See
+ https://github.com/cloudpipe/cloudpickle/issues/248
+ """
+ if sys.version_info[:2] < (3, 7) and _is_parametrized_type_hint(obj): # noqa # pragma: no branch
+ return (
+ _create_parametrized_type_hint,
+ parametrized_type_hint_getinitargs(obj)
+ )
+ t = type(obj)
+ try:
+ is_anyclass = issubclass(t, type)
+ except TypeError: # t is not a class (old Boost; see SF #502085)
+ is_anyclass = False
+
+ if is_anyclass:
+ return _class_reduce(obj)
+ elif isinstance(obj, types.FunctionType):
+ return self._function_reduce(obj)
+ else:
+ # fallback to save_global, including the Pickler's
+ # dispatch_table
+ return NotImplemented
+
+ else:
+ # When reducer_override is not available, hack the pure-Python
+ # Pickler's types.FunctionType and type savers. Note: the type saver
+ # must override Pickler.save_global, because pickle.py contains a
+ # hard-coded call to save_global when pickling meta-classes.
+ dispatch = Pickler.dispatch.copy()
+
+ def _save_reduce_pickle5(self, func, args, state=None, listitems=None,
+ dictitems=None, state_setter=None, obj=None):
+ save = self.save
+ write = self.write
+ self.save_reduce(
+ func, args, state=None, listitems=listitems,
+ dictitems=dictitems, obj=obj
+ )
+ # backport of the Python 3.8 state_setter pickle operations
+ save(state_setter)
+ save(obj) # simple BINGET opcode as obj is already memoized.
+ save(state)
+ write(pickle.TUPLE2)
+ # Trigger a state_setter(obj, state) function call.
+ write(pickle.REDUCE)
+ # The purpose of state_setter is to carry-out an
+ # inplace modification of obj. We do not care about what the
+ # method might return, so its output is eventually removed from
+ # the stack.
+ write(pickle.POP)
+
+ def save_global(self, obj, name=None, pack=struct.pack):
+ """
+ Save a "global".
+
+ The name of this method is somewhat misleading: all types get
+ dispatched here.
+ """
+ if obj is type(None): # noqa
+ return self.save_reduce(type, (None,), obj=obj)
+ elif obj is type(Ellipsis):
+ return self.save_reduce(type, (Ellipsis,), obj=obj)
+ elif obj is type(NotImplemented):
+ return self.save_reduce(type, (NotImplemented,), obj=obj)
+ elif obj in _BUILTIN_TYPE_NAMES:
+ return self.save_reduce(
+ _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)
+
+ if sys.version_info[:2] < (3, 7) and _is_parametrized_type_hint(obj): # noqa # pragma: no branch
+ # Parametrized typing constructs in Python < 3.7 are not
+ # compatible with type checks and ``isinstance`` semantics. For
+ # this reason, it is easier to detect them using a
+ # duck-typing-based check (``_is_parametrized_type_hint``) than
+ # to populate the Pickler's dispatch with type-specific savers.
+ self.save_reduce(
+ _create_parametrized_type_hint,
+ parametrized_type_hint_getinitargs(obj),
+ obj=obj
+ )
+ elif name is not None:
+ Pickler.save_global(self, obj, name=name)
+ elif not _should_pickle_by_reference(obj, name=name):
+ self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj)
+ else:
+ Pickler.save_global(self, obj, name=name)
+ dispatch[type] = save_global
+
+ def save_function(self, obj, name=None):
+ """ Registered with the dispatch to handle all function types.
+
+ Determines what kind of function obj is (e.g. lambda, defined at
+ interactive prompt, etc) and handles the pickling appropriately.
+ """
+ if _should_pickle_by_reference(obj, name=name):
+ return Pickler.save_global(self, obj, name=name)
+ elif PYPY and isinstance(obj.__code__, builtin_code_type):
+ return self.save_pypy_builtin_func(obj)
+ else:
+ return self._save_reduce_pickle5(
+ *self._dynamic_function_reduce(obj), obj=obj
+ )
+
+ def save_pypy_builtin_func(self, obj):
+ """Save pypy equivalent of builtin functions.
+ PyPy does not have the concept of builtin-functions. Instead,
+ builtin-functions are simple function instances, but with a
+ builtin-code attribute.
+ Most of the time, builtin functions should be pickled by attribute.
+ But PyPy has flaky support for __qualname__, so some builtin
+ functions such as float.__new__ will be classified as dynamic. For
+ this reason only, we created this special routine. Because
+ builtin-functions are not expected to have closure or globals,
+ there is no additional hack (compared the one already implemented
+ in pickle) to protect ourselves from reference cycles. A simple
+ (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note
+ also that PyPy improved their support for __qualname__ in v3.6, so
+ this routing should be removed when cloudpickle supports only PyPy
+ 3.6 and later.
+ """
+ rv = (types.FunctionType, (obj.__code__, {}, obj.__name__,
+ obj.__defaults__, obj.__closure__),
+ obj.__dict__)
+ self.save_reduce(*rv, obj=obj)
+
+ dispatch[types.FunctionType] = save_function
diff --git a/runtime/Lib/site-packages/joblib/externals/cloudpickle/compat.py b/runtime/Lib/site-packages/joblib/externals/cloudpickle/compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e9b52773d279c9663961fbbd4d34d92fa63e28b
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/cloudpickle/compat.py
@@ -0,0 +1,18 @@
+import sys
+
+
+if sys.version_info < (3, 8):
+ try:
+ import pickle5 as pickle # noqa: F401
+ from pickle5 import Pickler # noqa: F401
+ except ImportError:
+ import pickle # noqa: F401
+
+ # Use the Python pickler for old CPython versions
+ from pickle import _Pickler as Pickler # noqa: F401
+else:
+ import pickle # noqa: F401
+
+ # Pickler will the C implementation in CPython and the Python
+ # implementation in PyPy
+ from pickle import Pickler # noqa: F401
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/__init__.py b/runtime/Lib/site-packages/joblib/externals/loky/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd2008d789f353f0a5f060e35e9e571e7784107a
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/__init__.py
@@ -0,0 +1,32 @@
+r"""The :mod:`loky` module manages a pool of worker that can be re-used across time.
+It provides a robust and dynamic implementation os the
+:class:`ProcessPoolExecutor` and a function :func:`get_reusable_executor` which
+hide the pool management under the hood.
+"""
+from concurrent.futures import (
+ ALL_COMPLETED,
+ FIRST_COMPLETED,
+ FIRST_EXCEPTION,
+ CancelledError,
+ Executor,
+ TimeoutError,
+ as_completed,
+ wait,
+)
+
+from ._base import Future
+from .backend.context import cpu_count
+from .backend.reduction import set_loky_pickler
+from .reusable_executor import get_reusable_executor
+from .cloudpickle_wrapper import wrap_non_picklable_objects
+from .process_executor import BrokenProcessPool, ProcessPoolExecutor
+
+
+__all__ = ["get_reusable_executor", "cpu_count", "wait", "as_completed",
+ "Future", "Executor", "ProcessPoolExecutor",
+ "BrokenProcessPool", "CancelledError", "TimeoutError",
+ "FIRST_COMPLETED", "FIRST_EXCEPTION", "ALL_COMPLETED",
+ "wrap_non_picklable_objects", "set_loky_pickler"]
+
+
+__version__ = '3.3.0'
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/_base.py b/runtime/Lib/site-packages/joblib/externals/loky/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd8f34100cc0cf182e95020c2b400c689a2c748d
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/_base.py
@@ -0,0 +1,28 @@
+###############################################################################
+# Modification of concurrent.futures.Future
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from concurrent/futures/_base.py (17/02/2017)
+# * Do not use yield from
+# * Use old super syntax
+#
+# Copyright 2009 Brian Quinlan. All Rights Reserved.
+# Licensed to PSF under a Contributor Agreement.
+
+from concurrent.futures import Future as _BaseFuture
+from concurrent.futures._base import LOGGER
+
+
+# To make loky._base.Future instances awaitable by concurrent.futures.wait,
+# derive our custom Future class from _BaseFuture. _invoke_callback is the only
+# modification made to this class in loky.
+# TODO investigate why using `concurrent.futures.Future` directly does not
+# always work in our test suite.
+class Future(_BaseFuture):
+ def _invoke_callbacks(self):
+ for callback in self._done_callbacks:
+ try:
+ callback(self)
+ except BaseException:
+ LOGGER.exception(f'exception calling callback for {self!r}')
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/__init__.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c31023cc5df5f944e4ee91ac18c363c71f17b290
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/__init__.py
@@ -0,0 +1,14 @@
+import os
+from multiprocessing import synchronize
+
+from .context import get_context
+
+
+def _make_name():
+ return f'/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}'
+
+
+# monkey patch the name creation for multiprocessing
+synchronize.SemLock._make_name = staticmethod(_make_name)
+
+__all__ = ["get_context"]
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/_posix_reduction.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/_posix_reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9f34ed569af22bfc3dbcafda67c63a5dabe2330
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/_posix_reduction.py
@@ -0,0 +1,64 @@
+###############################################################################
+# Extra reducers for Unix based system and connections objects
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from multiprocessing/reduction.py (17/02/2017)
+# * Add adapted reduction for LokyProcesses and socket/Connection
+#
+import os
+import socket
+import _socket
+from multiprocessing.connection import Connection
+from multiprocessing.context import get_spawning_popen
+
+from .reduction import register
+
+HAVE_SEND_HANDLE = (hasattr(socket, 'CMSG_LEN') and
+ hasattr(socket, 'SCM_RIGHTS') and
+ hasattr(socket.socket, 'sendmsg'))
+
+
+def _mk_inheritable(fd):
+ os.set_inheritable(fd, True)
+ return fd
+
+
+def DupFd(fd):
+ '''Return a wrapper for an fd.'''
+ popen_obj = get_spawning_popen()
+ if popen_obj is not None:
+ return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
+ elif HAVE_SEND_HANDLE:
+ from multiprocessing import resource_sharer
+ return resource_sharer.DupFd(fd)
+ else:
+ raise TypeError(
+ 'Cannot pickle connection object. This object can only be '
+ 'passed when spawning a new process'
+ )
+
+
+def _reduce_socket(s):
+ df = DupFd(s.fileno())
+ return _rebuild_socket, (df, s.family, s.type, s.proto)
+
+
+def _rebuild_socket(df, family, type, proto):
+ fd = df.detach()
+ return socket.fromfd(fd, family, type, proto)
+
+
+def rebuild_connection(df, readable, writable):
+ fd = df.detach()
+ return Connection(fd, readable, writable)
+
+
+def reduce_connection(conn):
+ df = DupFd(conn.fileno())
+ return rebuild_connection, (df, conn.readable, conn.writable)
+
+
+register(socket.socket, _reduce_socket)
+register(_socket.socket, _reduce_socket)
+register(Connection, reduce_connection)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/_win_reduction.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/_win_reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f50c9f61596191607a5dafe775910cc1f904365
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/_win_reduction.py
@@ -0,0 +1,60 @@
+###############################################################################
+# Extra reducers for Windows system and connections objects
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from multiprocessing/reduction.py (17/02/2017)
+# * Add adapted reduction for LokyProcesses and socket/PipeConnection
+#
+import os
+import socket
+import _winapi
+from multiprocessing.connection import PipeConnection
+from multiprocessing.reduction import _reduce_socket
+
+from .reduction import register
+
+
+class DupHandle:
+ def __init__(self, handle, access, pid=None):
+ # duplicate handle for process with given pid
+ if pid is None:
+ pid = os.getpid()
+ proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid)
+ try:
+ self._handle = _winapi.DuplicateHandle(
+ _winapi.GetCurrentProcess(),
+ handle, proc, access, False, 0)
+ finally:
+ _winapi.CloseHandle(proc)
+ self._access = access
+ self._pid = pid
+
+ def detach(self):
+ # retrieve handle from process which currently owns it
+ if self._pid == os.getpid():
+ return self._handle
+ proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False,
+ self._pid)
+ try:
+ return _winapi.DuplicateHandle(
+ proc, self._handle, _winapi.GetCurrentProcess(),
+ self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE)
+ finally:
+ _winapi.CloseHandle(proc)
+
+
+def rebuild_pipe_connection(dh, readable, writable):
+ handle = dh.detach()
+ return PipeConnection(handle, readable, writable)
+
+
+def reduce_pipe_connection(conn):
+ access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
+ (_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
+ dh = DupHandle(conn.fileno(), access)
+ return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
+
+
+register(PipeConnection, reduce_pipe_connection)
+register(socket.socket, _reduce_socket)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/context.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e551688b40993776c1d23ca96ded2da71177b5a
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/context.py
@@ -0,0 +1,304 @@
+###############################################################################
+# Basic context management with LokyContext
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from multiprocessing/context.py
+# * Create a context ensuring loky uses only objects that are compatible
+# * Add LokyContext to the list of context of multiprocessing so loky can be
+# used with multiprocessing.set_start_method
+# * Implement a CFS-aware amd physical-core aware cpu_count function.
+#
+import os
+import sys
+import math
+import subprocess
+import traceback
+import warnings
+import multiprocessing as mp
+from multiprocessing import get_context as mp_get_context
+from multiprocessing.context import BaseContext
+
+from .process import LokyProcess, LokyInitMainProcess
+
+START_METHODS = ['loky', 'loky_init_main', 'spawn']
+if sys.platform != 'win32':
+ START_METHODS += ['fork', 'forkserver']
+
+_DEFAULT_START_METHOD = None
+
+# Cache for the number of physical cores to avoid repeating subprocess calls.
+# It should not change during the lifetime of the program.
+physical_cores_cache = None
+
+
+def get_context(method=None):
+ # Try to overload the default context
+ method = method or _DEFAULT_START_METHOD or "loky"
+ if method == "fork":
+ # If 'fork' is explicitly requested, warn user about potential issues.
+ warnings.warn("`fork` start method should not be used with "
+ "`loky` as it does not respect POSIX. Try using "
+ "`spawn` or `loky` instead.", UserWarning)
+ try:
+ return mp_get_context(method)
+ except ValueError:
+ raise ValueError(
+ f"Unknown context '{method}'. Value should be in "
+ f"{START_METHODS}."
+ )
+
+
+def set_start_method(method, force=False):
+ global _DEFAULT_START_METHOD
+ if _DEFAULT_START_METHOD is not None and not force:
+ raise RuntimeError('context has already been set')
+ assert method is None or method in START_METHODS, (
+ f"'{method}' is not a valid start_method. It should be in "
+ f"{START_METHODS}"
+ )
+
+ _DEFAULT_START_METHOD = method
+
+
+def get_start_method():
+ return _DEFAULT_START_METHOD
+
+
+def cpu_count(only_physical_cores=False):
+ """Return the number of CPUs the current process can use.
+
+ The returned number of CPUs accounts for:
+ * the number of CPUs in the system, as given by
+ ``multiprocessing.cpu_count``;
+ * the CPU affinity settings of the current process
+ (available on some Unix systems);
+ * Cgroup CPU bandwidth limit (available on Linux only, typically
+ set by docker and similar container orchestration systems);
+ * the value of the LOKY_MAX_CPU_COUNT environment variable if defined.
+ and is given as the minimum of these constraints.
+
+ If ``only_physical_cores`` is True, return the number of physical cores
+ instead of the number of logical cores (hyperthreading / SMT). Note that
+ this option is not enforced if the number of usable cores is controlled in
+ any other way such as: process affinity, Cgroup restricted CPU bandwidth
+ or the LOKY_MAX_CPU_COUNT environment variable. If the number of physical
+ cores is not found, return the number of logical cores.
+
+ It is also always larger or equal to 1.
+ """
+ # Note: os.cpu_count() is allowed to return None in its docstring
+ os_cpu_count = os.cpu_count() or 1
+
+ cpu_count_user = _cpu_count_user(os_cpu_count)
+ aggregate_cpu_count = max(min(os_cpu_count, cpu_count_user), 1)
+
+ if not only_physical_cores:
+ return aggregate_cpu_count
+
+ if cpu_count_user < os_cpu_count:
+ # Respect user setting
+ return max(cpu_count_user, 1)
+
+ cpu_count_physical, exception = _count_physical_cores()
+ if cpu_count_physical != "not found":
+ return cpu_count_physical
+
+ # Fallback to default behavior
+ if exception is not None:
+ # warns only the first time
+ warnings.warn(
+ "Could not find the number of physical cores for the "
+ f"following reason:\n{exception}\n"
+ "Returning the number of logical cores instead. You can "
+ "silence this warning by setting LOKY_MAX_CPU_COUNT to "
+ "the number of cores you want to use.")
+ traceback.print_tb(exception.__traceback__)
+
+ return aggregate_cpu_count
+
+
+def _cpu_count_cgroup(os_cpu_count):
+ # Cgroup CPU bandwidth limit available in Linux since 2.6 kernel
+ cpu_max_fname = "/sys/fs/cgroup/cpu.max"
+ cfs_quota_fname = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
+ cfs_period_fname = "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
+ if os.path.exists(cpu_max_fname):
+ # cgroup v2
+ # https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
+ with open(cpu_max_fname) as fh:
+ cpu_quota_us, cpu_period_us = fh.read().strip().split()
+ elif os.path.exists(cfs_quota_fname) and os.path.exists(cfs_period_fname):
+ # cgroup v1
+ # https://www.kernel.org/doc/html/latest/scheduler/sched-bwc.html#management
+ with open(cfs_quota_fname) as fh:
+ cpu_quota_us = fh.read().strip()
+ with open(cfs_period_fname) as fh:
+ cpu_period_us = fh.read().strip()
+ else:
+ # No Cgroup CPU bandwidth limit (e.g. non-Linux platform)
+ cpu_quota_us = "max"
+ cpu_period_us = 100_000 # unused, for consistency with default values
+
+ if cpu_quota_us == "max":
+ # No active Cgroup quota on a Cgroup-capable platform
+ return os_cpu_count
+ else:
+ cpu_quota_us = int(cpu_quota_us)
+ cpu_period_us = int(cpu_period_us)
+ if cpu_quota_us > 0 and cpu_period_us > 0:
+ return math.ceil(cpu_quota_us / cpu_period_us)
+ else: # pragma: no cover
+ # Setting a negative cpu_quota_us value is a valid way to disable
+ # cgroup CPU bandwith limits
+ return os_cpu_count
+
+
+def _cpu_count_user(os_cpu_count):
+ """Number of user defined available CPUs"""
+ # Number of available CPUs given affinity settings
+ cpu_count_affinity = os_cpu_count
+ if hasattr(os, 'sched_getaffinity'):
+ try:
+ cpu_count_affinity = len(os.sched_getaffinity(0))
+ except NotImplementedError:
+ pass
+
+ cpu_count_cgroup = _cpu_count_cgroup(os_cpu_count)
+
+ # User defined soft-limit passed as a loky specific environment variable.
+ cpu_count_loky = int(os.environ.get('LOKY_MAX_CPU_COUNT', os_cpu_count))
+
+ return min(cpu_count_affinity, cpu_count_cgroup, cpu_count_loky)
+
+
+def _count_physical_cores():
+ """Return a tuple (number of physical cores, exception)
+
+ If the number of physical cores is found, exception is set to None.
+ If it has not been found, return ("not found", exception).
+
+ The number of physical cores is cached to avoid repeating subprocess calls.
+ """
+ exception = None
+
+ # First check if the value is cached
+ global physical_cores_cache
+ if physical_cores_cache is not None:
+ return physical_cores_cache, exception
+
+ # Not cached yet, find it
+ try:
+ if sys.platform == "linux":
+ cpu_info = subprocess.run(
+ "lscpu --parse=core".split(), capture_output=True, text=True)
+ cpu_info = cpu_info.stdout.splitlines()
+ cpu_info = {line for line in cpu_info if not line.startswith("#")}
+ cpu_count_physical = len(cpu_info)
+ elif sys.platform == "win32":
+ cpu_info = subprocess.run(
+ "wmic CPU Get NumberOfCores /Format:csv".split(),
+ capture_output=True, text=True)
+ cpu_info = cpu_info.stdout.splitlines()
+ cpu_info = [l.split(",")[1] for l in cpu_info
+ if (l and l != "Node,NumberOfCores")]
+ cpu_count_physical = sum(map(int, cpu_info))
+ elif sys.platform == "darwin":
+ cpu_info = subprocess.run(
+ "sysctl -n hw.physicalcpu".split(),
+ capture_output=True, text=True)
+ cpu_info = cpu_info.stdout
+ cpu_count_physical = int(cpu_info)
+ else:
+ raise NotImplementedError(f"unsupported platform: {sys.platform}")
+
+ # if cpu_count_physical < 1, we did not find a valid value
+ if cpu_count_physical < 1:
+ raise ValueError(
+ f"found {cpu_count_physical} physical cores < 1")
+
+ except Exception as e:
+ exception = e
+ cpu_count_physical = "not found"
+
+ # Put the result in cache
+ physical_cores_cache = cpu_count_physical
+
+ return cpu_count_physical, exception
+
+
+class LokyContext(BaseContext):
+ """Context relying on the LokyProcess."""
+ _name = 'loky'
+ Process = LokyProcess
+ cpu_count = staticmethod(cpu_count)
+
+ def Queue(self, maxsize=0, reducers=None):
+ '''Returns a queue object'''
+ from .queues import Queue
+ return Queue(maxsize, reducers=reducers,
+ ctx=self.get_context())
+
+ def SimpleQueue(self, reducers=None):
+ '''Returns a queue object'''
+ from .queues import SimpleQueue
+ return SimpleQueue(reducers=reducers, ctx=self.get_context())
+
+ if sys.platform != "win32":
+ """For Unix platform, use our custom implementation of synchronize
+ ensuring that we use the loky.backend.resource_tracker to clean-up
+ the semaphores in case of a worker crash.
+ """
+ def Semaphore(self, value=1):
+ """Returns a semaphore object"""
+ from .synchronize import Semaphore
+ return Semaphore(value=value)
+
+ def BoundedSemaphore(self, value):
+ """Returns a bounded semaphore object"""
+ from .synchronize import BoundedSemaphore
+ return BoundedSemaphore(value)
+
+ def Lock(self):
+ """Returns a lock object"""
+ from .synchronize import Lock
+ return Lock()
+
+ def RLock(self):
+ """Returns a recurrent lock object"""
+ from .synchronize import RLock
+ return RLock()
+
+ def Condition(self, lock=None):
+ """Returns a condition object"""
+ from .synchronize import Condition
+ return Condition(lock)
+
+ def Event(self):
+ """Returns an event object"""
+ from .synchronize import Event
+ return Event()
+
+
+class LokyInitMainContext(LokyContext):
+ """Extra context with LokyProcess, which does load the main module
+
+ This context is used for compatibility in the case ``cloudpickle`` is not
+ present on the running system. This permits to load functions defined in
+ the ``main`` module, using proper safeguards. The declaration of the
+ ``executor`` should be protected by ``if __name__ == "__main__":`` and the
+ functions and variable used from main should be out of this block.
+
+ This mimics the default behavior of multiprocessing under Windows and the
+ behavior of the ``spawn`` start method on a posix system.
+ For more details, see the end of the following section of python doc
+ https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming
+ """
+ _name = 'loky_init_main'
+ Process = LokyInitMainProcess
+
+
+# Register loky context so it works with multiprocessing.get_context
+ctx_loky = LokyContext()
+mp.context._concrete_contexts['loky'] = ctx_loky
+mp.context._concrete_contexts['loky_init_main'] = LokyInitMainContext()
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/fork_exec.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/fork_exec.py
new file mode 100644
index 0000000000000000000000000000000000000000..211d1835afcae058993949fe409f02a390446356
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/fork_exec.py
@@ -0,0 +1,42 @@
+###############################################################################
+# Launch a subprocess using forkexec and make sure only the needed fd are
+# shared in the two process.
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+import os
+import sys
+
+
+def close_fds(keep_fds): # pragma: no cover
+ """Close all the file descriptors except those in keep_fds."""
+
+ # Make sure to keep stdout and stderr open for logging purpose
+ keep_fds = {*keep_fds, 1, 2}
+
+ # We try to retrieve all the open fds
+ try:
+ open_fds = {int(fd) for fd in os.listdir('/proc/self/fd')}
+ except FileNotFoundError:
+ import resource
+ max_nfds = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
+ open_fds = {*range(max_nfds)}
+
+ for i in open_fds - keep_fds:
+ try:
+ os.close(i)
+ except OSError:
+ pass
+
+
+def fork_exec(cmd, keep_fds, env=None):
+ # copy the environment variables to set in the child process
+ env = env or {}
+ child_env = {**os.environ, **env}
+
+ pid = os.fork()
+ if pid == 0: # pragma: no cover
+ close_fds(keep_fds)
+ os.execve(sys.executable, cmd, child_env)
+ else:
+ return pid
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py
new file mode 100644
index 0000000000000000000000000000000000000000..37a73172e74189a4ff2707e11da94a8b576af747
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py
@@ -0,0 +1,182 @@
+###############################################################################
+# Popen for LokyProcess.
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+import os
+import sys
+import signal
+import pickle
+from io import BytesIO
+from multiprocessing import util, process
+from multiprocessing.connection import wait
+from multiprocessing.context import set_spawning_popen
+
+from . import reduction, resource_tracker, spawn
+
+
+__all__ = ['Popen']
+
+
+#
+# Wrapper for an fd used while launching a process
+#
+
+class _DupFd:
+ def __init__(self, fd):
+ self.fd = reduction._mk_inheritable(fd)
+
+ def detach(self):
+ return self.fd
+
+
+#
+# Start child process using subprocess.Popen
+#
+
+class Popen:
+ method = 'loky'
+ DupFd = _DupFd
+
+ def __init__(self, process_obj):
+ sys.stdout.flush()
+ sys.stderr.flush()
+ self.returncode = None
+ self._fds = []
+ self._launch(process_obj)
+
+ def duplicate_for_child(self, fd):
+ self._fds.append(fd)
+ return reduction._mk_inheritable(fd)
+
+ def poll(self, flag=os.WNOHANG):
+ if self.returncode is None:
+ while True:
+ try:
+ pid, sts = os.waitpid(self.pid, flag)
+ except OSError:
+ # Child process not yet created. See #1731717
+ # e.errno == errno.ECHILD == 10
+ return None
+ else:
+ break
+ if pid == self.pid:
+ if os.WIFSIGNALED(sts):
+ self.returncode = -os.WTERMSIG(sts)
+ else:
+ assert os.WIFEXITED(sts)
+ self.returncode = os.WEXITSTATUS(sts)
+ return self.returncode
+
+ def wait(self, timeout=None):
+ if self.returncode is None:
+ if timeout is not None:
+ if not wait([self.sentinel], timeout):
+ return None
+ # This shouldn't block if wait() returned successfully.
+ return self.poll(os.WNOHANG if timeout == 0.0 else 0)
+ return self.returncode
+
+ def terminate(self):
+ if self.returncode is None:
+ try:
+ os.kill(self.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ except OSError:
+ if self.wait(timeout=0.1) is None:
+ raise
+
+ def _launch(self, process_obj):
+
+ tracker_fd = resource_tracker._resource_tracker.getfd()
+
+ fp = BytesIO()
+ set_spawning_popen(self)
+ try:
+ prep_data = spawn.get_preparation_data(
+ process_obj._name,
+ getattr(process_obj, "init_main_module", True))
+ reduction.dump(prep_data, fp)
+ reduction.dump(process_obj, fp)
+
+ finally:
+ set_spawning_popen(None)
+
+ try:
+ parent_r, child_w = os.pipe()
+ child_r, parent_w = os.pipe()
+ # for fd in self._fds:
+ # _mk_inheritable(fd)
+
+ cmd_python = [sys.executable]
+ cmd_python += ['-m', self.__module__]
+ cmd_python += ['--process-name', str(process_obj.name)]
+ cmd_python += ['--pipe', str(reduction._mk_inheritable(child_r))]
+ reduction._mk_inheritable(child_w)
+ reduction._mk_inheritable(tracker_fd)
+ self._fds += [child_r, child_w, tracker_fd]
+ if sys.version_info >= (3, 8) and os.name == 'posix':
+ mp_tracker_fd = prep_data['mp_tracker_args']['fd']
+ self.duplicate_for_child(mp_tracker_fd)
+
+ from .fork_exec import fork_exec
+ pid = fork_exec(cmd_python, self._fds, env=process_obj.env)
+ util.debug(
+ f"launched python with pid {pid} and cmd:\n{cmd_python}"
+ )
+ self.sentinel = parent_r
+
+ method = 'getbuffer'
+ if not hasattr(fp, method):
+ method = 'getvalue'
+ with os.fdopen(parent_w, 'wb') as f:
+ f.write(getattr(fp, method)())
+ self.pid = pid
+ finally:
+ if parent_r is not None:
+ util.Finalize(self, os.close, (parent_r,))
+ for fd in (child_r, child_w):
+ if fd is not None:
+ os.close(fd)
+
+ @staticmethod
+ def thread_is_spawning():
+ return True
+
+
+if __name__ == '__main__':
+ import argparse
+ parser = argparse.ArgumentParser('Command line parser')
+ parser.add_argument('--pipe', type=int, required=True,
+ help='File handle for the pipe')
+ parser.add_argument('--process-name', type=str, default=None,
+ help='Identifier for debugging purpose')
+
+ args = parser.parse_args()
+
+ info = {}
+ exitcode = 1
+ try:
+ with os.fdopen(args.pipe, 'rb') as from_parent:
+ process.current_process()._inheriting = True
+ try:
+ prep_data = pickle.load(from_parent)
+ spawn.prepare(prep_data)
+ process_obj = pickle.load(from_parent)
+ finally:
+ del process.current_process()._inheriting
+
+ exitcode = process_obj._bootstrap()
+ except Exception:
+ print('\n\n' + '-' * 80)
+ print(f'{args.process_name} failed with traceback: ')
+ print('-' * 80)
+ import traceback
+ print(traceback.format_exc())
+ print('\n' + '-' * 80)
+ finally:
+ if from_parent is not None:
+ from_parent.close()
+
+ sys.exit(exitcode)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_win32.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_win32.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2702a7241e4b1063bb2943ea929552003e6fb3d
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_win32.py
@@ -0,0 +1,156 @@
+import os
+import sys
+import msvcrt
+import _winapi
+from pickle import load
+from multiprocessing import process, util
+from multiprocessing.context import get_spawning_popen, set_spawning_popen
+from multiprocessing.popen_spawn_win32 import Popen as _Popen
+from multiprocessing.reduction import duplicate
+
+from . import reduction, spawn
+
+
+__all__ = ['Popen']
+
+#
+#
+#
+
+
+def _path_eq(p1, p2):
+ return p1 == p2 or os.path.normcase(p1) == os.path.normcase(p2)
+
+
+WINENV = (hasattr(sys, "_base_executable")
+ and not _path_eq(sys.executable, sys._base_executable))
+
+#
+# We define a Popen class similar to the one from subprocess, but
+# whose constructor takes a process object as its argument.
+#
+
+
+class Popen(_Popen):
+ '''
+ Start a subprocess to run the code of a process object
+ '''
+ method = 'loky'
+
+ def __init__(self, process_obj):
+ prep_data = spawn.get_preparation_data(
+ process_obj._name, getattr(process_obj, "init_main_module", True))
+
+ # read end of pipe will be "stolen" by the child process
+ # -- see spawn_main() in spawn.py.
+ rfd, wfd = os.pipe()
+ rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable=True)
+ os.close(rfd)
+
+ cmd = get_command_line(parent_pid=os.getpid(), pipe_handle=rhandle)
+ cmd = ' '.join(f'"{x}"' for x in cmd)
+
+ python_exe = spawn.get_executable()
+
+ # copy the environment variables to set in the child process
+ child_env = {**os.environ, **process_obj.env}
+
+ # bpo-35797: When running in a venv, we bypass the redirect
+ # executor and launch our base Python.
+ if WINENV and _path_eq(python_exe, sys.executable):
+ python_exe = sys._base_executable
+ child_env["__PYVENV_LAUNCHER__"] = sys.executable
+
+ try:
+ with open(wfd, 'wb') as to_child:
+ # start process
+ try:
+ # This flag allows to pass inheritable handles from the
+ # parent to the child process in a python2-3 compatible way
+ # (see
+ # https://github.com/tomMoral/loky/pull/204#discussion_r290719629
+ # for more detail). When support for Python 2 is dropped,
+ # the cleaner multiprocessing.reduction.steal_handle should
+ # be used instead.
+ inherit = True
+ hp, ht, pid, _ = _winapi.CreateProcess(
+ python_exe, cmd,
+ None, None, inherit, 0,
+ child_env, None, None)
+ _winapi.CloseHandle(ht)
+ except BaseException:
+ _winapi.CloseHandle(rhandle)
+ raise
+
+ # set attributes of self
+ self.pid = pid
+ self.returncode = None
+ self._handle = hp
+ self.sentinel = int(hp)
+ util.Finalize(self, _winapi.CloseHandle, (self.sentinel,))
+
+ # send information to child
+ set_spawning_popen(self)
+ try:
+ reduction.dump(prep_data, to_child)
+ reduction.dump(process_obj, to_child)
+ finally:
+ set_spawning_popen(None)
+ except IOError as exc:
+ # IOError 22 happens when the launched subprocess terminated before
+ # wfd.close is called. Thus we can safely ignore it.
+ if exc.errno != 22:
+ raise
+ util.debug(
+ f"While starting {process_obj._name}, ignored a IOError 22"
+ )
+
+ def duplicate_for_child(self, handle):
+ assert self is get_spawning_popen()
+ return duplicate(handle, self.sentinel)
+
+
+def get_command_line(pipe_handle, **kwds):
+ '''
+ Returns prefix of command line used for spawning a child process
+ '''
+ if getattr(sys, 'frozen', False):
+ return [sys.executable, '--multiprocessing-fork', pipe_handle]
+ else:
+ prog = 'from joblib.externals.loky.backend.popen_loky_win32 import main; main()'
+ opts = util._args_from_interpreter_flags()
+ return [spawn.get_executable(), *opts,
+ '-c', prog, '--multiprocessing-fork', pipe_handle]
+
+
+def is_forking(argv):
+ '''
+ Return whether commandline indicates we are forking
+ '''
+ if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
+ assert len(argv) == 3
+ return True
+ else:
+ return False
+
+
+def main():
+ '''
+ Run code specified by data received over pipe
+ '''
+ assert is_forking(sys.argv)
+
+ handle = int(sys.argv[-1])
+ fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
+ from_parent = os.fdopen(fd, 'rb')
+
+ process.current_process()._inheriting = True
+ preparation_data = load(from_parent)
+ spawn.prepare(preparation_data)
+ self = load(from_parent)
+ process.current_process()._inheriting = False
+
+ from_parent.close()
+
+ exitcode = self._bootstrap()
+ sys.exit(exitcode)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/process.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/process.py
new file mode 100644
index 0000000000000000000000000000000000000000..eafde66d0fe54cab27816aa86e8203a50515c16d
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/process.py
@@ -0,0 +1,58 @@
+###############################################################################
+# LokyProcess implementation
+#
+# authors: Thomas Moreau and Olivier Grisel
+#
+# based on multiprocessing/process.py (17/02/2017)
+#
+import sys
+from multiprocessing.context import assert_spawning
+from multiprocessing.process import BaseProcess
+
+
+class LokyProcess(BaseProcess):
+ _start_method = 'loky'
+
+ def __init__(self, group=None, target=None, name=None, args=(),
+ kwargs={}, daemon=None, init_main_module=False,
+ env=None):
+ super().__init__(
+ group=group, target=target, name=name, args=args,
+ kwargs=kwargs, daemon=daemon)
+ self.env = {} if env is None else env
+ self.authkey = self.authkey
+ self.init_main_module = init_main_module
+
+ @staticmethod
+ def _Popen(process_obj):
+ if sys.platform == "win32":
+ from .popen_loky_win32 import Popen
+ else:
+ from .popen_loky_posix import Popen
+ return Popen(process_obj)
+
+
+class LokyInitMainProcess(LokyProcess):
+ _start_method = 'loky_init_main'
+
+ def __init__(self, group=None, target=None, name=None, args=(),
+ kwargs={}, daemon=None):
+ super().__init__(
+ group=group, target=target, name=name, args=args, kwargs=kwargs,
+ daemon=daemon, init_main_module=True)
+
+
+#
+# We subclass bytes to avoid accidental transmission of auth keys over network
+#
+
+class AuthenticationKey(bytes):
+ def __reduce__(self):
+ try:
+ assert_spawning(self)
+ except RuntimeError:
+ raise TypeError(
+ 'Pickling an AuthenticationKey object is '
+ 'disallowed for security reasons'
+ )
+ return AuthenticationKey, (bytes(self),)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/queues.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/queues.py
new file mode 100644
index 0000000000000000000000000000000000000000..4113b89fbbae78d0b69087472be269eac705ca67
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/queues.py
@@ -0,0 +1,192 @@
+###############################################################################
+# Queue and SimpleQueue implementation for loky
+#
+# authors: Thomas Moreau, Olivier Grisel
+#
+# based on multiprocessing/queues.py (16/02/2017)
+# * Add some custom reducers for the Queues/SimpleQueue to tweak the
+# pickling process. (overload Queue._feed/SimpleQueue.put)
+#
+import os
+import sys
+import errno
+import weakref
+import threading
+from multiprocessing import util
+from multiprocessing.queues import (
+ Full,
+ Queue as mp_Queue,
+ SimpleQueue as mp_SimpleQueue,
+ _sentinel,
+)
+from multiprocessing.context import assert_spawning
+
+from .reduction import dumps
+
+
+__all__ = ['Queue', 'SimpleQueue', 'Full']
+
+
+class Queue(mp_Queue):
+
+ def __init__(self, maxsize=0, reducers=None, ctx=None):
+ super().__init__(maxsize=maxsize, ctx=ctx)
+ self._reducers = reducers
+
+ # Use custom queue set/get state to be able to reduce the custom reducers
+ def __getstate__(self):
+ assert_spawning(self)
+ return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
+ self._reducers, self._rlock, self._wlock, self._sem,
+ self._opid)
+
+ def __setstate__(self, state):
+ (self._ignore_epipe, self._maxsize, self._reader, self._writer,
+ self._reducers, self._rlock, self._wlock, self._sem,
+ self._opid) = state
+ if sys.version_info >= (3, 9):
+ self._reset()
+ else:
+ self._after_fork()
+
+ # Overload _start_thread to correctly call our custom _feed
+ def _start_thread(self):
+ util.debug('Queue._start_thread()')
+
+ # Start thread which transfers data from buffer to pipe
+ self._buffer.clear()
+ self._thread = threading.Thread(
+ target=Queue._feed,
+ args=(self._buffer, self._notempty, self._send_bytes,
+ self._wlock, self._writer.close, self._reducers,
+ self._ignore_epipe, self._on_queue_feeder_error, self._sem),
+ name='QueueFeederThread'
+ )
+ self._thread.daemon = True
+
+ util.debug('doing self._thread.start()')
+ self._thread.start()
+ util.debug('... done self._thread.start()')
+
+ # On process exit we will wait for data to be flushed to pipe.
+ #
+ # However, if this process created the queue then all
+ # processes which use the queue will be descendants of this
+ # process. Therefore waiting for the queue to be flushed
+ # is pointless once all the child processes have been joined.
+ created_by_this_process = (self._opid == os.getpid())
+ if not self._joincancelled and not created_by_this_process:
+ self._jointhread = util.Finalize(
+ self._thread, Queue._finalize_join,
+ [weakref.ref(self._thread)],
+ exitpriority=-5
+ )
+
+ # Send sentinel to the thread queue object when garbage collected
+ self._close = util.Finalize(
+ self, Queue._finalize_close,
+ [self._buffer, self._notempty],
+ exitpriority=10
+ )
+
+ # Overload the _feed methods to use our custom pickling strategy.
+ @staticmethod
+ def _feed(buffer, notempty, send_bytes, writelock, close, reducers,
+ ignore_epipe, onerror, queue_sem):
+ util.debug('starting thread to feed data to pipe')
+ nacquire = notempty.acquire
+ nrelease = notempty.release
+ nwait = notempty.wait
+ bpopleft = buffer.popleft
+ sentinel = _sentinel
+ if sys.platform != 'win32':
+ wacquire = writelock.acquire
+ wrelease = writelock.release
+ else:
+ wacquire = None
+
+ while True:
+ try:
+ nacquire()
+ try:
+ if not buffer:
+ nwait()
+ finally:
+ nrelease()
+ try:
+ while True:
+ obj = bpopleft()
+ if obj is sentinel:
+ util.debug('feeder thread got sentinel -- exiting')
+ close()
+ return
+
+ # serialize the data before acquiring the lock
+ obj_ = dumps(obj, reducers=reducers)
+ if wacquire is None:
+ send_bytes(obj_)
+ else:
+ wacquire()
+ try:
+ send_bytes(obj_)
+ finally:
+ wrelease()
+ # Remove references early to avoid leaking memory
+ del obj, obj_
+ except IndexError:
+ pass
+ except BaseException as e:
+ if ignore_epipe and getattr(e, 'errno', 0) == errno.EPIPE:
+ return
+ # Since this runs in a daemon thread the resources it uses
+ # may be become unusable while the process is cleaning up.
+ # We ignore errors which happen after the process has
+ # started to cleanup.
+ if util.is_exiting():
+ util.info(f'error in queue thread: {e}')
+ return
+ else:
+ queue_sem.release()
+ onerror(e, obj)
+
+ def _on_queue_feeder_error(self, e, obj):
+ """
+ Private API hook called when feeding data in the background thread
+ raises an exception. For overriding by concurrent.futures.
+ """
+ import traceback
+ traceback.print_exc()
+
+
+class SimpleQueue(mp_SimpleQueue):
+
+ def __init__(self, reducers=None, ctx=None):
+ super().__init__(ctx=ctx)
+
+ # Add possiblity to use custom reducers
+ self._reducers = reducers
+
+ def close(self):
+ self._reader.close()
+ self._writer.close()
+
+ # Use custom queue set/get state to be able to reduce the custom reducers
+ def __getstate__(self):
+ assert_spawning(self)
+ return (self._reader, self._writer, self._reducers, self._rlock,
+ self._wlock)
+
+ def __setstate__(self, state):
+ (self._reader, self._writer, self._reducers, self._rlock,
+ self._wlock) = state
+
+ # Overload put to use our customizable reducer
+ def put(self, obj):
+ # serialize the data before acquiring the lock
+ obj = dumps(obj, reducers=self._reducers)
+ if self._wlock is None:
+ # writes to a message oriented win32 pipe are atomic
+ self._writer.send_bytes(obj)
+ else:
+ with self._wlock:
+ self._writer.send_bytes(obj)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/reduction.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/reduction.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1ee394bb37d52dd1214d4f60ff1b04f931d885b
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/reduction.py
@@ -0,0 +1,219 @@
+###############################################################################
+# Customizable Pickler with some basic reducers
+#
+# author: Thomas Moreau
+#
+# adapted from multiprocessing/reduction.py (17/02/2017)
+# * Replace the ForkingPickler with a similar _LokyPickler,
+# * Add CustomizableLokyPickler to allow customizing pickling process
+# on the fly.
+#
+import copyreg
+import io
+import functools
+import types
+import sys
+import os
+
+from multiprocessing import util
+from pickle import loads, HIGHEST_PROTOCOL
+
+###############################################################################
+# Enable custom pickling in Loky.
+
+_dispatch_table = {}
+
+
+def register(type_, reduce_function):
+ _dispatch_table[type_] = reduce_function
+
+###############################################################################
+# Registers extra pickling routines to improve picklization for loky
+
+
+# make methods picklable
+def _reduce_method(m):
+ if m.__self__ is None:
+ return getattr, (m.__class__, m.__func__.__name__)
+ else:
+ return getattr, (m.__self__, m.__func__.__name__)
+
+
+class _C:
+ def f(self):
+ pass
+
+ @classmethod
+ def h(cls):
+ pass
+
+
+register(type(_C().f), _reduce_method)
+register(type(_C.h), _reduce_method)
+
+
+if not hasattr(sys, "pypy_version_info"):
+ # PyPy uses functions instead of method_descriptors and wrapper_descriptors
+ def _reduce_method_descriptor(m):
+ return getattr, (m.__objclass__, m.__name__)
+
+ register(type(list.append), _reduce_method_descriptor)
+ register(type(int.__add__), _reduce_method_descriptor)
+
+
+# Make partial func pickable
+def _reduce_partial(p):
+ return _rebuild_partial, (p.func, p.args, p.keywords or {})
+
+
+def _rebuild_partial(func, args, keywords):
+ return functools.partial(func, *args, **keywords)
+
+
+register(functools.partial, _reduce_partial)
+
+if sys.platform != "win32":
+ from ._posix_reduction import _mk_inheritable # noqa: F401
+else:
+ from . import _win_reduction # noqa: F401
+
+# global variable to change the pickler behavior
+try:
+ from joblib.externals import cloudpickle # noqa: F401
+ DEFAULT_ENV = "cloudpickle"
+except ImportError:
+ # If cloudpickle is not present, fallback to pickle
+ DEFAULT_ENV = "pickle"
+
+ENV_LOKY_PICKLER = os.environ.get("LOKY_PICKLER", DEFAULT_ENV)
+_LokyPickler = None
+_loky_pickler_name = None
+
+
+def set_loky_pickler(loky_pickler=None):
+ global _LokyPickler, _loky_pickler_name
+
+ if loky_pickler is None:
+ loky_pickler = ENV_LOKY_PICKLER
+
+ loky_pickler_cls = None
+
+ # The default loky_pickler is cloudpickle
+ if loky_pickler in ["", None]:
+ loky_pickler = "cloudpickle"
+
+ if loky_pickler == _loky_pickler_name:
+ return
+
+ if loky_pickler == "cloudpickle":
+ from joblib.externals.cloudpickle import CloudPickler as loky_pickler_cls
+ else:
+ try:
+ from importlib import import_module
+ module_pickle = import_module(loky_pickler)
+ loky_pickler_cls = module_pickle.Pickler
+ except (ImportError, AttributeError) as e:
+ extra_info = ("\nThis error occurred while setting loky_pickler to"
+ f" '{loky_pickler}', as required by the env variable "
+ "LOKY_PICKLER or the function set_loky_pickler.")
+ e.args = (e.args[0] + extra_info,) + e.args[1:]
+ e.msg = e.args[0]
+ raise e
+
+ util.debug(
+ f"Using '{loky_pickler if loky_pickler else 'cloudpickle'}' for "
+ "serialization."
+ )
+
+ class CustomizablePickler(loky_pickler_cls):
+ _loky_pickler_cls = loky_pickler_cls
+
+ def _set_dispatch_table(self, dispatch_table):
+ for ancestor_class in self._loky_pickler_cls.mro():
+ dt_attribute = getattr(ancestor_class, "dispatch_table", None)
+ if isinstance(dt_attribute, types.MemberDescriptorType):
+ # Ancestor class (typically _pickle.Pickler) has a
+ # member_descriptor for its "dispatch_table" attribute. Use
+ # it to set the dispatch_table as a member instead of a
+ # dynamic attribute in the __dict__ of the instance,
+ # otherwise it will not be taken into account by the C
+ # implementation of the dump method if a subclass defines a
+ # class-level dispatch_table attribute as was done in
+ # cloudpickle 1.6.0:
+ # https://github.com/joblib/loky/pull/260
+ dt_attribute.__set__(self, dispatch_table)
+ break
+
+ # On top of member descriptor set, also use setattr such that code
+ # that directly access self.dispatch_table gets a consistent view
+ # of the same table.
+ self.dispatch_table = dispatch_table
+
+ def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL):
+ loky_pickler_cls.__init__(self, writer, protocol=protocol)
+ if reducers is None:
+ reducers = {}
+
+ if hasattr(self, "dispatch_table"):
+ # Force a copy that we will update without mutating the
+ # any class level defined dispatch_table.
+ loky_dt = dict(self.dispatch_table)
+ else:
+ # Use standard reducers as bases
+ loky_dt = copyreg.dispatch_table.copy()
+
+ # Register loky specific reducers
+ loky_dt.update(_dispatch_table)
+
+ # Set the new dispatch table, taking care of the fact that we
+ # need to use the member_descriptor when we inherit from a
+ # subclass of the C implementation of the Pickler base class
+ # with an class level dispatch_table attribute.
+ self._set_dispatch_table(loky_dt)
+
+ # Register the reducers
+ for type, reduce_func in reducers.items():
+ self.register(type, reduce_func)
+
+ def register(self, type, reduce_func):
+ """Attach a reducer function to a given type in the dispatch table.
+ """
+ self.dispatch_table[type] = reduce_func
+
+ _LokyPickler = CustomizablePickler
+ _loky_pickler_name = loky_pickler
+
+
+def get_loky_pickler_name():
+ global _loky_pickler_name
+ return _loky_pickler_name
+
+
+def get_loky_pickler():
+ global _LokyPickler
+ return _LokyPickler
+
+
+# Set it to its default value
+set_loky_pickler()
+
+
+def dump(obj, file, reducers=None, protocol=None):
+ '''Replacement for pickle.dump() using _LokyPickler.'''
+ global _LokyPickler
+ _LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
+
+
+def dumps(obj, reducers=None, protocol=None):
+ global _LokyPickler
+
+ buf = io.BytesIO()
+ dump(obj, buf, reducers=reducers, protocol=protocol)
+ return buf.getbuffer()
+
+
+__all__ = ["dump", "dumps", "loads", "register", "set_loky_pickler"]
+
+if sys.platform == "win32":
+ from multiprocessing.reduction import duplicate
+ __all__ += ["duplicate"]
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/resource_tracker.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/resource_tracker.py
new file mode 100644
index 0000000000000000000000000000000000000000..d84504e142138f83fdb130afb7452e22c2e98351
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/resource_tracker.py
@@ -0,0 +1,371 @@
+###############################################################################
+# Server process to keep track of unlinked resources, like folders and
+# semaphores and clean them.
+#
+# author: Thomas Moreau
+#
+# adapted from multiprocessing/semaphore_tracker.py (17/02/2017)
+# * include custom spawnv_passfds to start the process
+# * add some VERBOSE logging
+#
+# TODO: multiprocessing.resource_tracker was contributed to Python 3.8 so
+# once loky drops support for Python 3.7 it might be possible to stop
+# maintaining this loky-specific fork. As a consequence, it might also be
+# possible to stop maintaining the loky.backend.synchronize fork of
+# multiprocessing.synchronize.
+
+#
+# On Unix we run a server process which keeps track of unlinked
+# resources. The server ignores SIGINT and SIGTERM and reads from a
+# pipe. The resource_tracker implements a reference counting scheme: each time
+# a Python process anticipates the shared usage of a resource by another
+# process, it signals the resource_tracker of this shared usage, and in return,
+# the resource_tracker increments the resource's reference count by 1.
+# Similarly, when access to a resource is closed by a Python process, the
+# process notifies the resource_tracker by asking it to decrement the
+# resource's reference count by 1. When the reference count drops to 0, the
+# resource_tracker attempts to clean up the underlying resource.
+
+# Finally, every other process connected to the resource tracker has a copy of
+# the writable end of the pipe used to communicate with it, so the resource
+# tracker gets EOF when all other processes have exited. Then the
+# resource_tracker process unlinks any remaining leaked resources (with
+# reference count above 0)
+
+# For semaphores, this is important because the system only supports a limited
+# number of named semaphores, and they will not be automatically removed till
+# the next reboot. Without this resource tracker process, "killall python"
+# would probably leave unlinked semaphores.
+
+# Note that this behavior differs from CPython's resource_tracker, which only
+# implements list of shared resources, and not a proper refcounting scheme.
+# Also, CPython's resource tracker will only attempt to cleanup those shared
+# resources once all procsses connected to the resouce tracker have exited.
+
+
+import os
+import shutil
+import sys
+import signal
+import warnings
+import threading
+from _multiprocessing import sem_unlink
+from multiprocessing import util
+
+from . import spawn
+
+if sys.platform == "win32":
+ import _winapi
+ import msvcrt
+ from multiprocessing.reduction import duplicate
+
+
+__all__ = ['ensure_running', 'register', 'unregister']
+
+_HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask')
+_IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM)
+
+_CLEANUP_FUNCS = {
+ 'folder': shutil.rmtree,
+ 'file': os.unlink
+}
+
+if os.name == "posix":
+ _CLEANUP_FUNCS['semlock'] = sem_unlink
+
+
+VERBOSE = False
+
+
+class ResourceTracker:
+
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._fd = None
+ self._pid = None
+
+ def getfd(self):
+ self.ensure_running()
+ return self._fd
+
+ def ensure_running(self):
+ '''Make sure that resource tracker process is running.
+
+ This can be run from any process. Usually a child process will use
+ the resource created by its parent.'''
+ with self._lock:
+ if self._fd is not None:
+ # resource tracker was launched before, is it still running?
+ if self._check_alive():
+ # => still alive
+ return
+ # => dead, launch it again
+ os.close(self._fd)
+ if os.name == "posix":
+ try:
+ # At this point, the resource_tracker process has been
+ # killed or crashed. Let's remove the process entry
+ # from the process table to avoid zombie processes.
+ os.waitpid(self._pid, 0)
+ except OSError:
+ # The process was terminated or is a child from an
+ # ancestor of the current process.
+ pass
+ self._fd = None
+ self._pid = None
+
+ warnings.warn('resource_tracker: process died unexpectedly, '
+ 'relaunching. Some folders/sempahores might '
+ 'leak.')
+
+ fds_to_pass = []
+ try:
+ fds_to_pass.append(sys.stderr.fileno())
+ except Exception:
+ pass
+
+ r, w = os.pipe()
+ if sys.platform == "win32":
+ _r = duplicate(msvcrt.get_osfhandle(r), inheritable=True)
+ os.close(r)
+ r = _r
+
+ cmd = f'from {main.__module__} import main; main({r}, {VERBOSE})'
+ try:
+ fds_to_pass.append(r)
+ # process will out live us, so no need to wait on pid
+ exe = spawn.get_executable()
+ args = [exe, *util._args_from_interpreter_flags(), '-c', cmd]
+ util.debug(f"launching resource tracker: {args}")
+ # bpo-33613: Register a signal mask that will block the
+ # signals. This signal mask will be inherited by the child
+ # that is going to be spawned and will protect the child from a
+ # race condition that can make the child die before it
+ # registers signal handlers for SIGINT and SIGTERM. The mask is
+ # unregistered after spawning the child.
+ try:
+ if _HAVE_SIGMASK:
+ signal.pthread_sigmask(signal.SIG_BLOCK,
+ _IGNORED_SIGNALS)
+ pid = spawnv_passfds(exe, args, fds_to_pass)
+ finally:
+ if _HAVE_SIGMASK:
+ signal.pthread_sigmask(signal.SIG_UNBLOCK,
+ _IGNORED_SIGNALS)
+ except BaseException:
+ os.close(w)
+ raise
+ else:
+ self._fd = w
+ self._pid = pid
+ finally:
+ if sys.platform == "win32":
+ _winapi.CloseHandle(r)
+ else:
+ os.close(r)
+
+ def _check_alive(self):
+ '''Check for the existence of the resource tracker process.'''
+ try:
+ self._send('PROBE', '', '')
+ except BrokenPipeError:
+ return False
+ else:
+ return True
+
+ def register(self, name, rtype):
+ '''Register a named resource, and increment its refcount.'''
+ self.ensure_running()
+ self._send('REGISTER', name, rtype)
+
+ def unregister(self, name, rtype):
+ '''Unregister a named resource with resource tracker.'''
+ self.ensure_running()
+ self._send('UNREGISTER', name, rtype)
+
+ def maybe_unlink(self, name, rtype):
+ '''Decrement the refcount of a resource, and delete it if it hits 0'''
+ self.ensure_running()
+ self._send("MAYBE_UNLINK", name, rtype)
+
+ def _send(self, cmd, name, rtype):
+ if len(name) > 512:
+ # posix guarantees that writes to a pipe of less than PIPE_BUF
+ # bytes are atomic, and that PIPE_BUF >= 512
+ raise ValueError('name too long')
+ msg = f'{cmd}:{name}:{rtype}\n'.encode('ascii')
+ nbytes = os.write(self._fd, msg)
+ assert nbytes == len(msg)
+
+
+_resource_tracker = ResourceTracker()
+ensure_running = _resource_tracker.ensure_running
+register = _resource_tracker.register
+maybe_unlink = _resource_tracker.maybe_unlink
+unregister = _resource_tracker.unregister
+getfd = _resource_tracker.getfd
+
+
+def main(fd, verbose=0):
+ '''Run resource tracker.'''
+ # protect the process from ^C and "killall python" etc
+ if verbose:
+ util.log_to_stderr(level=util.DEBUG)
+
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
+
+ if _HAVE_SIGMASK:
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
+
+ for f in (sys.stdin, sys.stdout):
+ try:
+ f.close()
+ except Exception:
+ pass
+
+ if verbose:
+ util.debug("Main resource tracker is running")
+
+ registry = {rtype: {} for rtype in _CLEANUP_FUNCS.keys()}
+ try:
+ # keep track of registered/unregistered resources
+ if sys.platform == "win32":
+ fd = msvcrt.open_osfhandle(fd, os.O_RDONLY)
+ with open(fd, 'rb') as f:
+ while True:
+ line = f.readline()
+ if line == b'': # EOF
+ break
+ try:
+ splitted = line.strip().decode('ascii').split(':')
+ # name can potentially contain separator symbols (for
+ # instance folders on Windows)
+ cmd, name, rtype = (
+ splitted[0], ':'.join(splitted[1:-1]), splitted[-1])
+
+ if cmd == 'PROBE':
+ continue
+
+ if rtype not in _CLEANUP_FUNCS:
+ raise ValueError(
+ f'Cannot register {name} for automatic cleanup: '
+ f'unknown resource type ({rtype}). Resource type '
+ 'should be one of the following: '
+ f'{list(_CLEANUP_FUNCS.keys())}'
+ )
+
+ if cmd == 'REGISTER':
+ if name not in registry[rtype]:
+ registry[rtype][name] = 1
+ else:
+ registry[rtype][name] += 1
+
+ if verbose:
+ util.debug(
+ "[ResourceTracker] incremented refcount of "
+ f"{rtype} {name} "
+ f"(current {registry[rtype][name]})"
+ )
+ elif cmd == 'UNREGISTER':
+ del registry[rtype][name]
+ if verbose:
+ util.debug(
+ f"[ResourceTracker] unregister {name} {rtype}: "
+ f"registry({len(registry)})"
+ )
+ elif cmd == 'MAYBE_UNLINK':
+ registry[rtype][name] -= 1
+ if verbose:
+ util.debug(
+ "[ResourceTracker] decremented refcount of "
+ f"{rtype} {name} "
+ f"(current {registry[rtype][name]})"
+ )
+
+ if registry[rtype][name] == 0:
+ del registry[rtype][name]
+ try:
+ if verbose:
+ util.debug(
+ f"[ResourceTracker] unlink {name}"
+ )
+ _CLEANUP_FUNCS[rtype](name)
+ except Exception as e:
+ warnings.warn(
+ f'resource_tracker: {name}: {e!r}')
+
+ else:
+ raise RuntimeError(f'unrecognized command {cmd!r}')
+ except BaseException:
+ try:
+ sys.excepthook(*sys.exc_info())
+ except BaseException:
+ pass
+ finally:
+ # all processes have terminated; cleanup any remaining resources
+ def _unlink_resources(rtype_registry, rtype):
+ if rtype_registry:
+ try:
+ warnings.warn(
+ 'resource_tracker: There appear to be '
+ f'{len(rtype_registry)} leaked {rtype} objects to '
+ 'clean up at shutdown'
+ )
+ except Exception:
+ pass
+ for name in rtype_registry:
+ # For some reason the process which created and registered this
+ # resource has failed to unregister it. Presumably it has
+ # died. We therefore clean it up.
+ try:
+ _CLEANUP_FUNCS[rtype](name)
+ if verbose:
+ util.debug(f"[ResourceTracker] unlink {name}")
+ except Exception as e:
+ warnings.warn(f'resource_tracker: {name}: {e!r}')
+
+ for rtype, rtype_registry in registry.items():
+ if rtype == "folder":
+ continue
+ else:
+ _unlink_resources(rtype_registry, rtype)
+
+ # The default cleanup routine for folders deletes everything inside
+ # those folders recursively, which can include other resources tracked
+ # by the resource tracker). To limit the risk of the resource tracker
+ # attempting to delete twice a resource (once as part of a tracked
+ # folder, and once as a resource), we delete the folders after all
+ # other resource types.
+ if "folder" in registry:
+ _unlink_resources(registry["folder"], "folder")
+
+ if verbose:
+ util.debug("resource tracker shut down")
+
+
+#
+# Start a program with only specified fds kept open
+#
+
+def spawnv_passfds(path, args, passfds):
+ passfds = sorted(passfds)
+ if sys.platform != "win32":
+ errpipe_read, errpipe_write = os.pipe()
+ try:
+ from .reduction import _mk_inheritable
+ from .fork_exec import fork_exec
+ _pass = [_mk_inheritable(fd) for fd in passfds]
+ return fork_exec(args, _pass)
+ finally:
+ os.close(errpipe_read)
+ os.close(errpipe_write)
+ else:
+ cmd = ' '.join(f'"{x}"' for x in args)
+ try:
+ _, ht, pid, _ = _winapi.CreateProcess(
+ path, cmd, None, None, True, 0, None, None, None)
+ _winapi.CloseHandle(ht)
+ except BaseException:
+ pass
+ return pid
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/spawn.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/spawn.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a9cc2dd1aa64ef73d7c243c2671c854930c6dc3
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/spawn.py
@@ -0,0 +1,242 @@
+###############################################################################
+# Prepares and processes the data to setup the new process environment
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from multiprocessing/spawn.py (17/02/2017)
+# * Improve logging data
+#
+import os
+import sys
+import runpy
+import types
+from multiprocessing import process, util
+
+
+if sys.platform != 'win32':
+ WINEXE = False
+ WINSERVICE = False
+else:
+ import msvcrt
+ from multiprocessing.reduction import duplicate
+ WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
+ WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
+
+if WINSERVICE:
+ _python_exe = os.path.join(sys.exec_prefix, 'python.exe')
+else:
+ _python_exe = sys.executable
+
+
+def get_executable():
+ return _python_exe
+
+
+def _check_not_importing_main():
+ if getattr(process.current_process(), '_inheriting', False):
+ raise RuntimeError('''
+ An attempt has been made to start a new process before the
+ current process has finished its bootstrapping phase.
+
+ This probably means that you are not using fork to start your
+ child processes and you have forgotten to use the proper idiom
+ in the main module:
+
+ if __name__ == '__main__':
+ freeze_support()
+ ...
+
+ The "freeze_support()" line can be omitted if the program
+ is not going to be frozen to produce an executable.''')
+
+
+def get_preparation_data(name, init_main_module=True):
+ '''
+ Return info about parent needed by child to unpickle process object
+ '''
+ _check_not_importing_main()
+ d = dict(
+ log_to_stderr=util._log_to_stderr,
+ authkey=bytes(process.current_process().authkey),
+ name=name,
+ sys_argv=sys.argv,
+ orig_dir=process.ORIGINAL_DIR,
+ dir=os.getcwd()
+ )
+
+ # Send sys_path and make sure the current directory will not be changed
+ d['sys_path'] = [p if p != '' else process.ORIGINAL_DIR for p in sys.path]
+
+ # Make sure to pass the information if the multiprocessing logger is active
+ if util._logger is not None:
+ d['log_level'] = util._logger.getEffectiveLevel()
+ if util._logger.handlers:
+ h = util._logger.handlers[0]
+ d['log_fmt'] = h.formatter._fmt
+
+ # Tell the child how to communicate with the resource_tracker
+ from .resource_tracker import _resource_tracker
+ _resource_tracker.ensure_running()
+ d["tracker_args"] = {"pid": _resource_tracker._pid}
+ if sys.platform == "win32":
+ child_w = duplicate(
+ msvcrt.get_osfhandle(_resource_tracker._fd), inheritable=True)
+ d["tracker_args"]["fh"] = child_w
+ else:
+ d["tracker_args"]["fd"] = _resource_tracker._fd
+
+ if sys.version_info >= (3, 8) and os.name == 'posix':
+ # joblib/loky#242: allow loky processes to retrieve the resource
+ # tracker of their parent in case the child processes depickles
+ # shared_memory objects, that are still tracked by multiprocessing's
+ # resource_tracker by default.
+ # XXX: this is a workaround that may be error prone: in the future, it
+ # would be better to have loky subclass multiprocessing's shared_memory
+ # to force registration of shared_memory segments via loky's
+ # resource_tracker.
+ from multiprocessing.resource_tracker import (
+ _resource_tracker as mp_resource_tracker
+ )
+ # multiprocessing's resource_tracker must be running before loky
+ # process is created (othewise the child won't be able to use it if it
+ # is created later on)
+ mp_resource_tracker.ensure_running()
+ d["mp_tracker_args"] = {
+ 'fd': mp_resource_tracker._fd, 'pid': mp_resource_tracker._pid
+ }
+
+ # Figure out whether to initialise main in the subprocess as a module
+ # or through direct execution (or to leave it alone entirely)
+ if init_main_module:
+ main_module = sys.modules['__main__']
+ try:
+ main_mod_name = getattr(main_module.__spec__, "name", None)
+ except BaseException:
+ main_mod_name = None
+ if main_mod_name is not None:
+ d['init_main_from_name'] = main_mod_name
+ elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
+ main_path = getattr(main_module, '__file__', None)
+ if main_path is not None:
+ if (not os.path.isabs(main_path) and
+ process.ORIGINAL_DIR is not None):
+ main_path = os.path.join(process.ORIGINAL_DIR, main_path)
+ d['init_main_from_path'] = os.path.normpath(main_path)
+
+ return d
+
+
+#
+# Prepare current process
+#
+old_main_modules = []
+
+
+def prepare(data):
+ '''
+ Try to get current process ready to unpickle process object
+ '''
+ if 'name' in data:
+ process.current_process().name = data['name']
+
+ if 'authkey' in data:
+ process.current_process().authkey = data['authkey']
+
+ if 'log_to_stderr' in data and data['log_to_stderr']:
+ util.log_to_stderr()
+
+ if 'log_level' in data:
+ util.get_logger().setLevel(data['log_level'])
+
+ if 'log_fmt' in data:
+ import logging
+ util.get_logger().handlers[0].setFormatter(
+ logging.Formatter(data['log_fmt'])
+ )
+
+ if 'sys_path' in data:
+ sys.path = data['sys_path']
+
+ if 'sys_argv' in data:
+ sys.argv = data['sys_argv']
+
+ if 'dir' in data:
+ os.chdir(data['dir'])
+
+ if 'orig_dir' in data:
+ process.ORIGINAL_DIR = data['orig_dir']
+
+ if 'mp_tracker_args' in data:
+ from multiprocessing.resource_tracker import (
+ _resource_tracker as mp_resource_tracker
+ )
+ mp_resource_tracker._fd = data['mp_tracker_args']['fd']
+ mp_resource_tracker._pid = data['mp_tracker_args']['pid']
+ if 'tracker_args' in data:
+ from .resource_tracker import _resource_tracker
+ _resource_tracker._pid = data["tracker_args"]['pid']
+ if sys.platform == 'win32':
+ handle = data["tracker_args"]["fh"]
+ _resource_tracker._fd = msvcrt.open_osfhandle(handle, 0)
+ else:
+ _resource_tracker._fd = data["tracker_args"]["fd"]
+
+ if 'init_main_from_name' in data:
+ _fixup_main_from_name(data['init_main_from_name'])
+ elif 'init_main_from_path' in data:
+ _fixup_main_from_path(data['init_main_from_path'])
+
+
+# Multiprocessing module helpers to fix up the main module in
+# spawned subprocesses
+def _fixup_main_from_name(mod_name):
+ # __main__.py files for packages, directories, zip archives, etc, run
+ # their "main only" code unconditionally, so we don't even try to
+ # populate anything in __main__, nor do we make any changes to
+ # __main__ attributes
+ current_main = sys.modules['__main__']
+ if mod_name == "__main__" or mod_name.endswith(".__main__"):
+ return
+
+ # If this process was forked, __main__ may already be populated
+ if getattr(current_main.__spec__, "name", None) == mod_name:
+ return
+
+ # Otherwise, __main__ may contain some non-main code where we need to
+ # support unpickling it properly. We rerun it as __mp_main__ and make
+ # the normal __main__ an alias to that
+ old_main_modules.append(current_main)
+ main_module = types.ModuleType("__mp_main__")
+ main_content = runpy.run_module(mod_name,
+ run_name="__mp_main__",
+ alter_sys=True)
+ main_module.__dict__.update(main_content)
+ sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
+
+
+def _fixup_main_from_path(main_path):
+ # If this process was forked, __main__ may already be populated
+ current_main = sys.modules['__main__']
+
+ # Unfortunately, the main ipython launch script historically had no
+ # "if __name__ == '__main__'" guard, so we work around that
+ # by treating it like a __main__.py file
+ # See https://github.com/ipython/ipython/issues/4698
+ main_name = os.path.splitext(os.path.basename(main_path))[0]
+ if main_name == 'ipython':
+ return
+
+ # Otherwise, if __file__ already has the setting we expect,
+ # there's nothing more to do
+ if getattr(current_main, '__file__', None) == main_path:
+ return
+
+ # If the parent process has sent a path through rather than a module
+ # name we assume it is an executable script that may contain
+ # non-main code that needs to be executed
+ old_main_modules.append(current_main)
+ main_module = types.ModuleType("__mp_main__")
+ main_content = runpy.run_path(main_path,
+ run_name="__mp_main__")
+ main_module.__dict__.update(main_content)
+ sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/synchronize.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/synchronize.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9518a8803507a1343db133d606bfcfeabaa9388
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/synchronize.py
@@ -0,0 +1,391 @@
+###############################################################################
+# Synchronization primitives based on our SemLock implementation
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from multiprocessing/synchronize.py (17/02/2017)
+# * Remove ctx argument for compatibility reason
+# * Registers a cleanup function with the loky resource_tracker to remove the
+# semaphore when the process dies instead.
+#
+# TODO: investigate which Python version is required to be able to use
+# multiprocessing.resource_tracker and therefore multiprocessing.synchronize
+# instead of a loky-specific fork.
+
+import os
+import sys
+import tempfile
+import threading
+import _multiprocessing
+from time import time as _time
+from multiprocessing import process, util
+from multiprocessing.context import assert_spawning
+
+from . import resource_tracker
+
+__all__ = [
+ 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event'
+ ]
+# Try to import the mp.synchronize module cleanly, if it fails
+# raise ImportError for platforms lacking a working sem_open implementation.
+# See issue 3770
+try:
+ from _multiprocessing import SemLock as _SemLock
+ from _multiprocessing import sem_unlink
+except ImportError:
+ raise ImportError("This platform lacks a functioning sem_open" +
+ " implementation, therefore, the required" +
+ " synchronization primitives needed will not" +
+ " function, see issue 3770.")
+
+#
+# Constants
+#
+
+RECURSIVE_MUTEX, SEMAPHORE = range(2)
+SEM_VALUE_MAX = _multiprocessing.SemLock.SEM_VALUE_MAX
+
+
+#
+# Base class for semaphores and mutexes; wraps `_multiprocessing.SemLock`
+#
+
+class SemLock:
+
+ _rand = tempfile._RandomNameSequence()
+
+ def __init__(self, kind, value, maxvalue, name=None):
+ # unlink_now is only used on win32 or when we are using fork.
+ unlink_now = False
+ if name is None:
+ # Try to find an unused name for the SemLock instance.
+ for _ in range(100):
+ try:
+ self._semlock = _SemLock(
+ kind, value, maxvalue, SemLock._make_name(), unlink_now
+ )
+ except FileExistsError: # pragma: no cover
+ pass
+ else:
+ break
+ else: # pragma: no cover
+ raise FileExistsError('cannot find name for semaphore')
+ else:
+ self._semlock = _SemLock(
+ kind, value, maxvalue, name, unlink_now
+ )
+ self.name = name
+ util.debug(
+ f'created semlock with handle {self._semlock.handle} and name '
+ f'"{self.name}"'
+ )
+
+ self._make_methods()
+
+ def _after_fork(obj):
+ obj._semlock._after_fork()
+
+ util.register_after_fork(self, _after_fork)
+
+ # When the object is garbage collected or the
+ # process shuts down we unlink the semaphore name
+ resource_tracker.register(self._semlock.name, "semlock")
+ util.Finalize(self, SemLock._cleanup, (self._semlock.name,),
+ exitpriority=0)
+
+ @staticmethod
+ def _cleanup(name):
+ try:
+ sem_unlink(name)
+ except FileNotFoundError:
+ # Already unlinked, possibly by user code: ignore and make sure to
+ # unregister the semaphore from the resource tracker.
+ pass
+ finally:
+ resource_tracker.unregister(name, "semlock")
+
+ def _make_methods(self):
+ self.acquire = self._semlock.acquire
+ self.release = self._semlock.release
+
+ def __enter__(self):
+ return self._semlock.acquire()
+
+ def __exit__(self, *args):
+ return self._semlock.release()
+
+ def __getstate__(self):
+ assert_spawning(self)
+ sl = self._semlock
+ h = sl.handle
+ return (h, sl.kind, sl.maxvalue, sl.name)
+
+ def __setstate__(self, state):
+ self._semlock = _SemLock._rebuild(*state)
+ util.debug(
+ f'recreated blocker with handle {state[0]!r} and name "{state[3]}"'
+ )
+ self._make_methods()
+
+ @staticmethod
+ def _make_name():
+ # OSX does not support long names for semaphores
+ return f'/loky-{os.getpid()}-{next(SemLock._rand)}'
+
+
+#
+# Semaphore
+#
+
+class Semaphore(SemLock):
+
+ def __init__(self, value=1):
+ SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX)
+
+ def get_value(self):
+ if sys.platform == 'darwin':
+ raise NotImplementedError("OSX does not implement sem_getvalue")
+ return self._semlock._get_value()
+
+ def __repr__(self):
+ try:
+ value = self._semlock._get_value()
+ except Exception:
+ value = 'unknown'
+ return f'<{self.__class__.__name__}(value={value})>'
+
+
+#
+# Bounded semaphore
+#
+
+class BoundedSemaphore(Semaphore):
+
+ def __init__(self, value=1):
+ SemLock.__init__(self, SEMAPHORE, value, value)
+
+ def __repr__(self):
+ try:
+ value = self._semlock._get_value()
+ except Exception:
+ value = 'unknown'
+ return (
+ f'<{self.__class__.__name__}(value={value}, '
+ f'maxvalue={self._semlock.maxvalue})>'
+ )
+
+
+#
+# Non-recursive lock
+#
+
+class Lock(SemLock):
+
+ def __init__(self):
+ super().__init__(SEMAPHORE, 1, 1)
+
+ def __repr__(self):
+ try:
+ if self._semlock._is_mine():
+ name = process.current_process().name
+ if threading.current_thread().name != 'MainThread':
+ name = f'{name}|{threading.current_thread().name}'
+ elif self._semlock._get_value() == 1:
+ name = 'None'
+ elif self._semlock._count() > 0:
+ name = 'SomeOtherThread'
+ else:
+ name = 'SomeOtherProcess'
+ except Exception:
+ name = 'unknown'
+ return f'<{self.__class__.__name__}(owner={name})>'
+
+
+#
+# Recursive lock
+#
+
+class RLock(SemLock):
+
+ def __init__(self):
+ super().__init__(RECURSIVE_MUTEX, 1, 1)
+
+ def __repr__(self):
+ try:
+ if self._semlock._is_mine():
+ name = process.current_process().name
+ if threading.current_thread().name != 'MainThread':
+ name = f'{name}|{threading.current_thread().name}'
+ count = self._semlock._count()
+ elif self._semlock._get_value() == 1:
+ name, count = 'None', 0
+ elif self._semlock._count() > 0:
+ name, count = 'SomeOtherThread', 'nonzero'
+ else:
+ name, count = 'SomeOtherProcess', 'nonzero'
+ except Exception:
+ name, count = 'unknown', 'unknown'
+ return f'<{self.__class__.__name__}({name}, {count})>'
+
+
+#
+# Condition variable
+#
+
+class Condition:
+
+ def __init__(self, lock=None):
+ self._lock = lock or RLock()
+ self._sleeping_count = Semaphore(0)
+ self._woken_count = Semaphore(0)
+ self._wait_semaphore = Semaphore(0)
+ self._make_methods()
+
+ def __getstate__(self):
+ assert_spawning(self)
+ return (self._lock, self._sleeping_count,
+ self._woken_count, self._wait_semaphore)
+
+ def __setstate__(self, state):
+ (self._lock, self._sleeping_count,
+ self._woken_count, self._wait_semaphore) = state
+ self._make_methods()
+
+ def __enter__(self):
+ return self._lock.__enter__()
+
+ def __exit__(self, *args):
+ return self._lock.__exit__(*args)
+
+ def _make_methods(self):
+ self.acquire = self._lock.acquire
+ self.release = self._lock.release
+
+ def __repr__(self):
+ try:
+ num_waiters = (self._sleeping_count._semlock._get_value() -
+ self._woken_count._semlock._get_value())
+ except Exception:
+ num_waiters = 'unknown'
+ return f'<{self.__class__.__name__}({self._lock}, {num_waiters})>'
+
+ def wait(self, timeout=None):
+ assert self._lock._semlock._is_mine(), \
+ 'must acquire() condition before using wait()'
+
+ # indicate that this thread is going to sleep
+ self._sleeping_count.release()
+
+ # release lock
+ count = self._lock._semlock._count()
+ for _ in range(count):
+ self._lock.release()
+
+ try:
+ # wait for notification or timeout
+ return self._wait_semaphore.acquire(True, timeout)
+ finally:
+ # indicate that this thread has woken
+ self._woken_count.release()
+
+ # reacquire lock
+ for _ in range(count):
+ self._lock.acquire()
+
+ def notify(self):
+ assert self._lock._semlock._is_mine(), 'lock is not owned'
+ assert not self._wait_semaphore.acquire(False)
+
+ # to take account of timeouts since last notify() we subtract
+ # woken_count from sleeping_count and rezero woken_count
+ while self._woken_count.acquire(False):
+ res = self._sleeping_count.acquire(False)
+ assert res
+
+ if self._sleeping_count.acquire(False): # try grabbing a sleeper
+ self._wait_semaphore.release() # wake up one sleeper
+ self._woken_count.acquire() # wait for the sleeper to wake
+
+ # rezero _wait_semaphore in case a timeout just happened
+ self._wait_semaphore.acquire(False)
+
+ def notify_all(self):
+ assert self._lock._semlock._is_mine(), 'lock is not owned'
+ assert not self._wait_semaphore.acquire(False)
+
+ # to take account of timeouts since last notify*() we subtract
+ # woken_count from sleeping_count and rezero woken_count
+ while self._woken_count.acquire(False):
+ res = self._sleeping_count.acquire(False)
+ assert res
+
+ sleepers = 0
+ while self._sleeping_count.acquire(False):
+ self._wait_semaphore.release() # wake up one sleeper
+ sleepers += 1
+
+ if sleepers:
+ for _ in range(sleepers):
+ self._woken_count.acquire() # wait for a sleeper to wake
+
+ # rezero wait_semaphore in case some timeouts just happened
+ while self._wait_semaphore.acquire(False):
+ pass
+
+ def wait_for(self, predicate, timeout=None):
+ result = predicate()
+ if result:
+ return result
+ if timeout is not None:
+ endtime = _time() + timeout
+ else:
+ endtime = None
+ waittime = None
+ while not result:
+ if endtime is not None:
+ waittime = endtime - _time()
+ if waittime <= 0:
+ break
+ self.wait(waittime)
+ result = predicate()
+ return result
+
+
+#
+# Event
+#
+
+class Event:
+
+ def __init__(self):
+ self._cond = Condition(Lock())
+ self._flag = Semaphore(0)
+
+ def is_set(self):
+ with self._cond:
+ if self._flag.acquire(False):
+ self._flag.release()
+ return True
+ return False
+
+ def set(self):
+ with self._cond:
+ self._flag.acquire(False)
+ self._flag.release()
+ self._cond.notify_all()
+
+ def clear(self):
+ with self._cond:
+ self._flag.acquire(False)
+
+ def wait(self, timeout=None):
+ with self._cond:
+ if self._flag.acquire(False):
+ self._flag.release()
+ else:
+ self._cond.wait(timeout)
+
+ if self._flag.acquire(False):
+ self._flag.release()
+ return True
+ return False
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/backend/utils.py b/runtime/Lib/site-packages/joblib/externals/loky/backend/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2956614e4b5883e9685d74ee3dfe309d028f0269
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/backend/utils.py
@@ -0,0 +1,174 @@
+import os
+import sys
+import time
+import errno
+import signal
+import warnings
+import subprocess
+import traceback
+try:
+ import psutil
+except ImportError:
+ psutil = None
+
+
+def kill_process_tree(process, use_psutil=True):
+ """Terminate process and its descendants with SIGKILL"""
+ if use_psutil and psutil is not None:
+ _kill_process_tree_with_psutil(process)
+ else:
+ _kill_process_tree_without_psutil(process)
+
+
+def recursive_terminate(process, use_psutil=True):
+ warnings.warn(
+ "recursive_terminate is deprecated in loky 3.2, use kill_process_tree"
+ "instead",
+ DeprecationWarning,
+ )
+ kill_process_tree(process, use_psutil=use_psutil)
+
+
+def _kill_process_tree_with_psutil(process):
+ try:
+ descendants = psutil.Process(process.pid).children(recursive=True)
+ except psutil.NoSuchProcess:
+ return
+
+ # Kill the descendants in reverse order to avoid killing the parents before
+ # the descendant in cases where there are more processes nested.
+ for descendant in descendants[::-1]:
+ try:
+ descendant.kill()
+ except psutil.NoSuchProcess:
+ pass
+
+ try:
+ psutil.Process(process.pid).kill()
+ except psutil.NoSuchProcess:
+ pass
+ process.join()
+
+
+def _kill_process_tree_without_psutil(process):
+ """Terminate a process and its descendants."""
+ try:
+ if sys.platform == "win32":
+ _windows_taskkill_process_tree(process.pid)
+ else:
+ _posix_recursive_kill(process.pid)
+ except Exception: # pragma: no cover
+ details = traceback.format_exc()
+ warnings.warn(
+ "Failed to kill subprocesses on this platform. Please install"
+ "psutil: https://github.com/giampaolo/psutil\n"
+ f"Details:\n{details}"
+ )
+ # In case we cannot introspect or kill the descendants, we fall back to
+ # only killing the main process.
+ #
+ # Note: on Windows, process.kill() is an alias for process.terminate()
+ # which in turns calls the Win32 API function TerminateProcess().
+ process.kill()
+ process.join()
+
+
+def _windows_taskkill_process_tree(pid):
+ # On windows, the taskkill function with option `/T` terminate a given
+ # process pid and its children.
+ try:
+ subprocess.check_output(
+ ["taskkill", "/F", "/T", "/PID", str(pid)], stderr=None
+ )
+ except subprocess.CalledProcessError as e:
+ # In Windows, taskkill returns 128, 255 for no process found.
+ if e.returncode not in [128, 255]:
+ # Let's raise to let the caller log the error details in a
+ # warning and only kill the root process.
+ raise # pragma: no cover
+
+
+def _kill(pid):
+ # Not all systems (e.g. Windows) have a SIGKILL, but the C specification
+ # mandates a SIGTERM signal. While Windows is handled specifically above,
+ # let's try to be safe for other hypothetic platforms that only have
+ # SIGTERM without SIGKILL.
+ kill_signal = getattr(signal, 'SIGKILL', signal.SIGTERM)
+ try:
+ os.kill(pid, kill_signal)
+ except OSError as e:
+ # if OSError is raised with [Errno 3] no such process, the process
+ # is already terminated, else, raise the error and let the top
+ # level function raise a warning and retry to kill the process.
+ if e.errno != errno.ESRCH:
+ raise # pragma: no cover
+
+
+def _posix_recursive_kill(pid):
+ """Recursively kill the descendants of a process before killing it."""
+ try:
+ children_pids = subprocess.check_output(
+ ["pgrep", "-P", str(pid)], stderr=None, text=True
+ )
+ except subprocess.CalledProcessError as e:
+ # `ps` returns 1 when no child process has been found
+ if e.returncode == 1:
+ children_pids = ''
+ else:
+ raise # pragma: no cover
+
+ # Decode the result, split the cpid and remove the trailing line
+ for cpid in children_pids.splitlines():
+ cpid = int(cpid)
+ _posix_recursive_kill(cpid)
+
+ _kill(pid)
+
+
+def get_exitcodes_terminated_worker(processes):
+ """Return a formated string with the exitcodes of terminated workers.
+
+ If necessary, wait (up to .25s) for the system to correctly set the
+ exitcode of one terminated worker.
+ """
+ patience = 5
+
+ # Catch the exitcode of the terminated workers. There should at least be
+ # one. If not, wait a bit for the system to correctly set the exitcode of
+ # the terminated worker.
+ exitcodes = [p.exitcode for p in list(processes.values())
+ if p.exitcode is not None]
+ while not exitcodes and patience > 0:
+ patience -= 1
+ exitcodes = [p.exitcode for p in list(processes.values())
+ if p.exitcode is not None]
+ time.sleep(.05)
+
+ return _format_exitcodes(exitcodes)
+
+
+def _format_exitcodes(exitcodes):
+ """Format a list of exit code with names of the signals if possible"""
+ str_exitcodes = [f"{_get_exitcode_name(e)}({e})"
+ for e in exitcodes if e is not None]
+ return "{" + ", ".join(str_exitcodes) + "}"
+
+
+def _get_exitcode_name(exitcode):
+ if sys.platform == "win32":
+ # The exitcode are unreliable on windows (see bpo-31863).
+ # For this case, return UNKNOWN
+ return "UNKNOWN"
+
+ if exitcode < 0:
+ try:
+ import signal
+ return signal.Signals(-exitcode).name
+ except ValueError:
+ return "UNKNOWN"
+ elif exitcode != 255:
+ # The exitcode are unreliable on forkserver were 255 is always returned
+ # (see bpo-30589). For this case, return UNKNOWN
+ return "EXIT"
+
+ return "UNKNOWN"
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/cloudpickle_wrapper.py b/runtime/Lib/site-packages/joblib/externals/loky/cloudpickle_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b187e84eecfdc94e8301619a41194bf2a4bcc54
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/cloudpickle_wrapper.py
@@ -0,0 +1,100 @@
+import inspect
+from functools import partial
+from joblib.externals.cloudpickle import dumps, loads
+
+
+WRAP_CACHE = {}
+
+
+class CloudpickledObjectWrapper:
+ def __init__(self, obj, keep_wrapper=False):
+ self._obj = obj
+ self._keep_wrapper = keep_wrapper
+
+ def __reduce__(self):
+ _pickled_object = dumps(self._obj)
+ if not self._keep_wrapper:
+ return loads, (_pickled_object,)
+
+ return _reconstruct_wrapper, (_pickled_object, self._keep_wrapper)
+
+ def __getattr__(self, attr):
+ # Ensure that the wrapped object can be used seemlessly as the
+ # previous object.
+ if attr not in ['_obj', '_keep_wrapper']:
+ return getattr(self._obj, attr)
+ return getattr(self, attr)
+
+
+# Make sure the wrapped object conserves the callable property
+class CallableObjectWrapper(CloudpickledObjectWrapper):
+
+ def __call__(self, *args, **kwargs):
+ return self._obj(*args, **kwargs)
+
+
+def _wrap_non_picklable_objects(obj, keep_wrapper):
+ if callable(obj):
+ return CallableObjectWrapper(obj, keep_wrapper=keep_wrapper)
+ return CloudpickledObjectWrapper(obj, keep_wrapper=keep_wrapper)
+
+
+def _reconstruct_wrapper(_pickled_object, keep_wrapper):
+ obj = loads(_pickled_object)
+ return _wrap_non_picklable_objects(obj, keep_wrapper)
+
+
+def _wrap_objects_when_needed(obj):
+ # Function to introspect an object and decide if it should be wrapped or
+ # not.
+ need_wrap = "__main__" in getattr(obj, "__module__", "")
+ if isinstance(obj, partial):
+ return partial(
+ _wrap_objects_when_needed(obj.func),
+ *[_wrap_objects_when_needed(a) for a in obj.args],
+ **{k: _wrap_objects_when_needed(v)
+ for k, v in obj.keywords.items()}
+ )
+ if callable(obj):
+ # Need wrap if the object is a function defined in a local scope of
+ # another function.
+ func_code = getattr(obj, "__code__", "")
+ need_wrap |= getattr(func_code, "co_flags", 0) & inspect.CO_NESTED
+
+ # Need wrap if the obj is a lambda expression
+ func_name = getattr(obj, "__name__", "")
+ need_wrap |= "" in func_name
+
+ if not need_wrap:
+ return obj
+
+ wrapped_obj = WRAP_CACHE.get(obj)
+ if wrapped_obj is None:
+ wrapped_obj = _wrap_non_picklable_objects(obj, keep_wrapper=False)
+ WRAP_CACHE[obj] = wrapped_obj
+ return wrapped_obj
+
+
+def wrap_non_picklable_objects(obj, keep_wrapper=True):
+ """Wrapper for non-picklable object to use cloudpickle to serialize them.
+
+ Note that this wrapper tends to slow down the serialization process as it
+ is done with cloudpickle which is typically slower compared to pickle. The
+ proper way to solve serialization issues is to avoid defining functions and
+ objects in the main scripts and to implement __reduce__ functions for
+ complex classes.
+ """
+ # If obj is a class, create a CloudpickledClassWrapper which instantiates
+ # the object internally and wrap it directly in a CloudpickledObjectWrapper
+ if inspect.isclass(obj):
+ class CloudpickledClassWrapper(CloudpickledObjectWrapper):
+ def __init__(self, *args, **kwargs):
+ self._obj = obj(*args, **kwargs)
+ self._keep_wrapper = keep_wrapper
+
+ CloudpickledClassWrapper.__name__ = obj.__name__
+ return CloudpickledClassWrapper
+
+ # If obj is an instance of a class, just wrap it in a regular
+ # CloudpickledObjectWrapper
+ return _wrap_non_picklable_objects(obj, keep_wrapper=keep_wrapper)
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/initializers.py b/runtime/Lib/site-packages/joblib/externals/loky/initializers.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc4b7b17c57019246a6dee739402daeccafbb416
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/initializers.py
@@ -0,0 +1,76 @@
+import warnings
+
+
+def _viztracer_init(init_kwargs):
+ """Initialize viztracer's profiler in worker processes"""
+ from viztracer import VizTracer
+ tracer = VizTracer(**init_kwargs)
+ tracer.register_exit()
+ tracer.start()
+
+
+def _make_viztracer_initializer_and_initargs():
+ try:
+ import viztracer
+ tracer = viztracer.get_tracer()
+ if tracer is not None and getattr(tracer, 'enable', False):
+ # Profiler is active: introspect its configuration to
+ # initialize the workers with the same configuration.
+ return _viztracer_init, (tracer.init_kwargs,)
+ except ImportError:
+ # viztracer is not installed: nothing to do
+ pass
+ except Exception as e:
+ # In case viztracer's API evolve, we do not want to crash loky but
+ # we want to know about it to be able to update loky.
+ warnings.warn(f"Unable to introspect viztracer state: {e}")
+ return None, ()
+
+
+class _ChainedInitializer:
+ """Compound worker initializer
+
+ This is meant to be used in conjunction with _chain_initializers to
+ produce the necessary chained_args list to be passed to __call__.
+ """
+
+ def __init__(self, initializers):
+ self._initializers = initializers
+
+ def __call__(self, *chained_args):
+ for initializer, args in zip(self._initializers, chained_args):
+ initializer(*args)
+
+
+def _chain_initializers(initializer_and_args):
+ """Convenience helper to combine a sequence of initializers.
+
+ If some initializers are None, they are filtered out.
+ """
+ filtered_initializers = []
+ filtered_initargs = []
+ for initializer, initargs in initializer_and_args:
+ if initializer is not None:
+ filtered_initializers.append(initializer)
+ filtered_initargs.append(initargs)
+
+ if not filtered_initializers:
+ return None, ()
+ elif len(filtered_initializers) == 1:
+ return filtered_initializers[0], filtered_initargs[0]
+ else:
+ return _ChainedInitializer(filtered_initializers), filtered_initargs
+
+
+def _prepare_initializer(initializer, initargs):
+ if initializer is not None and not callable(initializer):
+ raise TypeError(
+ f"initializer must be a callable, got: {initializer!r}"
+ )
+
+ # Introspect runtime to determine if we need to propagate the viztracer
+ # profiler information to the workers:
+ return _chain_initializers([
+ (initializer, initargs),
+ _make_viztracer_initializer_and_initargs(),
+ ])
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/process_executor.py b/runtime/Lib/site-packages/joblib/externals/loky/process_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e3e819ce620c18281eeaec82d2aba05e0c97a9e
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/process_executor.py
@@ -0,0 +1,1209 @@
+###############################################################################
+# Re-implementation of the ProcessPoolExecutor more robust to faults
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+# adapted from concurrent/futures/process_pool_executor.py (17/02/2017)
+# * Add an extra management thread to detect executor_manager_thread failures,
+# * Improve the shutdown process to avoid deadlocks,
+# * Add timeout for workers,
+# * More robust pickling process.
+#
+# Copyright 2009 Brian Quinlan. All Rights Reserved.
+# Licensed to PSF under a Contributor Agreement.
+
+"""Implements ProcessPoolExecutor.
+
+The follow diagram and text describe the data-flow through the system:
+
+|======================= In-process =====================|== Out-of-process ==|
+
++----------+ +----------+ +--------+ +-----------+ +---------+
+| | => | Work Ids | | | | Call Q | | Process |
+| | +----------+ | | +-----------+ | Pool |
+| | | ... | | | | ... | +---------+
+| | | 6 | => | | => | 5, call() | => | |
+| | | 7 | | | | ... | | |
+| Process | | ... | | Local | +-----------+ | Process |
+| Pool | +----------+ | Worker | | #1..n |
+| Executor | | Thread | | |
+| | +----------- + | | +-----------+ | |
+| | <=> | Work Items | <=> | | <= | Result Q | <= | |
+| | +------------+ | | +-----------+ | |
+| | | 6: call() | | | | ... | | |
+| | | future | +--------+ | 4, result | | |
+| | | ... | | 3, except | | |
++----------+ +------------+ +-----------+ +---------+
+
+Executor.submit() called:
+- creates a uniquely numbered _WorkItem and adds it to the "Work Items" dict
+- adds the id of the _WorkItem to the "Work Ids" queue
+
+Local worker thread:
+- reads work ids from the "Work Ids" queue and looks up the corresponding
+ WorkItem from the "Work Items" dict: if the work item has been cancelled then
+ it is simply removed from the dict, otherwise it is repackaged as a
+ _CallItem and put in the "Call Q". New _CallItems are put in the "Call Q"
+ until "Call Q" is full. NOTE: the size of the "Call Q" is kept small because
+ calls placed in the "Call Q" can no longer be cancelled with Future.cancel().
+- reads _ResultItems from "Result Q", updates the future stored in the
+ "Work Items" dict and deletes the dict entry
+
+Process #1..n:
+- reads _CallItems from "Call Q", executes the calls, and puts the resulting
+ _ResultItems in "Result Q"
+"""
+
+
+__author__ = 'Thomas Moreau (thomas.moreau.2010@gmail.com)'
+
+
+import os
+import gc
+import sys
+import queue
+import struct
+import weakref
+import warnings
+import itertools
+import traceback
+import threading
+from time import time, sleep
+import multiprocessing as mp
+from functools import partial
+from pickle import PicklingError
+from concurrent.futures import Executor
+from concurrent.futures._base import LOGGER
+from concurrent.futures.process import BrokenProcessPool as _BPPException
+from multiprocessing.connection import wait
+
+from ._base import Future
+from .backend import get_context
+from .backend.context import cpu_count
+from .backend.queues import Queue, SimpleQueue
+from .backend.reduction import set_loky_pickler, get_loky_pickler_name
+from .backend.utils import kill_process_tree, get_exitcodes_terminated_worker
+from .initializers import _prepare_initializer
+
+
+# Mechanism to prevent infinite process spawning. When a worker of a
+# ProcessPoolExecutor nested in MAX_DEPTH Executor tries to create a new
+# Executor, a LokyRecursionError is raised
+MAX_DEPTH = int(os.environ.get("LOKY_MAX_DEPTH", 10))
+_CURRENT_DEPTH = 0
+
+# Minimum time interval between two consecutive memory leak protection checks.
+_MEMORY_LEAK_CHECK_DELAY = 1.
+
+# Number of bytes of memory usage allowed over the reference process size.
+_MAX_MEMORY_LEAK_SIZE = int(3e8)
+
+
+try:
+ from psutil import Process
+ _USE_PSUTIL = True
+
+ def _get_memory_usage(pid, force_gc=False):
+ if force_gc:
+ gc.collect()
+
+ mem_size = Process(pid).memory_info().rss
+ mp.util.debug(f'psutil return memory size: {mem_size}')
+ return mem_size
+
+except ImportError:
+ _USE_PSUTIL = False
+
+
+class _ThreadWakeup:
+ def __init__(self):
+ self._closed = False
+ self._reader, self._writer = mp.Pipe(duplex=False)
+
+ def close(self):
+ if not self._closed:
+ self._closed = True
+ self._writer.close()
+ self._reader.close()
+
+ def wakeup(self):
+ if not self._closed:
+ self._writer.send_bytes(b"")
+
+ def clear(self):
+ if not self._closed:
+ while self._reader.poll():
+ self._reader.recv_bytes()
+
+
+class _ExecutorFlags:
+ """necessary references to maintain executor states without preventing gc
+
+ It permits to keep the information needed by executor_manager_thread
+ and crash_detection_thread to maintain the pool without preventing the
+ garbage collection of unreferenced executors.
+ """
+ def __init__(self, shutdown_lock):
+
+ self.shutdown = False
+ self.broken = None
+ self.kill_workers = False
+ self.shutdown_lock = shutdown_lock
+
+ def flag_as_shutting_down(self, kill_workers=None):
+ with self.shutdown_lock:
+ self.shutdown = True
+ if kill_workers is not None:
+ self.kill_workers = kill_workers
+
+ def flag_as_broken(self, broken):
+ with self.shutdown_lock:
+ self.shutdown = True
+ self.broken = broken
+
+
+# Prior to 3.9, executor_manager_thread is created as daemon thread. This means
+# that it is not joined automatically when the interpreter is shutting down.
+# To work around this problem, an exit handler is installed to tell the
+# thread to exit when the interpreter is shutting down and then waits until
+# it finishes. The thread needs to be daemonized because the atexit hooks are
+# called after all non daemonized threads are joined.
+#
+# Starting 3.9, there exists a specific atexit hook to be called before joining
+# the threads so the executor_manager_thread does not need to be daemonized
+# anymore.
+#
+# The atexit hooks are registered when starting the first ProcessPoolExecutor
+# to avoid import having an effect on the interpreter.
+
+_threads_wakeups = weakref.WeakKeyDictionary()
+_global_shutdown = False
+
+
+def _python_exit():
+ global _global_shutdown
+ _global_shutdown = True
+ items = list(_threads_wakeups.items())
+ if len(items) > 0:
+ mp.util.debug("Interpreter shutting down. Waking up "
+ f"executor_manager_thread {items}")
+ for _, (shutdown_lock, thread_wakeup) in items:
+ with shutdown_lock:
+ thread_wakeup.wakeup()
+ for thread, _ in items:
+ thread.join()
+
+
+# With the fork context, _thread_wakeups is propagated to children.
+# Clear it after fork to avoid some situation that can cause some
+# freeze when joining the workers.
+mp.util.register_after_fork(_threads_wakeups, lambda obj: obj.clear())
+
+
+# Module variable to register the at_exit call
+process_pool_executor_at_exit = None
+
+# Controls how many more calls than processes will be queued in the call queue.
+# A smaller number will mean that processes spend more time idle waiting for
+# work while a larger number will make Future.cancel() succeed less frequently
+# (Futures in the call queue cannot be cancelled).
+EXTRA_QUEUED_CALLS = 1
+
+
+class _RemoteTraceback(Exception):
+ """Embed stringification of remote traceback in local traceback
+ """
+ def __init__(self, tb=None):
+ self.tb = f'\n"""\n{tb}"""'
+
+ def __str__(self):
+ return self.tb
+
+
+class _ExceptionWithTraceback(BaseException):
+
+ def __init__(self, exc):
+ tb = getattr(exc, "__traceback__", None)
+ if tb is None:
+ _, _, tb = sys.exc_info()
+ tb = traceback.format_exception(type(exc), exc, tb)
+ tb = ''.join(tb)
+ self.exc = exc
+ self.tb = tb
+
+ def __reduce__(self):
+ return _rebuild_exc, (self.exc, self.tb)
+
+
+def _rebuild_exc(exc, tb):
+ exc.__cause__ = _RemoteTraceback(tb)
+ return exc
+
+
+class _WorkItem:
+
+ __slots__ = ["future", "fn", "args", "kwargs"]
+
+ def __init__(self, future, fn, args, kwargs):
+ self.future = future
+ self.fn = fn
+ self.args = args
+ self.kwargs = kwargs
+
+
+class _ResultItem:
+
+ def __init__(self, work_id, exception=None, result=None):
+ self.work_id = work_id
+ self.exception = exception
+ self.result = result
+
+
+class _CallItem:
+
+ def __init__(self, work_id, fn, args, kwargs):
+ self.work_id = work_id
+ self.fn = fn
+ self.args = args
+ self.kwargs = kwargs
+
+ # Store the current loky_pickler so it is correctly set in the worker
+ self.loky_pickler = get_loky_pickler_name()
+
+ def __call__(self):
+ set_loky_pickler(self.loky_pickler)
+ return self.fn(*self.args, **self.kwargs)
+
+ def __repr__(self):
+ return (
+ f"CallItem({self.work_id}, {self.fn}, {self.args}, {self.kwargs})"
+ )
+
+
+class _SafeQueue(Queue):
+ """Safe Queue set exception to the future object linked to a job"""
+ def __init__(self, max_size=0, ctx=None, pending_work_items=None,
+ running_work_items=None, thread_wakeup=None, reducers=None):
+ self.thread_wakeup = thread_wakeup
+ self.pending_work_items = pending_work_items
+ self.running_work_items = running_work_items
+ super().__init__(max_size, reducers=reducers, ctx=ctx)
+
+ def _on_queue_feeder_error(self, e, obj):
+ if isinstance(obj, _CallItem):
+ # format traceback only works on python3
+ if isinstance(e, struct.error):
+ raised_error = RuntimeError(
+ "The task could not be sent to the workers as it is too "
+ "large for `send_bytes`.")
+ else:
+ raised_error = PicklingError(
+ "Could not pickle the task to send it to the workers.")
+ tb = traceback.format_exception(
+ type(e), e, getattr(e, "__traceback__", None))
+ raised_error.__cause__ = _RemoteTraceback(''.join(tb))
+ work_item = self.pending_work_items.pop(obj.work_id, None)
+ self.running_work_items.remove(obj.work_id)
+ # work_item can be None if another process terminated. In this
+ # case, the executor_manager_thread fails all work_items with
+ # BrokenProcessPool
+ if work_item is not None:
+ work_item.future.set_exception(raised_error)
+ del work_item
+ self.thread_wakeup.wakeup()
+ else:
+ super()._on_queue_feeder_error(e, obj)
+
+
+def _get_chunks(chunksize, *iterables):
+ """Iterates over zip()ed iterables in chunks. """
+ it = zip(*iterables)
+ while True:
+ chunk = tuple(itertools.islice(it, chunksize))
+ if not chunk:
+ return
+ yield chunk
+
+
+def _process_chunk(fn, chunk):
+ """Processes a chunk of an iterable passed to map.
+
+ Runs the function passed to map() on a chunk of the
+ iterable passed to map.
+
+ This function is run in a separate process.
+
+ """
+ return [fn(*args) for args in chunk]
+
+
+def _sendback_result(result_queue, work_id, result=None, exception=None):
+ """Safely send back the given result or exception"""
+ try:
+ result_queue.put(_ResultItem(work_id, result=result,
+ exception=exception))
+ except BaseException as e:
+ exc = _ExceptionWithTraceback(e)
+ result_queue.put(_ResultItem(work_id, exception=exc))
+
+
+def _process_worker(call_queue, result_queue, initializer, initargs,
+ processes_management_lock, timeout, worker_exit_lock,
+ current_depth):
+ """Evaluates calls from call_queue and places the results in result_queue.
+
+ This worker is run in a separate process.
+
+ Args:
+ call_queue: A ctx.Queue of _CallItems that will be read and
+ evaluated by the worker.
+ result_queue: A ctx.Queue of _ResultItems that will written
+ to by the worker.
+ initializer: A callable initializer, or None
+ initargs: A tuple of args for the initializer
+ processes_management_lock: A ctx.Lock avoiding worker timeout while
+ some workers are being spawned.
+ timeout: maximum time to wait for a new item in the call_queue. If that
+ time is expired, the worker will shutdown.
+ worker_exit_lock: Lock to avoid flagging the executor as broken on
+ workers timeout.
+ current_depth: Nested parallelism level, to avoid infinite spawning.
+ """
+ if initializer is not None:
+ try:
+ initializer(*initargs)
+ except BaseException:
+ LOGGER.critical('Exception in initializer:', exc_info=True)
+ # The parent will notice that the process stopped and
+ # mark the pool broken
+ return
+
+ # set the global _CURRENT_DEPTH mechanism to limit recursive call
+ global _CURRENT_DEPTH
+ _CURRENT_DEPTH = current_depth
+ _process_reference_size = None
+ _last_memory_leak_check = None
+ pid = os.getpid()
+
+ mp.util.debug(f'Worker started with timeout={timeout}')
+ while True:
+ try:
+ call_item = call_queue.get(block=True, timeout=timeout)
+ if call_item is None:
+ mp.util.info("Shutting down worker on sentinel")
+ except queue.Empty:
+ mp.util.info(f"Shutting down worker after timeout {timeout:0.3f}s")
+ if processes_management_lock.acquire(block=False):
+ processes_management_lock.release()
+ call_item = None
+ else:
+ mp.util.info("Could not acquire processes_management_lock")
+ continue
+ except BaseException:
+ previous_tb = traceback.format_exc()
+ try:
+ result_queue.put(_RemoteTraceback(previous_tb))
+ except BaseException:
+ # If we cannot format correctly the exception, at least print
+ # the traceback.
+ print(previous_tb)
+ mp.util.debug('Exiting with code 1')
+ sys.exit(1)
+ if call_item is None:
+ # Notify queue management thread about worker shutdown
+ result_queue.put(pid)
+ is_clean = worker_exit_lock.acquire(True, timeout=30)
+
+ # Early notify any loky executor running in this worker process
+ # (nested parallelism) that this process is about to shutdown to
+ # avoid a deadlock waiting undifinitely for the worker to finish.
+ _python_exit()
+
+ if is_clean:
+ mp.util.debug('Exited cleanly')
+ else:
+ mp.util.info('Main process did not release worker_exit')
+ return
+ try:
+ r = call_item()
+ except BaseException as e:
+ exc = _ExceptionWithTraceback(e)
+ result_queue.put(_ResultItem(call_item.work_id, exception=exc))
+ else:
+ _sendback_result(result_queue, call_item.work_id, result=r)
+ del r
+
+ # Free the resource as soon as possible, to avoid holding onto
+ # open files or shared memory that is not needed anymore
+ del call_item
+
+ if _USE_PSUTIL:
+ if _process_reference_size is None:
+ # Make reference measurement after the first call
+ _process_reference_size = _get_memory_usage(pid, force_gc=True)
+ _last_memory_leak_check = time()
+ continue
+ if time() - _last_memory_leak_check > _MEMORY_LEAK_CHECK_DELAY:
+ mem_usage = _get_memory_usage(pid)
+ _last_memory_leak_check = time()
+ if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE:
+ # Memory usage stays within bounds: everything is fine.
+ continue
+
+ # Check again memory usage; this time take the measurement
+ # after a forced garbage collection to break any reference
+ # cycles.
+ mem_usage = _get_memory_usage(pid, force_gc=True)
+ _last_memory_leak_check = time()
+ if mem_usage - _process_reference_size < _MAX_MEMORY_LEAK_SIZE:
+ # The GC managed to free the memory: everything is fine.
+ continue
+
+ # The process is leaking memory: let the master process
+ # know that we need to start a new worker.
+ mp.util.info("Memory leak detected: shutting down worker")
+ result_queue.put(pid)
+ with worker_exit_lock:
+ mp.util.debug('Exit due to memory leak')
+ return
+ else:
+ # if psutil is not installed, trigger gc.collect events
+ # regularly to limit potential memory leaks due to reference cycles
+ if (_last_memory_leak_check is None or
+ (time() - _last_memory_leak_check >
+ _MEMORY_LEAK_CHECK_DELAY)):
+ gc.collect()
+ _last_memory_leak_check = time()
+
+
+class _ExecutorManagerThread(threading.Thread):
+ """Manages the communication between this process and the worker processes.
+
+ The manager is run in a local thread.
+
+ Args:
+ executor: A reference to the ProcessPoolExecutor that owns
+ this thread. A weakref will be own by the manager as well as
+ references to internal objects used to introspect the state of
+ the executor.
+ """
+
+ def __init__(self, executor):
+ # Store references to necessary internals of the executor.
+
+ # A _ThreadWakeup to allow waking up the executor_manager_thread from
+ # the main Thread and avoid deadlocks caused by permanently
+ # locked queues.
+ self.thread_wakeup = executor._executor_manager_thread_wakeup
+ self.shutdown_lock = executor._shutdown_lock
+
+ # A weakref.ref to the ProcessPoolExecutor that owns this thread. Used
+ # to determine if the ProcessPoolExecutor has been garbage collected
+ # and that the manager can exit.
+ # When the executor gets garbage collected, the weakref callback
+ # will wake up the queue management thread so that it can terminate
+ # if there is no pending work item.
+ def weakref_cb(_,
+ thread_wakeup=self.thread_wakeup,
+ shutdown_lock=self.shutdown_lock):
+ if mp is not None:
+ # At this point, the multiprocessing module can already be
+ # garbage collected. We only log debug info when still
+ # possible.
+ mp.util.debug('Executor collected: triggering callback for'
+ ' QueueManager wakeup')
+ with shutdown_lock:
+ thread_wakeup.wakeup()
+
+ self.executor_reference = weakref.ref(executor, weakref_cb)
+
+ # The flags of the executor
+ self.executor_flags = executor._flags
+
+ # A list of the ctx.Process instances used as workers.
+ self.processes = executor._processes
+
+ # A ctx.Queue that will be filled with _CallItems derived from
+ # _WorkItems for processing by the process workers.
+ self.call_queue = executor._call_queue
+
+ # A ctx.SimpleQueue of _ResultItems generated by the process workers.
+ self.result_queue = executor._result_queue
+
+ # A queue.Queue of work ids e.g. Queue([5, 6, ...]).
+ self.work_ids_queue = executor._work_ids
+
+ # A dict mapping work ids to _WorkItems e.g.
+ # {5: <_WorkItem...>, 6: <_WorkItem...>, ...}
+ self.pending_work_items = executor._pending_work_items
+
+ # A list of the work_ids that are currently running
+ self.running_work_items = executor._running_work_items
+
+ # A lock to avoid concurrent shutdown of workers on timeout and spawn
+ # of new processes or shut down
+ self.processes_management_lock = executor._processes_management_lock
+
+ super().__init__(name="ExecutorManagerThread")
+ if sys.version_info < (3, 9):
+ self.daemon = True
+
+ def run(self):
+ # Main loop for the executor manager thread.
+
+ while True:
+ self.add_call_item_to_queue()
+
+ result_item, is_broken, bpe = self.wait_result_broken_or_wakeup()
+
+ if is_broken:
+ self.terminate_broken(bpe)
+ return
+ if result_item is not None:
+ self.process_result_item(result_item)
+ # Delete reference to result_item to avoid keeping references
+ # while waiting on new results.
+ del result_item
+
+ if self.is_shutting_down():
+ self.flag_executor_shutting_down()
+
+ # Since no new work items can be added, it is safe to shutdown
+ # this thread if there are no pending work items.
+ if not self.pending_work_items:
+ self.join_executor_internals()
+ return
+
+ def add_call_item_to_queue(self):
+ # Fills call_queue with _WorkItems from pending_work_items.
+ # This function never blocks.
+ while True:
+ if self.call_queue.full():
+ return
+ try:
+ work_id = self.work_ids_queue.get(block=False)
+ except queue.Empty:
+ return
+ else:
+ work_item = self.pending_work_items[work_id]
+
+ if work_item.future.set_running_or_notify_cancel():
+ self.running_work_items += [work_id]
+ self.call_queue.put(_CallItem(work_id,
+ work_item.fn,
+ work_item.args,
+ work_item.kwargs),
+ block=True)
+ else:
+ del self.pending_work_items[work_id]
+ continue
+
+ def wait_result_broken_or_wakeup(self):
+ # Wait for a result to be ready in the result_queue while checking
+ # that all worker processes are still running, or for a wake up
+ # signal send. The wake up signals come either from new tasks being
+ # submitted, from the executor being shutdown/gc-ed, or from the
+ # shutdown of the python interpreter.
+ result_reader = self.result_queue._reader
+ wakeup_reader = self.thread_wakeup._reader
+ readers = [result_reader, wakeup_reader]
+ worker_sentinels = [p.sentinel for p in list(self.processes.values())]
+ ready = wait(readers + worker_sentinels)
+
+ bpe = None
+ is_broken = True
+ result_item = None
+ if result_reader in ready:
+ try:
+ result_item = result_reader.recv()
+ if isinstance(result_item, _RemoteTraceback):
+ bpe = BrokenProcessPool(
+ "A task has failed to un-serialize. Please ensure that"
+ " the arguments of the function are all picklable."
+ )
+ bpe.__cause__ = result_item
+ else:
+ is_broken = False
+ except BaseException as e:
+ bpe = BrokenProcessPool(
+ "A result has failed to un-serialize. Please ensure that "
+ "the objects returned by the function are always "
+ "picklable."
+ )
+ tb = traceback.format_exception(
+ type(e), e, getattr(e, "__traceback__", None))
+ bpe.__cause__ = _RemoteTraceback(''.join(tb))
+
+ elif wakeup_reader in ready:
+ # This is simply a wake-up event that might either trigger putting
+ # more tasks in the queue or trigger the clean up of resources.
+ is_broken = False
+ else:
+ # A worker has terminated and we don't know why, set the state of
+ # the executor as broken
+ exit_codes = ''
+ if sys.platform != "win32":
+ # In Windows, introspecting terminated workers exitcodes seems
+ # unstable, therefore they are not appended in the exception
+ # message.
+ exit_codes = (
+ "\nThe exit codes of the workers are "
+ f"{get_exitcodes_terminated_worker(self.processes)}"
+ )
+ mp.util.debug('A worker unexpectedly terminated. Workers that '
+ 'might have caused the breakage: '
+ + str({p.name: p.exitcode
+ for p in list(self.processes.values())
+ if p is not None and p.sentinel in ready}))
+ bpe = TerminatedWorkerError(
+ "A worker process managed by the executor was unexpectedly "
+ "terminated. This could be caused by a segmentation fault "
+ "while calling the function or by an excessive memory usage "
+ "causing the Operating System to kill the worker.\n"
+ f"{exit_codes}"
+ )
+
+ self.thread_wakeup.clear()
+
+ return result_item, is_broken, bpe
+
+ def process_result_item(self, result_item):
+ # Process the received a result_item. This can be either the PID of a
+ # worker that exited gracefully or a _ResultItem
+
+ if isinstance(result_item, int):
+ # Clean shutdown of a worker using its PID, either on request
+ # by the executor.shutdown method or by the timeout of the worker
+ # itself: we should not mark the executor as broken.
+ with self.processes_management_lock:
+ p = self.processes.pop(result_item, None)
+
+ # p can be None if the executor is concurrently shutting down.
+ if p is not None:
+ p._worker_exit_lock.release()
+ mp.util.debug(
+ f"joining {p.name} when processing {p.pid} as result_item"
+ )
+ p.join()
+ del p
+
+ # Make sure the executor have the right number of worker, even if a
+ # worker timeout while some jobs were submitted. If some work is
+ # pending or there is less processes than running items, we need to
+ # start a new Process and raise a warning.
+ n_pending = len(self.pending_work_items)
+ n_running = len(self.running_work_items)
+ if (n_pending - n_running > 0 or n_running > len(self.processes)):
+ executor = self.executor_reference()
+ if (executor is not None
+ and len(self.processes) < executor._max_workers):
+ warnings.warn(
+ "A worker stopped while some jobs were given to the "
+ "executor. This can be caused by a too short worker "
+ "timeout or by a memory leak.", UserWarning
+ )
+ with executor._processes_management_lock:
+ executor._adjust_process_count()
+ executor = None
+ else:
+ # Received a _ResultItem so mark the future as completed.
+ work_item = self.pending_work_items.pop(result_item.work_id, None)
+ # work_item can be None if another process terminated (see above)
+ if work_item is not None:
+ if result_item.exception:
+ work_item.future.set_exception(result_item.exception)
+ else:
+ work_item.future.set_result(result_item.result)
+ self.running_work_items.remove(result_item.work_id)
+
+ def is_shutting_down(self):
+ # Check whether we should start shutting down the executor.
+ executor = self.executor_reference()
+ # No more work items can be added if:
+ # - The interpreter is shutting down OR
+ # - The executor that owns this thread is not broken AND
+ # * The executor that owns this worker has been collected OR
+ # * The executor that owns this worker has been shutdown.
+ # If the executor is broken, it should be detected in the next loop.
+ return (_global_shutdown or
+ ((executor is None or self.executor_flags.shutdown)
+ and not self.executor_flags.broken))
+
+ def terminate_broken(self, bpe):
+ # Terminate the executor because it is in a broken state. The bpe
+ # argument can be used to display more information on the error that
+ # lead the executor into becoming broken.
+
+ # Mark the process pool broken so that submits fail right now.
+ self.executor_flags.flag_as_broken(bpe)
+
+ # Mark pending tasks as failed.
+ for work_item in self.pending_work_items.values():
+ work_item.future.set_exception(bpe)
+ # Delete references to object. See issue16284
+ del work_item
+ self.pending_work_items.clear()
+
+ # Terminate remaining workers forcibly: the queues or their
+ # locks may be in a dirty state and block forever.
+ self.kill_workers(reason="broken executor")
+
+ # clean up resources
+ self.join_executor_internals()
+
+ def flag_executor_shutting_down(self):
+ # Flag the executor as shutting down and cancel remaining tasks if
+ # requested as early as possible if it is not gc-ed yet.
+ self.executor_flags.flag_as_shutting_down()
+
+ # Cancel pending work items if requested.
+ if self.executor_flags.kill_workers:
+ while self.pending_work_items:
+ _, work_item = self.pending_work_items.popitem()
+ work_item.future.set_exception(ShutdownExecutorError(
+ "The Executor was shutdown with `kill_workers=True` "
+ "before this job could complete."))
+ del work_item
+
+ # Kill the remaining worker forcibly to no waste time joining them
+ self.kill_workers(reason="executor shutting down")
+
+ def kill_workers(self, reason=''):
+ # Terminate the remaining workers using SIGKILL. This function also
+ # terminates descendant workers of the children in case there is some
+ # nested parallelism.
+ while self.processes:
+ _, p = self.processes.popitem()
+ mp.util.debug(f"terminate process {p.name}, reason: {reason}")
+ try:
+ kill_process_tree(p)
+ except ProcessLookupError: # pragma: no cover
+ pass
+
+ def shutdown_workers(self):
+ # shutdown all workers in self.processes
+
+ # Create a list to avoid RuntimeError due to concurrent modification of
+ # processes. nb_children_alive is thus an upper bound. Also release the
+ # processes' _worker_exit_lock to accelerate the shutdown procedure, as
+ # there is no need for hand-shake here.
+ with self.processes_management_lock:
+ n_children_to_stop = 0
+ for p in list(self.processes.values()):
+ mp.util.debug(f"releasing worker exit lock on {p.name}")
+ p._worker_exit_lock.release()
+ n_children_to_stop += 1
+
+ mp.util.debug(f"found {n_children_to_stop} processes to stop")
+
+ # Send the right number of sentinels, to make sure all children are
+ # properly terminated. Do it with a mechanism that avoid hanging on
+ # Full queue when all workers have already been shutdown.
+ n_sentinels_sent = 0
+ cooldown_time = 0.001
+ while (n_sentinels_sent < n_children_to_stop
+ and self.get_n_children_alive() > 0):
+ for _ in range(n_children_to_stop - n_sentinels_sent):
+ try:
+ self.call_queue.put_nowait(None)
+ n_sentinels_sent += 1
+ except queue.Full as e:
+ if cooldown_time > 10.0:
+ raise e
+ mp.util.info(
+ "full call_queue prevented to send all sentinels at "
+ "once, waiting..."
+ )
+ sleep(cooldown_time)
+ cooldown_time *= 2
+ break
+
+ mp.util.debug(f"sent {n_sentinels_sent} sentinels to the call queue")
+
+ def join_executor_internals(self):
+ self.shutdown_workers()
+
+ # Release the queue's resources as soon as possible. Flag the feeder
+ # thread for clean exit to avoid having the crash detection thread flag
+ # the Executor as broken during the shutdown. This is safe as either:
+ # * We don't need to communicate with the workers anymore
+ # * There is nothing left in the Queue buffer except None sentinels
+ mp.util.debug("closing call_queue")
+ self.call_queue.close()
+ self.call_queue.join_thread()
+
+ # Closing result_queue
+ mp.util.debug("closing result_queue")
+ self.result_queue.close()
+
+ mp.util.debug("closing thread_wakeup")
+ with self.shutdown_lock:
+ self.thread_wakeup.close()
+
+ # If .join() is not called on the created processes then
+ # some ctx.Queue methods may deadlock on macOS.
+ with self.processes_management_lock:
+ mp.util.debug(f"joining {len(self.processes)} processes")
+ n_joined_processes = 0
+ while True:
+ try:
+ pid, p = self.processes.popitem()
+ mp.util.debug(f"joining process {p.name} with pid {pid}")
+ p.join()
+ n_joined_processes += 1
+ except KeyError:
+ break
+
+ mp.util.debug(
+ "executor management thread clean shutdown of "
+ f"{n_joined_processes} workers"
+ )
+
+ def get_n_children_alive(self):
+ # This is an upper bound on the number of children alive.
+ with self.processes_management_lock:
+ return sum(p.is_alive() for p in list(self.processes.values()))
+
+
+_system_limits_checked = False
+_system_limited = None
+
+
+def _check_system_limits():
+ global _system_limits_checked, _system_limited
+ if _system_limits_checked and _system_limited:
+ raise NotImplementedError(_system_limited)
+ _system_limits_checked = True
+ try:
+ nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
+ except (AttributeError, ValueError):
+ # sysconf not available or setting not available
+ return
+ if nsems_max == -1:
+ # undetermined limit, assume that limit is determined
+ # by available memory only
+ return
+ if nsems_max >= 256:
+ # minimum number of semaphores available
+ # according to POSIX
+ return
+ _system_limited = (
+ f"system provides too few semaphores ({nsems_max} available, "
+ "256 necessary)"
+ )
+ raise NotImplementedError(_system_limited)
+
+
+def _chain_from_iterable_of_lists(iterable):
+ """
+ Specialized implementation of itertools.chain.from_iterable.
+ Each item in *iterable* should be a list. This function is
+ careful not to keep references to yielded objects.
+ """
+ for element in iterable:
+ element.reverse()
+ while element:
+ yield element.pop()
+
+
+def _check_max_depth(context):
+ # Limit the maxmal recursion level
+ global _CURRENT_DEPTH
+ if context.get_start_method() == "fork" and _CURRENT_DEPTH > 0:
+ raise LokyRecursionError(
+ "Could not spawn extra nested processes at depth superior to "
+ "MAX_DEPTH=1. It is not possible to increase this limit when "
+ "using the 'fork' start method.")
+
+ if 0 < MAX_DEPTH and _CURRENT_DEPTH + 1 > MAX_DEPTH:
+ raise LokyRecursionError(
+ "Could not spawn extra nested processes at depth superior to "
+ f"MAX_DEPTH={MAX_DEPTH}. If this is intendend, you can change "
+ "this limit with the LOKY_MAX_DEPTH environment variable.")
+
+
+class LokyRecursionError(RuntimeError):
+ """Raised when a process try to spawn too many levels of nested processes.
+ """
+
+
+class BrokenProcessPool(_BPPException):
+ """
+ Raised when the executor is broken while a future was in the running state.
+ The cause can an error raised when unpickling the task in the worker
+ process or when unpickling the result value in the parent process. It can
+ also be caused by a worker process being terminated unexpectedly.
+ """
+
+
+class TerminatedWorkerError(BrokenProcessPool):
+ """
+ Raised when a process in a ProcessPoolExecutor terminated abruptly
+ while a future was in the running state.
+ """
+
+
+# Alias for backward compat (for code written for loky 1.1.4 and earlier). Do
+# not use in new code.
+BrokenExecutor = BrokenProcessPool
+
+
+class ShutdownExecutorError(RuntimeError):
+
+ """
+ Raised when a ProcessPoolExecutor is shutdown while a future was in the
+ running or pending state.
+ """
+
+
+class ProcessPoolExecutor(Executor):
+
+ _at_exit = None
+
+ def __init__(self, max_workers=None, job_reducers=None,
+ result_reducers=None, timeout=None, context=None,
+ initializer=None, initargs=(), env=None):
+ """Initializes a new ProcessPoolExecutor instance.
+
+ Args:
+ max_workers: int, optional (default: cpu_count())
+ The maximum number of processes that can be used to execute the
+ given calls. If None or not given then as many worker processes
+ will be created as the number of CPUs the current process
+ can use.
+ job_reducers, result_reducers: dict(type: reducer_func)
+ Custom reducer for pickling the jobs and the results from the
+ Executor. If only `job_reducers` is provided, `result_reducer`
+ will use the same reducers
+ timeout: int, optional (default: None)
+ Idle workers exit after timeout seconds. If a new job is
+ submitted after the timeout, the executor will start enough
+ new Python processes to make sure the pool of workers is full.
+ context: A multiprocessing context to launch the workers. This
+ object should provide SimpleQueue, Queue and Process.
+ initializer: An callable used to initialize worker processes.
+ initargs: A tuple of arguments to pass to the initializer.
+ env: A dict of environment variable to overwrite in the child
+ process. The environment variables are set before any module is
+ loaded. Note that this only works with the loky context.
+ """
+ _check_system_limits()
+
+ if max_workers is None:
+ self._max_workers = cpu_count()
+ else:
+ if max_workers <= 0:
+ raise ValueError("max_workers must be greater than 0")
+ self._max_workers = max_workers
+
+ if context is None:
+ context = get_context()
+ self._context = context
+ self._env = env
+
+ self._initializer, self._initargs = _prepare_initializer(
+ initializer, initargs
+ )
+ _check_max_depth(self._context)
+
+ if result_reducers is None:
+ result_reducers = job_reducers
+
+ # Timeout
+ self._timeout = timeout
+
+ # Management thread
+ self._executor_manager_thread = None
+
+ # Map of pids to processes
+ self._processes = {}
+
+ # Internal variables of the ProcessPoolExecutor
+ self._processes = {}
+ self._queue_count = 0
+ self._pending_work_items = {}
+ self._running_work_items = []
+ self._work_ids = queue.Queue()
+ self._processes_management_lock = self._context.Lock()
+ self._executor_manager_thread = None
+ self._shutdown_lock = threading.Lock()
+
+ # _ThreadWakeup is a communication channel used to interrupt the wait
+ # of the main loop of executor_manager_thread from another thread (e.g.
+ # when calling executor.submit or executor.shutdown). We do not use the
+ # _result_queue to send wakeup signals to the executor_manager_thread
+ # as it could result in a deadlock if a worker process dies with the
+ # _result_queue write lock still acquired.
+ #
+ # _shutdown_lock must be locked to access _ThreadWakeup.wakeup.
+ self._executor_manager_thread_wakeup = _ThreadWakeup()
+
+ # Flag to hold the state of the Executor. This permits to introspect
+ # the Executor state even once it has been garbage collected.
+ self._flags = _ExecutorFlags(self._shutdown_lock)
+
+ # Finally setup the queues for interprocess communication
+ self._setup_queues(job_reducers, result_reducers)
+
+ mp.util.debug('ProcessPoolExecutor is setup')
+
+ def _setup_queues(self, job_reducers, result_reducers, queue_size=None):
+ # Make the call queue slightly larger than the number of processes to
+ # prevent the worker processes from idling. But don't make it too big
+ # because futures in the call queue cannot be cancelled.
+ if queue_size is None:
+ queue_size = 2 * self._max_workers + EXTRA_QUEUED_CALLS
+ self._call_queue = _SafeQueue(
+ max_size=queue_size, pending_work_items=self._pending_work_items,
+ running_work_items=self._running_work_items,
+ thread_wakeup=self._executor_manager_thread_wakeup,
+ reducers=job_reducers, ctx=self._context)
+ # Killed worker processes can produce spurious "broken pipe"
+ # tracebacks in the queue's own worker thread. But we detect killed
+ # processes anyway, so silence the tracebacks.
+ self._call_queue._ignore_epipe = True
+
+ self._result_queue = SimpleQueue(reducers=result_reducers,
+ ctx=self._context)
+
+ def _start_executor_manager_thread(self):
+ if self._executor_manager_thread is None:
+ mp.util.debug('_start_executor_manager_thread called')
+
+ # Start the processes so that their sentinels are known.
+ self._executor_manager_thread = _ExecutorManagerThread(self)
+ self._executor_manager_thread.start()
+
+ # register this executor in a mechanism that ensures it will wakeup
+ # when the interpreter is exiting.
+ _threads_wakeups[self._executor_manager_thread] = \
+ (self._shutdown_lock,
+ self._executor_manager_thread_wakeup)
+
+ global process_pool_executor_at_exit
+ if process_pool_executor_at_exit is None:
+ # Ensure that the _python_exit function will be called before
+ # the multiprocessing.Queue._close finalizers which have an
+ # exitpriority of 10.
+
+ if sys.version_info < (3, 9):
+ process_pool_executor_at_exit = mp.util.Finalize(
+ None, _python_exit, exitpriority=20)
+ else:
+ process_pool_executor_at_exit = threading._register_atexit(
+ _python_exit)
+
+ def _adjust_process_count(self):
+ while len(self._processes) < self._max_workers:
+ worker_exit_lock = self._context.BoundedSemaphore(1)
+ args = (self._call_queue, self._result_queue, self._initializer,
+ self._initargs, self._processes_management_lock,
+ self._timeout, worker_exit_lock, _CURRENT_DEPTH + 1)
+ worker_exit_lock.acquire()
+ try:
+ # Try to spawn the process with some environment variable to
+ # overwrite but it only works with the loky context for now.
+ p = self._context.Process(target=_process_worker, args=args,
+ env=self._env)
+ except TypeError:
+ p = self._context.Process(target=_process_worker, args=args)
+ p._worker_exit_lock = worker_exit_lock
+ p.start()
+ self._processes[p.pid] = p
+ mp.util.debug(
+ f"Adjusted process count to {self._max_workers}: "
+ f"{[(p.name, pid) for pid, p in self._processes.items()]}"
+ )
+
+ def _ensure_executor_running(self):
+ """ensures all workers and management thread are running
+ """
+ with self._processes_management_lock:
+ if len(self._processes) != self._max_workers:
+ self._adjust_process_count()
+ self._start_executor_manager_thread()
+
+ def submit(self, fn, *args, **kwargs):
+ with self._flags.shutdown_lock:
+ if self._flags.broken is not None:
+ raise self._flags.broken
+ if self._flags.shutdown:
+ raise ShutdownExecutorError(
+ 'cannot schedule new futures after shutdown')
+
+ # Cannot submit a new calls once the interpreter is shutting down.
+ # This check avoids spawning new processes at exit.
+ if _global_shutdown:
+ raise RuntimeError('cannot schedule new futures after '
+ 'interpreter shutdown')
+
+ f = Future()
+ w = _WorkItem(f, fn, args, kwargs)
+
+ self._pending_work_items[self._queue_count] = w
+ self._work_ids.put(self._queue_count)
+ self._queue_count += 1
+ # Wake up queue management thread
+ self._executor_manager_thread_wakeup.wakeup()
+
+ self._ensure_executor_running()
+ return f
+ submit.__doc__ = Executor.submit.__doc__
+
+ def map(self, fn, *iterables, **kwargs):
+ """Returns an iterator equivalent to map(fn, iter).
+
+ Args:
+ fn: A callable that will take as many arguments as there are
+ passed iterables.
+ timeout: The maximum number of seconds to wait. If None, then there
+ is no limit on the wait time.
+ chunksize: If greater than one, the iterables will be chopped into
+ chunks of size chunksize and submitted to the process pool.
+ If set to one, the items in the list will be sent one at a
+ time.
+
+ Returns:
+ An iterator equivalent to: map(func, *iterables) but the calls may
+ be evaluated out-of-order.
+
+ Raises:
+ TimeoutError: If the entire result iterator could not be generated
+ before the given timeout.
+ Exception: If fn(*args) raises for any values.
+ """
+ timeout = kwargs.get('timeout', None)
+ chunksize = kwargs.get('chunksize', 1)
+ if chunksize < 1:
+ raise ValueError("chunksize must be >= 1.")
+
+ results = super().map(
+ partial(_process_chunk, fn), _get_chunks(chunksize, *iterables),
+ timeout=timeout
+ )
+ return _chain_from_iterable_of_lists(results)
+
+ def shutdown(self, wait=True, kill_workers=False):
+ mp.util.debug(f'shutting down executor {self}')
+
+ self._flags.flag_as_shutting_down(kill_workers)
+ executor_manager_thread = self._executor_manager_thread
+ executor_manager_thread_wakeup = self._executor_manager_thread_wakeup
+
+ if executor_manager_thread_wakeup is not None:
+ # Wake up queue management thread
+ with self._shutdown_lock:
+ self._executor_manager_thread_wakeup.wakeup()
+
+ if executor_manager_thread is not None and wait:
+ executor_manager_thread.join()
+
+ # To reduce the risk of opening too many files, remove references to
+ # objects that use file descriptors.
+ self._executor_manager_thread = None
+ self._executor_manager_thread_wakeup = None
+ self._call_queue = None
+ self._result_queue = None
+ self._processes_management_lock = None
+
+ shutdown.__doc__ = Executor.shutdown.__doc__
diff --git a/runtime/Lib/site-packages/joblib/externals/loky/reusable_executor.py b/runtime/Lib/site-packages/joblib/externals/loky/reusable_executor.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b183a0bf2b0b4ef8b2345842d5f57cad8b50277
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/externals/loky/reusable_executor.py
@@ -0,0 +1,233 @@
+###############################################################################
+# Reusable ProcessPoolExecutor
+#
+# author: Thomas Moreau and Olivier Grisel
+#
+import time
+import warnings
+import threading
+import multiprocessing as mp
+
+from .process_executor import ProcessPoolExecutor, EXTRA_QUEUED_CALLS
+from .backend.context import cpu_count
+from .backend import get_context
+
+__all__ = ['get_reusable_executor']
+
+# Singleton executor and id management
+_executor_lock = threading.RLock()
+_next_executor_id = 0
+_executor = None
+_executor_kwargs = None
+
+
+def _get_next_executor_id():
+ """Ensure that each successive executor instance has a unique, monotonic id.
+
+ The purpose of this monotonic id is to help debug and test automated
+ instance creation.
+ """
+ global _next_executor_id
+ with _executor_lock:
+ executor_id = _next_executor_id
+ _next_executor_id += 1
+ return executor_id
+
+
+def get_reusable_executor(max_workers=None, context=None, timeout=10,
+ kill_workers=False, reuse="auto",
+ job_reducers=None, result_reducers=None,
+ initializer=None, initargs=(), env=None):
+ """Return the current ReusableExectutor instance.
+
+ Start a new instance if it has not been started already or if the previous
+ instance was left in a broken state.
+
+ If the previous instance does not have the requested number of workers, the
+ executor is dynamically resized to adjust the number of workers prior to
+ returning.
+
+ Reusing a singleton instance spares the overhead of starting new worker
+ processes and importing common python packages each time.
+
+ ``max_workers`` controls the maximum number of tasks that can be running in
+ parallel in worker processes. By default this is set to the number of
+ CPUs on the host.
+
+ Setting ``timeout`` (in seconds) makes idle workers automatically shutdown
+ so as to release system resources. New workers are respawn upon submission
+ of new tasks so that ``max_workers`` are available to accept the newly
+ submitted tasks. Setting ``timeout`` to around 100 times the time required
+ to spawn new processes and import packages in them (on the order of 100ms)
+ ensures that the overhead of spawning workers is negligible.
+
+ Setting ``kill_workers=True`` makes it possible to forcibly interrupt
+ previously spawned jobs to get a new instance of the reusable executor
+ with new constructor argument values.
+
+ The ``job_reducers`` and ``result_reducers`` are used to customize the
+ pickling of tasks and results send to the executor.
+
+ When provided, the ``initializer`` is run first in newly spawned
+ processes with argument ``initargs``.
+
+ The environment variable in the child process are a copy of the values in
+ the main process. One can provide a dict ``{ENV: VAL}`` where ``ENV`` and
+ ``VAR`` are string literals to overwrite the environment variable ``ENV``
+ in the child processes to value ``VAL``. The environment variables are set
+ in the children before any module is loaded. This only works with with the
+ ``loky`` context.
+ """
+ _executor, _ = _ReusablePoolExecutor.get_reusable_executor(
+ max_workers=max_workers, context=context, timeout=timeout,
+ kill_workers=kill_workers, reuse=reuse, job_reducers=job_reducers,
+ result_reducers=result_reducers, initializer=initializer,
+ initargs=initargs, env=env
+ )
+ return _executor
+
+
+class _ReusablePoolExecutor(ProcessPoolExecutor):
+ def __init__(self, submit_resize_lock, max_workers=None, context=None,
+ timeout=None, executor_id=0, job_reducers=None,
+ result_reducers=None, initializer=None, initargs=(),
+ env=None):
+ super().__init__(
+ max_workers=max_workers, context=context, timeout=timeout,
+ job_reducers=job_reducers, result_reducers=result_reducers,
+ initializer=initializer, initargs=initargs, env=env)
+ self.executor_id = executor_id
+ self._submit_resize_lock = submit_resize_lock
+
+ @classmethod
+ def get_reusable_executor(cls, max_workers=None, context=None, timeout=10,
+ kill_workers=False, reuse="auto",
+ job_reducers=None, result_reducers=None,
+ initializer=None, initargs=(), env=None):
+ with _executor_lock:
+ global _executor, _executor_kwargs
+ executor = _executor
+
+ if max_workers is None:
+ if reuse is True and executor is not None:
+ max_workers = executor._max_workers
+ else:
+ max_workers = cpu_count()
+ elif max_workers <= 0:
+ raise ValueError(
+ f"max_workers must be greater than 0, got {max_workers}."
+ )
+
+ if isinstance(context, str):
+ context = get_context(context)
+ if context is not None and context.get_start_method() == "fork":
+ raise ValueError(
+ "Cannot use reusable executor with the 'fork' context"
+ )
+
+ kwargs = dict(context=context, timeout=timeout,
+ job_reducers=job_reducers,
+ result_reducers=result_reducers,
+ initializer=initializer, initargs=initargs,
+ env=env)
+ if executor is None:
+ is_reused = False
+ mp.util.debug(
+ f"Create a executor with max_workers={max_workers}."
+ )
+ executor_id = _get_next_executor_id()
+ _executor_kwargs = kwargs
+ _executor = executor = cls(
+ _executor_lock, max_workers=max_workers,
+ executor_id=executor_id, **kwargs)
+ else:
+ if reuse == 'auto':
+ reuse = kwargs == _executor_kwargs
+ if (executor._flags.broken or executor._flags.shutdown
+ or not reuse):
+ if executor._flags.broken:
+ reason = "broken"
+ elif executor._flags.shutdown:
+ reason = "shutdown"
+ else:
+ reason = "arguments have changed"
+ mp.util.debug(
+ "Creating a new executor with max_workers= "
+ f"{max_workers} as the previous instance cannot be "
+ f"reused ({reason})."
+ )
+ executor.shutdown(wait=True, kill_workers=kill_workers)
+ _executor = executor = _executor_kwargs = None
+ # Recursive call to build a new instance
+ return cls.get_reusable_executor(max_workers=max_workers,
+ **kwargs)
+ else:
+ mp.util.debug(
+ "Reusing existing executor with "
+ f"max_workers={executor._max_workers}."
+ )
+ is_reused = True
+ executor._resize(max_workers)
+
+ return executor, is_reused
+
+ def submit(self, fn, *args, **kwargs):
+ with self._submit_resize_lock:
+ return super().submit(fn, *args, **kwargs)
+
+ def _resize(self, max_workers):
+ with self._submit_resize_lock:
+ if max_workers is None:
+ raise ValueError("Trying to resize with max_workers=None")
+ elif max_workers == self._max_workers:
+ return
+
+ if self._executor_manager_thread is None:
+ # If the executor_manager_thread has not been started
+ # then no processes have been spawned and we can just
+ # update _max_workers and return
+ self._max_workers = max_workers
+ return
+
+ self._wait_job_completion()
+
+ # Some process might have returned due to timeout so check how many
+ # children are still alive. Use the _process_management_lock to
+ # ensure that no process are spawned or timeout during the resize.
+ with self._processes_management_lock:
+ processes = list(self._processes.values())
+ nb_children_alive = sum(p.is_alive() for p in processes)
+ self._max_workers = max_workers
+ for _ in range(max_workers, nb_children_alive):
+ self._call_queue.put(None)
+ while (len(self._processes) > max_workers
+ and not self._flags.broken):
+ time.sleep(1e-3)
+
+ self._adjust_process_count()
+ processes = list(self._processes.values())
+ while not all(p.is_alive() for p in processes):
+ time.sleep(1e-3)
+
+ def _wait_job_completion(self):
+ """Wait for the cache to be empty before resizing the pool."""
+ # Issue a warning to the user about the bad effect of this usage.
+ if self._pending_work_items:
+ warnings.warn("Trying to resize an executor with running jobs: "
+ "waiting for jobs completion before resizing.",
+ UserWarning)
+ mp.util.debug(
+ f"Executor {self.executor_id} waiting for jobs completion "
+ "before resizing"
+ )
+ # Wait for the completion of the jobs
+ while self._pending_work_items:
+ time.sleep(1e-3)
+
+ def _setup_queues(self, job_reducers, result_reducers):
+ # As this executor can be resized, use a large queue size to avoid
+ # underestimating capacity and introducing overhead
+ queue_size = 2 * cpu_count() + EXTRA_QUEUED_CALLS
+ super()._setup_queues(
+ job_reducers, result_reducers, queue_size=queue_size
+ )
diff --git a/runtime/Lib/site-packages/joblib/format_stack.py b/runtime/Lib/site-packages/joblib/format_stack.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3249192217c9d32e1417e88d6f14d094d1b776c
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/format_stack.py
@@ -0,0 +1,36 @@
+from sys import version_info
+
+from warnings import warn
+
+"""
+Represent an exception with a lot of information.
+
+Provides 2 useful functions:
+
+format_exc: format an exception into a complete traceback, with full
+ debugging instruction.
+
+format_outer_frames: format the current position in the stack call.
+
+Adapted from IPython's VerboseTB.
+
+This module is deprecated and will be removed in joblib 0.16.
+"""
+from joblib import _deprecated_format_stack
+
+_deprecated_names = [
+ name for name in dir(_deprecated_format_stack) if
+ not name.startswith("__") # special attributes
+]
+
+
+if version_info[:2] >= (3, 7):
+ def __getattr__(name):
+ if not name.startswith("__") and name in _deprecated_names:
+ warn("{} is deprecated and will be removed from joblib "
+ "in 0.16".format(name), DeprecationWarning)
+ return getattr(_deprecated_format_stack, name)
+ raise AttributeError
+else:
+ for name in _deprecated_names:
+ globals()[name] = getattr(_deprecated_format_stack, name)
diff --git a/runtime/Lib/site-packages/joblib/func_inspect.py b/runtime/Lib/site-packages/joblib/func_inspect.py
new file mode 100644
index 0000000000000000000000000000000000000000..d334a2b9dcf52a27e2cc136a01cb04ae5f658719
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/func_inspect.py
@@ -0,0 +1,365 @@
+"""
+My own variation on function-specific inspect-like features.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import inspect
+import warnings
+import re
+import os
+import collections
+
+from itertools import islice
+from tokenize import open as open_py_source
+
+from .logger import pformat
+
+full_argspec_fields = ('args varargs varkw defaults kwonlyargs '
+ 'kwonlydefaults annotations')
+full_argspec_type = collections.namedtuple('FullArgSpec', full_argspec_fields)
+
+
+def get_func_code(func):
+ """ Attempts to retrieve a reliable function code hash.
+
+ The reason we don't use inspect.getsource is that it caches the
+ source, whereas we want this to be modified on the fly when the
+ function is modified.
+
+ Returns
+ -------
+ func_code: string
+ The function code
+ source_file: string
+ The path to the file in which the function is defined.
+ first_line: int
+ The first line of the code in the source file.
+
+ Notes
+ ------
+ This function does a bit more magic than inspect, and is thus
+ more robust.
+ """
+ source_file = None
+ try:
+ code = func.__code__
+ source_file = code.co_filename
+ if not os.path.exists(source_file):
+ # Use inspect for lambda functions and functions defined in an
+ # interactive shell, or in doctests
+ source_code = ''.join(inspect.getsourcelines(func)[0])
+ line_no = 1
+ if source_file.startswith('', source_file).groups()
+ line_no = int(line_no)
+ source_file = '' % source_file
+ return source_code, source_file, line_no
+ # Try to retrieve the source code.
+ with open_py_source(source_file) as source_file_obj:
+ first_line = code.co_firstlineno
+ # All the lines after the function definition:
+ source_lines = list(islice(source_file_obj, first_line - 1, None))
+ return ''.join(inspect.getblock(source_lines)), source_file, first_line
+ except:
+ # If the source code fails, we use the hash. This is fragile and
+ # might change from one session to another.
+ if hasattr(func, '__code__'):
+ # Python 3.X
+ return str(func.__code__.__hash__()), source_file, -1
+ else:
+ # Weird objects like numpy ufunc don't have __code__
+ # This is fragile, as quite often the id of the object is
+ # in the repr, so it might not persist across sessions,
+ # however it will work for ufuncs.
+ return repr(func), source_file, -1
+
+
+def _clean_win_chars(string):
+ """Windows cannot encode some characters in filename."""
+ import urllib
+ if hasattr(urllib, 'quote'):
+ quote = urllib.quote
+ else:
+ # In Python 3, quote is elsewhere
+ import urllib.parse
+ quote = urllib.parse.quote
+ for char in ('<', '>', '!', ':', '\\'):
+ string = string.replace(char, quote(char))
+ return string
+
+
+def get_func_name(func, resolv_alias=True, win_characters=True):
+ """ Return the function import path (as a list of module names), and
+ a name for the function.
+
+ Parameters
+ ----------
+ func: callable
+ The func to inspect
+ resolv_alias: boolean, optional
+ If true, possible local aliases are indicated.
+ win_characters: boolean, optional
+ If true, substitute special characters using urllib.quote
+ This is useful in Windows, as it cannot encode some filenames
+ """
+ if hasattr(func, '__module__'):
+ module = func.__module__
+ else:
+ try:
+ module = inspect.getmodule(func)
+ except TypeError:
+ if hasattr(func, '__class__'):
+ module = func.__class__.__module__
+ else:
+ module = 'unknown'
+ if module is None:
+ # Happens in doctests, eg
+ module = ''
+ if module == '__main__':
+ try:
+ filename = os.path.abspath(inspect.getsourcefile(func))
+ except:
+ filename = None
+ if filename is not None:
+ # mangling of full path to filename
+ parts = filename.split(os.sep)
+ if parts[-1].startswith(', where:
+ # - N is the cell number where the function was defined
+ # - XYZ is a hash representing the function's code (and name).
+ # It will be consistent across sessions and kernel restarts,
+ # and will change if the function's code/name changes
+ # We remove N so that cache is properly hit if the cell where
+ # the func is defined is re-exectuted.
+ # The XYZ hash should avoid collisions between functions with
+ # the same name, both within the same notebook but also across
+ # notebooks
+ splitted = parts[-1].split('-')
+ parts[-1] = '-'.join(splitted[:2] + splitted[3:])
+ elif len(parts) > 2 and parts[-2].startswith('ipykernel_'):
+ # In a notebook session (ipykernel). Filename seems to be 'xyz'
+ # of above. parts[-2] has the structure ipykernel_XXXXXX where
+ # XXXXXX is a six-digit number identifying the current run (?).
+ # If we split it off, the function again has the same
+ # identifier across runs.
+ parts[-2] = 'ipykernel'
+ filename = '-'.join(parts)
+ if filename.endswith('.py'):
+ filename = filename[:-3]
+ module = module + '-' + filename
+ module = module.split('.')
+ if hasattr(func, 'func_name'):
+ name = func.func_name
+ elif hasattr(func, '__name__'):
+ name = func.__name__
+ else:
+ name = 'unknown'
+ # Hack to detect functions not defined at the module-level
+ if resolv_alias:
+ # TODO: Maybe add a warning here?
+ if hasattr(func, 'func_globals') and name in func.func_globals:
+ if not func.func_globals[name] is func:
+ name = '%s-alias' % name
+ if inspect.ismethod(func):
+ # We need to add the name of the class
+ if hasattr(func, 'im_class'):
+ klass = func.im_class
+ module.append(klass.__name__)
+ if os.name == 'nt' and win_characters:
+ # Windows can't encode certain characters in filenames
+ name = _clean_win_chars(name)
+ module = [_clean_win_chars(s) for s in module]
+ return module, name
+
+
+def _signature_str(function_name, arg_sig):
+ """Helper function to output a function signature"""
+ return '{}{}'.format(function_name, arg_sig)
+
+
+def _function_called_str(function_name, args, kwargs):
+ """Helper function to output a function call"""
+ template_str = '{0}({1}, {2})'
+
+ args_str = repr(args)[1:-1]
+ kwargs_str = ', '.join('%s=%s' % (k, v)
+ for k, v in kwargs.items())
+ return template_str.format(function_name, args_str,
+ kwargs_str)
+
+
+def filter_args(func, ignore_lst, args=(), kwargs=dict()):
+ """ Filters the given args and kwargs using a list of arguments to
+ ignore, and a function specification.
+
+ Parameters
+ ----------
+ func: callable
+ Function giving the argument specification
+ ignore_lst: list of strings
+ List of arguments to ignore (either a name of an argument
+ in the function spec, or '*', or '**')
+ *args: list
+ Positional arguments passed to the function.
+ **kwargs: dict
+ Keyword arguments passed to the function
+
+ Returns
+ -------
+ filtered_args: list
+ List of filtered positional and keyword arguments.
+ """
+ args = list(args)
+ if isinstance(ignore_lst, str):
+ # Catch a common mistake
+ raise ValueError(
+ 'ignore_lst must be a list of parameters to ignore '
+ '%s (type %s) was given' % (ignore_lst, type(ignore_lst)))
+ # Special case for functools.partial objects
+ if (not inspect.ismethod(func) and not inspect.isfunction(func)):
+ if ignore_lst:
+ warnings.warn('Cannot inspect object %s, ignore list will '
+ 'not work.' % func, stacklevel=2)
+ return {'*': args, '**': kwargs}
+ arg_sig = inspect.signature(func)
+ arg_names = []
+ arg_defaults = []
+ arg_kwonlyargs = []
+ arg_varargs = None
+ arg_varkw = None
+ for param in arg_sig.parameters.values():
+ if param.kind is param.POSITIONAL_OR_KEYWORD:
+ arg_names.append(param.name)
+ elif param.kind is param.KEYWORD_ONLY:
+ arg_names.append(param.name)
+ arg_kwonlyargs.append(param.name)
+ elif param.kind is param.VAR_POSITIONAL:
+ arg_varargs = param.name
+ elif param.kind is param.VAR_KEYWORD:
+ arg_varkw = param.name
+ if param.default is not param.empty:
+ arg_defaults.append(param.default)
+ if inspect.ismethod(func):
+ # First argument is 'self', it has been removed by Python
+ # we need to add it back:
+ args = [func.__self__, ] + args
+ # func is an instance method, inspect.signature(func) does not
+ # include self, we need to fetch it from the class method, i.e
+ # func.__func__
+ class_method_sig = inspect.signature(func.__func__)
+ self_name = next(iter(class_method_sig.parameters))
+ arg_names = [self_name] + arg_names
+ # XXX: Maybe I need an inspect.isbuiltin to detect C-level methods, such
+ # as on ndarrays.
+
+ _, name = get_func_name(func, resolv_alias=False)
+ arg_dict = dict()
+ arg_position = -1
+ for arg_position, arg_name in enumerate(arg_names):
+ if arg_position < len(args):
+ # Positional argument or keyword argument given as positional
+ if arg_name not in arg_kwonlyargs:
+ arg_dict[arg_name] = args[arg_position]
+ else:
+ raise ValueError(
+ "Keyword-only parameter '%s' was passed as "
+ 'positional parameter for %s:\n'
+ ' %s was called.'
+ % (arg_name,
+ _signature_str(name, arg_sig),
+ _function_called_str(name, args, kwargs))
+ )
+
+ else:
+ position = arg_position - len(arg_names)
+ if arg_name in kwargs:
+ arg_dict[arg_name] = kwargs[arg_name]
+ else:
+ try:
+ arg_dict[arg_name] = arg_defaults[position]
+ except (IndexError, KeyError) as e:
+ # Missing argument
+ raise ValueError(
+ 'Wrong number of arguments for %s:\n'
+ ' %s was called.'
+ % (_signature_str(name, arg_sig),
+ _function_called_str(name, args, kwargs))
+ ) from e
+
+ varkwargs = dict()
+ for arg_name, arg_value in sorted(kwargs.items()):
+ if arg_name in arg_dict:
+ arg_dict[arg_name] = arg_value
+ elif arg_varkw is not None:
+ varkwargs[arg_name] = arg_value
+ else:
+ raise TypeError("Ignore list for %s() contains an unexpected "
+ "keyword argument '%s'" % (name, arg_name))
+
+ if arg_varkw is not None:
+ arg_dict['**'] = varkwargs
+ if arg_varargs is not None:
+ varargs = args[arg_position + 1:]
+ arg_dict['*'] = varargs
+
+ # Now remove the arguments to be ignored
+ for item in ignore_lst:
+ if item in arg_dict:
+ arg_dict.pop(item)
+ else:
+ raise ValueError("Ignore list: argument '%s' is not defined for "
+ "function %s"
+ % (item,
+ _signature_str(name, arg_sig))
+ )
+ # XXX: Return a sorted list of pairs?
+ return arg_dict
+
+
+def _format_arg(arg):
+ formatted_arg = pformat(arg, indent=2)
+ if len(formatted_arg) > 1500:
+ formatted_arg = '%s...' % formatted_arg[:700]
+ return formatted_arg
+
+
+def format_signature(func, *args, **kwargs):
+ # XXX: Should this use inspect.formatargvalues/formatargspec?
+ module, name = get_func_name(func)
+ module = [m for m in module if m]
+ if module:
+ module.append(name)
+ module_path = '.'.join(module)
+ else:
+ module_path = name
+ arg_str = list()
+ previous_length = 0
+ for arg in args:
+ formatted_arg = _format_arg(arg)
+ if previous_length > 80:
+ formatted_arg = '\n%s' % formatted_arg
+ previous_length = len(formatted_arg)
+ arg_str.append(formatted_arg)
+ arg_str.extend(['%s=%s' % (v, _format_arg(i)) for v, i in kwargs.items()])
+ arg_str = ', '.join(arg_str)
+
+ signature = '%s(%s)' % (name, arg_str)
+ return module_path, signature
+
+
+def format_call(func, args, kwargs, object_name="Memory"):
+ """ Returns a nicely formatted statement displaying the function
+ call with the given arguments.
+ """
+ path, signature = format_signature(func, *args, **kwargs)
+ msg = '%s\n[%s] Calling %s...\n%s' % (80 * '_', object_name,
+ path, signature)
+ return msg
+ # XXX: Not using logging framework
+ # self.debug(msg)
diff --git a/runtime/Lib/site-packages/joblib/hashing.py b/runtime/Lib/site-packages/joblib/hashing.py
new file mode 100644
index 0000000000000000000000000000000000000000..b983e84fab805b3307174e988d2d79d88e2ddd64
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/hashing.py
@@ -0,0 +1,266 @@
+"""
+Fast cryptographic hash of Python objects, with a special case for fast
+hashing of numpy arrays.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import pickle
+import hashlib
+import sys
+import types
+import struct
+import io
+import decimal
+
+
+Pickler = pickle._Pickler
+
+
+class _ConsistentSet(object):
+ """ Class used to ensure the hash of Sets is preserved
+ whatever the order of its items.
+ """
+ def __init__(self, set_sequence):
+ # Forces order of elements in set to ensure consistent hash.
+ try:
+ # Trying first to order the set assuming the type of elements is
+ # consistent and orderable.
+ # This fails on python 3 when elements are unorderable
+ # but we keep it in a try as it's faster.
+ self._sequence = sorted(set_sequence)
+ except (TypeError, decimal.InvalidOperation):
+ # If elements are unorderable, sorting them using their hash.
+ # This is slower but works in any case.
+ self._sequence = sorted((hash(e) for e in set_sequence))
+
+
+class _MyHash(object):
+ """ Class used to hash objects that won't normally pickle """
+
+ def __init__(self, *args):
+ self.args = args
+
+
+class Hasher(Pickler):
+ """ A subclass of pickler, to do cryptographic hashing, rather than
+ pickling.
+ """
+
+ def __init__(self, hash_name='md5'):
+ self.stream = io.BytesIO()
+ # By default we want a pickle protocol that only changes with
+ # the major python version and not the minor one
+ protocol = 3
+ Pickler.__init__(self, self.stream, protocol=protocol)
+ # Initialise the hash obj
+ self._hash = hashlib.new(hash_name)
+
+ def hash(self, obj, return_digest=True):
+ try:
+ self.dump(obj)
+ except pickle.PicklingError as e:
+ e.args += ('PicklingError while hashing %r: %r' % (obj, e),)
+ raise
+ dumps = self.stream.getvalue()
+ self._hash.update(dumps)
+ if return_digest:
+ return self._hash.hexdigest()
+
+ def save(self, obj):
+ if isinstance(obj, (types.MethodType, type({}.pop))):
+ # the Pickler cannot pickle instance methods; here we decompose
+ # them into components that make them uniquely identifiable
+ if hasattr(obj, '__func__'):
+ func_name = obj.__func__.__name__
+ else:
+ func_name = obj.__name__
+ inst = obj.__self__
+ if type(inst) == type(pickle):
+ obj = _MyHash(func_name, inst.__name__)
+ elif inst is None:
+ # type(None) or type(module) do not pickle
+ obj = _MyHash(func_name, inst)
+ else:
+ cls = obj.__self__.__class__
+ obj = _MyHash(func_name, inst, cls)
+ Pickler.save(self, obj)
+
+ def memoize(self, obj):
+ # We want hashing to be sensitive to value instead of reference.
+ # For example we want ['aa', 'aa'] and ['aa', 'aaZ'[:2]]
+ # to hash to the same value and that's why we disable memoization
+ # for strings
+ if isinstance(obj, (bytes, str)):
+ return
+ Pickler.memoize(self, obj)
+
+ # The dispatch table of the pickler is not accessible in Python
+ # 3, as these lines are only bugware for IPython, we skip them.
+ def save_global(self, obj, name=None, pack=struct.pack):
+ # We have to override this method in order to deal with objects
+ # defined interactively in IPython that are not injected in
+ # __main__
+ kwargs = dict(name=name, pack=pack)
+ del kwargs['pack']
+ try:
+ Pickler.save_global(self, obj, **kwargs)
+ except pickle.PicklingError:
+ Pickler.save_global(self, obj, **kwargs)
+ module = getattr(obj, "__module__", None)
+ if module == '__main__':
+ my_name = name
+ if my_name is None:
+ my_name = obj.__name__
+ mod = sys.modules[module]
+ if not hasattr(mod, my_name):
+ # IPython doesn't inject the variables define
+ # interactively in __main__
+ setattr(mod, my_name, obj)
+
+ dispatch = Pickler.dispatch.copy()
+ # builtin
+ dispatch[type(len)] = save_global
+ # type
+ dispatch[type(object)] = save_global
+ # classobj
+ dispatch[type(Pickler)] = save_global
+ # function
+ dispatch[type(pickle.dump)] = save_global
+
+ def _batch_setitems(self, items):
+ # forces order of keys in dict to ensure consistent hash.
+ try:
+ # Trying first to compare dict assuming the type of keys is
+ # consistent and orderable.
+ # This fails on python 3 when keys are unorderable
+ # but we keep it in a try as it's faster.
+ Pickler._batch_setitems(self, iter(sorted(items)))
+ except TypeError:
+ # If keys are unorderable, sorting them using their hash. This is
+ # slower but works in any case.
+ Pickler._batch_setitems(self, iter(sorted((hash(k), v)
+ for k, v in items)))
+
+ def save_set(self, set_items):
+ # forces order of items in Set to ensure consistent hash
+ Pickler.save(self, _ConsistentSet(set_items))
+
+ dispatch[type(set())] = save_set
+
+
+class NumpyHasher(Hasher):
+ """ Special case the hasher for when numpy is loaded.
+ """
+
+ def __init__(self, hash_name='md5', coerce_mmap=False):
+ """
+ Parameters
+ ----------
+ hash_name: string
+ The hash algorithm to be used
+ coerce_mmap: boolean
+ Make no difference between np.memmap and np.ndarray
+ objects.
+ """
+ self.coerce_mmap = coerce_mmap
+ Hasher.__init__(self, hash_name=hash_name)
+ # delayed import of numpy, to avoid tight coupling
+ import numpy as np
+ self.np = np
+ if hasattr(np, 'getbuffer'):
+ self._getbuffer = np.getbuffer
+ else:
+ self._getbuffer = memoryview
+
+ def save(self, obj):
+ """ Subclass the save method, to hash ndarray subclass, rather
+ than pickling them. Off course, this is a total abuse of
+ the Pickler class.
+ """
+ if isinstance(obj, self.np.ndarray) and not obj.dtype.hasobject:
+ # Compute a hash of the object
+ # The update function of the hash requires a c_contiguous buffer.
+ if obj.shape == ():
+ # 0d arrays need to be flattened because viewing them as bytes
+ # raises a ValueError exception.
+ obj_c_contiguous = obj.flatten()
+ elif obj.flags.c_contiguous:
+ obj_c_contiguous = obj
+ elif obj.flags.f_contiguous:
+ obj_c_contiguous = obj.T
+ else:
+ # Cater for non-single-segment arrays: this creates a
+ # copy, and thus alleviates this issue.
+ # XXX: There might be a more efficient way of doing this
+ obj_c_contiguous = obj.flatten()
+
+ # memoryview is not supported for some dtypes, e.g. datetime64, see
+ # https://github.com/numpy/numpy/issues/4983. The
+ # workaround is to view the array as bytes before
+ # taking the memoryview.
+ self._hash.update(
+ self._getbuffer(obj_c_contiguous.view(self.np.uint8)))
+
+ # We store the class, to be able to distinguish between
+ # Objects with the same binary content, but different
+ # classes.
+ if self.coerce_mmap and isinstance(obj, self.np.memmap):
+ # We don't make the difference between memmap and
+ # normal ndarrays, to be able to reload previously
+ # computed results with memmap.
+ klass = self.np.ndarray
+ else:
+ klass = obj.__class__
+ # We also return the dtype and the shape, to distinguish
+ # different views on the same data with different dtypes.
+
+ # The object will be pickled by the pickler hashed at the end.
+ obj = (klass, ('HASHED', obj.dtype, obj.shape, obj.strides))
+ elif isinstance(obj, self.np.dtype):
+ # numpy.dtype consistent hashing is tricky to get right. This comes
+ # from the fact that atomic np.dtype objects are interned:
+ # ``np.dtype('f4') is np.dtype('f4')``. The situation is
+ # complicated by the fact that this interning does not resist a
+ # simple pickle.load/dump roundtrip:
+ # ``pickle.loads(pickle.dumps(np.dtype('f4'))) is not
+ # np.dtype('f4') Because pickle relies on memoization during
+ # pickling, it is easy to
+ # produce different hashes for seemingly identical objects, such as
+ # ``[np.dtype('f4'), np.dtype('f4')]``
+ # and ``[np.dtype('f4'), pickle.loads(pickle.dumps('f4'))]``.
+ # To prevent memoization from interfering with hashing, we isolate
+ # the serialization (and thus the pickle memoization) of each dtype
+ # using each time a different ``pickle.dumps`` call unrelated to
+ # the current Hasher instance.
+ self._hash.update("_HASHED_DTYPE".encode('utf-8'))
+ self._hash.update(pickle.dumps(obj))
+ return
+ Hasher.save(self, obj)
+
+
+def hash(obj, hash_name='md5', coerce_mmap=False):
+ """ Quick calculation of a hash to identify uniquely Python objects
+ containing numpy arrays.
+
+
+ Parameters
+ -----------
+ hash_name: 'md5' or 'sha1'
+ Hashing algorithm used. sha1 is supposedly safer, but md5 is
+ faster.
+ coerce_mmap: boolean
+ Make no difference between np.memmap and np.ndarray
+ """
+ valid_hash_names = ('md5', 'sha1')
+ if hash_name not in valid_hash_names:
+ raise ValueError("Valid options for 'hash_name' are {}. "
+ "Got hash_name={!r} instead."
+ .format(valid_hash_names, hash_name))
+ if 'numpy' in sys.modules:
+ hasher = NumpyHasher(hash_name=hash_name, coerce_mmap=coerce_mmap)
+ else:
+ hasher = Hasher(hash_name=hash_name)
+ return hasher.hash(obj)
diff --git a/runtime/Lib/site-packages/joblib/logger.py b/runtime/Lib/site-packages/joblib/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..f30efef8535d26421694c677d88f1aebb3615bc7
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/logger.py
@@ -0,0 +1,156 @@
+"""
+Helpers for logging.
+
+This module needs much love to become useful.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2008 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+from __future__ import print_function
+
+import time
+import sys
+import os
+import shutil
+import logging
+import pprint
+
+from .disk import mkdirp
+
+
+def _squeeze_time(t):
+ """Remove .1s to the time under Windows: this is the time it take to
+ stat files. This is needed to make results similar to timings under
+ Unix, for tests
+ """
+ if sys.platform.startswith('win'):
+ return max(0, t - .1)
+ else:
+ return t
+
+
+def format_time(t):
+ t = _squeeze_time(t)
+ return "%.1fs, %.1fmin" % (t, t / 60.)
+
+
+def short_format_time(t):
+ t = _squeeze_time(t)
+ if t > 60:
+ return "%4.1fmin" % (t / 60.)
+ else:
+ return " %5.1fs" % (t)
+
+
+def pformat(obj, indent=0, depth=3):
+ if 'numpy' in sys.modules:
+ import numpy as np
+ print_options = np.get_printoptions()
+ np.set_printoptions(precision=6, threshold=64, edgeitems=1)
+ else:
+ print_options = None
+ out = pprint.pformat(obj, depth=depth, indent=indent)
+ if print_options:
+ np.set_printoptions(**print_options)
+ return out
+
+
+###############################################################################
+# class `Logger`
+###############################################################################
+class Logger(object):
+ """ Base class for logging messages.
+ """
+
+ def __init__(self, depth=3):
+ """
+ Parameters
+ ----------
+ depth: int, optional
+ The depth of objects printed.
+ """
+ self.depth = depth
+
+ def warn(self, msg):
+ logging.warning("[%s]: %s" % (self, msg))
+
+ def debug(self, msg):
+ # XXX: This conflicts with the debug flag used in children class
+ logging.debug("[%s]: %s" % (self, msg))
+
+ def format(self, obj, indent=0):
+ """Return the formatted representation of the object."""
+ return pformat(obj, indent=indent, depth=self.depth)
+
+
+###############################################################################
+# class `PrintTime`
+###############################################################################
+class PrintTime(object):
+ """ Print and log messages while keeping track of time.
+ """
+
+ def __init__(self, logfile=None, logdir=None):
+ if logfile is not None and logdir is not None:
+ raise ValueError('Cannot specify both logfile and logdir')
+ # XXX: Need argument docstring
+ self.last_time = time.time()
+ self.start_time = self.last_time
+ if logdir is not None:
+ logfile = os.path.join(logdir, 'joblib.log')
+ self.logfile = logfile
+ if logfile is not None:
+ mkdirp(os.path.dirname(logfile))
+ if os.path.exists(logfile):
+ # Rotate the logs
+ for i in range(1, 9):
+ try:
+ shutil.move(logfile + '.%i' % i,
+ logfile + '.%i' % (i + 1))
+ except:
+ "No reason failing here"
+ # Use a copy rather than a move, so that a process
+ # monitoring this file does not get lost.
+ try:
+ shutil.copy(logfile, logfile + '.1')
+ except:
+ "No reason failing here"
+ try:
+ with open(logfile, 'w') as logfile:
+ logfile.write('\nLogging joblib python script\n')
+ logfile.write('\n---%s---\n' % time.ctime(self.last_time))
+ except:
+ """ Multiprocessing writing to files can create race
+ conditions. Rather fail silently than crash the
+ computation.
+ """
+ # XXX: We actually need a debug flag to disable this
+ # silent failure.
+
+ def __call__(self, msg='', total=False):
+ """ Print the time elapsed between the last call and the current
+ call, with an optional message.
+ """
+ if not total:
+ time_lapse = time.time() - self.last_time
+ full_msg = "%s: %s" % (msg, format_time(time_lapse))
+ else:
+ # FIXME: Too much logic duplicated
+ time_lapse = time.time() - self.start_time
+ full_msg = "%s: %.2fs, %.1f min" % (msg, time_lapse,
+ time_lapse / 60)
+ print(full_msg, file=sys.stderr)
+ if self.logfile is not None:
+ try:
+ with open(self.logfile, 'a') as f:
+ print(full_msg, file=f)
+ except:
+ """ Multiprocessing writing to files can create race
+ conditions. Rather fail silently than crash the
+ calculation.
+ """
+ # XXX: We actually need a debug flag to disable this
+ # silent failure.
+ self.last_time = time.time()
diff --git a/runtime/Lib/site-packages/joblib/memory.py b/runtime/Lib/site-packages/joblib/memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc58fdfdce43fb9d3cc68e9c3a1f34f2b191ae3
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/memory.py
@@ -0,0 +1,1030 @@
+"""
+A context object for caching a function's return value each time it
+is called with the same input arguments.
+
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+
+from __future__ import with_statement
+import os
+import time
+import pathlib
+import pydoc
+import re
+import functools
+import traceback
+import warnings
+import inspect
+import weakref
+
+from tokenize import open as open_py_source
+
+# Local imports
+from . import hashing
+from .func_inspect import get_func_code, get_func_name, filter_args
+from .func_inspect import format_call
+from .func_inspect import format_signature
+from .logger import Logger, format_time, pformat
+from ._store_backends import StoreBackendBase, FileSystemStoreBackend
+
+
+FIRST_LINE_TEXT = "# first line:"
+
+# TODO: The following object should have a data store object as a sub
+# object, and the interface to persist and query should be separated in
+# the data store.
+#
+# This would enable creating 'Memory' objects with a different logic for
+# pickling that would simply span a MemorizedFunc with the same
+# store (or do we want to copy it to avoid cross-talks?), for instance to
+# implement HDF5 pickling.
+
+# TODO: Same remark for the logger, and probably use the Python logging
+# mechanism.
+
+
+def extract_first_line(func_code):
+ """ Extract the first line information from the function code
+ text if available.
+ """
+ if func_code.startswith(FIRST_LINE_TEXT):
+ func_code = func_code.split('\n')
+ first_line = int(func_code[0][len(FIRST_LINE_TEXT):])
+ func_code = '\n'.join(func_code[1:])
+ else:
+ first_line = -1
+ return func_code, first_line
+
+
+class JobLibCollisionWarning(UserWarning):
+ """ Warn that there might be a collision between names of functions.
+ """
+
+
+_STORE_BACKENDS = {'local': FileSystemStoreBackend}
+
+
+def register_store_backend(backend_name, backend):
+ """Extend available store backends.
+
+ The Memory, MemorizeResult and MemorizeFunc objects are designed to be
+ agnostic to the type of store used behind. By default, the local file
+ system is used but this function gives the possibility to extend joblib's
+ memory pattern with other types of storage such as cloud storage (S3, GCS,
+ OpenStack, HadoopFS, etc) or blob DBs.
+
+ Parameters
+ ----------
+ backend_name: str
+ The name identifying the store backend being registered. For example,
+ 'local' is used with FileSystemStoreBackend.
+ backend: StoreBackendBase subclass
+ The name of a class that implements the StoreBackendBase interface.
+
+ """
+ if not isinstance(backend_name, str):
+ raise ValueError("Store backend name should be a string, "
+ "'{0}' given.".format(backend_name))
+ if backend is None or not issubclass(backend, StoreBackendBase):
+ raise ValueError("Store backend should inherit "
+ "StoreBackendBase, "
+ "'{0}' given.".format(backend))
+
+ _STORE_BACKENDS[backend_name] = backend
+
+
+def _store_backend_factory(backend, location, verbose=0, backend_options=None):
+ """Return the correct store object for the given location."""
+ if backend_options is None:
+ backend_options = {}
+
+ if isinstance(location, pathlib.Path):
+ location = str(location)
+
+ if isinstance(location, StoreBackendBase):
+ return location
+ elif isinstance(location, str):
+ obj = None
+ location = os.path.expanduser(location)
+ # The location is not a local file system, we look in the
+ # registered backends if there's one matching the given backend
+ # name.
+ for backend_key, backend_obj in _STORE_BACKENDS.items():
+ if backend == backend_key:
+ obj = backend_obj()
+
+ # By default, we assume the FileSystemStoreBackend can be used if no
+ # matching backend could be found.
+ if obj is None:
+ raise TypeError('Unknown location {0} or backend {1}'.format(
+ location, backend))
+
+ # The store backend is configured with the extra named parameters,
+ # some of them are specific to the underlying store backend.
+ obj.configure(location, verbose=verbose,
+ backend_options=backend_options)
+ return obj
+ elif location is not None:
+ warnings.warn(
+ "Instantiating a backend using a {} as a location is not "
+ "supported by joblib. Returning None instead.".format(
+ location.__class__.__name__), UserWarning)
+
+ return None
+
+
+def _get_func_fullname(func):
+ """Compute the part of part associated with a function."""
+ modules, funcname = get_func_name(func)
+ modules.append(funcname)
+ return os.path.join(*modules)
+
+
+def _build_func_identifier(func):
+ """Build a roughly unique identifier for the cached function."""
+ parts = []
+ if isinstance(func, str):
+ parts.append(func)
+ else:
+ parts.append(_get_func_fullname(func))
+
+ # We reuse historical fs-like way of building a function identifier
+ return os.path.join(*parts)
+
+
+def _format_load_msg(func_id, args_id, timestamp=None, metadata=None):
+ """ Helper function to format the message when loading the results.
+ """
+ signature = ""
+ try:
+ if metadata is not None:
+ args = ", ".join(['%s=%s' % (name, value)
+ for name, value
+ in metadata['input_args'].items()])
+ signature = "%s(%s)" % (os.path.basename(func_id), args)
+ else:
+ signature = os.path.basename(func_id)
+ except KeyError:
+ pass
+
+ if timestamp is not None:
+ ts_string = "{0: <16}".format(format_time(time.time() - timestamp))
+ else:
+ ts_string = ""
+ return '[Memory]{0}: Loading {1}'.format(ts_string, str(signature))
+
+
+# An in-memory store to avoid looking at the disk-based function
+# source code to check if a function definition has changed
+_FUNCTION_HASHES = weakref.WeakKeyDictionary()
+
+
+###############################################################################
+# class `MemorizedResult`
+###############################################################################
+class MemorizedResult(Logger):
+ """Object representing a cached value.
+
+ Attributes
+ ----------
+ location: str
+ The location of joblib cache. Depends on the store backend used.
+
+ func: function or str
+ function whose output is cached. The string case is intended only for
+ instantiation based on the output of repr() on another instance.
+ (namely eval(repr(memorized_instance)) works).
+
+ argument_hash: str
+ hash of the function arguments.
+
+ backend: str
+ Type of store backend for reading/writing cache files.
+ Default is 'local'.
+
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
+ The memmapping mode used when loading from cache numpy arrays. See
+ numpy.load for the meaning of the different values.
+
+ verbose: int
+ verbosity level (0 means no message).
+
+ timestamp, metadata: string
+ for internal use only.
+ """
+ def __init__(self, location, func, args_id, backend='local',
+ mmap_mode=None, verbose=0, timestamp=None, metadata=None):
+ Logger.__init__(self)
+ self.func_id = _build_func_identifier(func)
+ if isinstance(func, str):
+ self.func = func
+ else:
+ self.func = self.func_id
+ self.args_id = args_id
+ self.store_backend = _store_backend_factory(backend, location,
+ verbose=verbose)
+ self.mmap_mode = mmap_mode
+
+ if metadata is not None:
+ self.metadata = metadata
+ else:
+ self.metadata = self.store_backend.get_metadata(
+ [self.func_id, self.args_id])
+
+ self.duration = self.metadata.get('duration', None)
+ self.verbose = verbose
+ self.timestamp = timestamp
+
+ @property
+ def argument_hash(self):
+ warnings.warn(
+ "The 'argument_hash' attribute has been deprecated in version "
+ "0.12 and will be removed in version 0.14.\n"
+ "Use `args_id` attribute instead.",
+ DeprecationWarning, stacklevel=2)
+ return self.args_id
+
+ def get(self):
+ """Read value from cache and return it."""
+ if self.verbose:
+ msg = _format_load_msg(self.func_id, self.args_id,
+ timestamp=self.timestamp,
+ metadata=self.metadata)
+ else:
+ msg = None
+
+ try:
+ return self.store_backend.load_item(
+ [self.func_id, self.args_id], msg=msg, verbose=self.verbose)
+ except ValueError as exc:
+ new_exc = KeyError(
+ "Error while trying to load a MemorizedResult's value. "
+ "It seems that this folder is corrupted : {}".format(
+ os.path.join(
+ self.store_backend.location, self.func_id,
+ self.args_id)
+ ))
+ raise new_exc from exc
+
+ def clear(self):
+ """Clear value from cache"""
+ self.store_backend.clear_item([self.func_id, self.args_id])
+
+ def __repr__(self):
+ return ('{class_name}(location="{location}", func="{func}", '
+ 'args_id="{args_id}")'
+ .format(class_name=self.__class__.__name__,
+ location=self.store_backend.location,
+ func=self.func,
+ args_id=self.args_id
+ ))
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state['timestamp'] = None
+ return state
+
+
+class NotMemorizedResult(object):
+ """Class representing an arbitrary value.
+
+ This class is a replacement for MemorizedResult when there is no cache.
+ """
+ __slots__ = ('value', 'valid')
+
+ def __init__(self, value):
+ self.value = value
+ self.valid = True
+
+ def get(self):
+ if self.valid:
+ return self.value
+ else:
+ raise KeyError("No value stored.")
+
+ def clear(self):
+ self.valid = False
+ self.value = None
+
+ def __repr__(self):
+ if self.valid:
+ return ('{class_name}({value})'
+ .format(class_name=self.__class__.__name__,
+ value=pformat(self.value)))
+ else:
+ return self.__class__.__name__ + ' with no value'
+
+ # __getstate__ and __setstate__ are required because of __slots__
+ def __getstate__(self):
+ return {"valid": self.valid, "value": self.value}
+
+ def __setstate__(self, state):
+ self.valid = state["valid"]
+ self.value = state["value"]
+
+
+###############################################################################
+# class `NotMemorizedFunc`
+###############################################################################
+class NotMemorizedFunc(object):
+ """No-op object decorating a function.
+
+ This class replaces MemorizedFunc when there is no cache. It provides an
+ identical API but does not write anything on disk.
+
+ Attributes
+ ----------
+ func: callable
+ Original undecorated function.
+ """
+ # Should be a light as possible (for speed)
+ def __init__(self, func):
+ self.func = func
+
+ def __call__(self, *args, **kwargs):
+ return self.func(*args, **kwargs)
+
+ def call_and_shelve(self, *args, **kwargs):
+ return NotMemorizedResult(self.func(*args, **kwargs))
+
+ def __repr__(self):
+ return '{0}(func={1})'.format(self.__class__.__name__, self.func)
+
+ def clear(self, warn=True):
+ # Argument "warn" is for compatibility with MemorizedFunc.clear
+ pass
+
+ def call(self, *args, **kwargs):
+ return self.func(*args, **kwargs)
+
+ def check_call_in_cache(self, *args, **kwargs):
+ return False
+
+
+###############################################################################
+# class `MemorizedFunc`
+###############################################################################
+class MemorizedFunc(Logger):
+ """Callable object decorating a function for caching its return value
+ each time it is called.
+
+ Methods are provided to inspect the cache or clean it.
+
+ Attributes
+ ----------
+ func: callable
+ The original, undecorated, function.
+
+ location: string
+ The location of joblib cache. Depends on the store backend used.
+
+ backend: str
+ Type of store backend for reading/writing cache files.
+ Default is 'local', in which case the location is the path to a
+ disk storage.
+
+ ignore: list or None
+ List of variable names to ignore when choosing whether to
+ recompute.
+
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
+ The memmapping mode used when loading from cache
+ numpy arrays. See numpy.load for the meaning of the different
+ values.
+
+ compress: boolean, or integer
+ Whether to zip the stored data on disk. If an integer is
+ given, it should be between 1 and 9, and sets the amount
+ of compression. Note that compressed arrays cannot be
+ read by memmapping.
+
+ verbose: int, optional
+ The verbosity flag, controls messages that are issued as
+ the function is evaluated.
+ """
+ # ------------------------------------------------------------------------
+ # Public interface
+ # ------------------------------------------------------------------------
+
+ def __init__(self, func, location, backend='local', ignore=None,
+ mmap_mode=None, compress=False, verbose=1, timestamp=None):
+ Logger.__init__(self)
+ self.mmap_mode = mmap_mode
+ self.compress = compress
+ self.func = func
+
+ if ignore is None:
+ ignore = []
+ self.ignore = ignore
+ self._verbose = verbose
+
+ # retrieve store object from backend type and location.
+ self.store_backend = _store_backend_factory(backend, location,
+ verbose=verbose,
+ backend_options=dict(
+ compress=compress,
+ mmap_mode=mmap_mode),
+ )
+ if self.store_backend is not None:
+ # Create func directory on demand.
+ self.store_backend.\
+ store_cached_func_code([_build_func_identifier(self.func)])
+
+ if timestamp is None:
+ timestamp = time.time()
+ self.timestamp = timestamp
+ try:
+ functools.update_wrapper(self, func)
+ except:
+ " Objects like ufunc don't like that "
+ if inspect.isfunction(func):
+ doc = pydoc.TextDoc().document(func)
+ # Remove blank line
+ doc = doc.replace('\n', '\n\n', 1)
+ # Strip backspace-overprints for compatibility with autodoc
+ doc = re.sub('\x08.', '', doc)
+ else:
+ # Pydoc does a poor job on other objects
+ doc = func.__doc__
+ self.__doc__ = 'Memoized version of %s' % doc
+
+ self._func_code_info = None
+ self._func_code_id = None
+
+ def _cached_call(self, args, kwargs, shelving=False):
+ """Call wrapped function and cache result, or read cache if available.
+
+ This function returns the wrapped function output and some metadata.
+
+ Arguments:
+ ----------
+
+ args, kwargs: list and dict
+ input arguments for wrapped function
+
+ shelving: bool
+ True when called via the call_and_shelve function.
+
+
+ Returns
+ -------
+ output: value or tuple or None
+ Output of the wrapped function.
+ If shelving is True and the call has been already cached,
+ output is None.
+
+ argument_hash: string
+ Hash of function arguments.
+
+ metadata: dict
+ Some metadata about wrapped function call (see _persist_input()).
+ """
+ func_id, args_id = self._get_output_identifiers(*args, **kwargs)
+ metadata = None
+ msg = None
+
+ # Whether or not the memorized function must be called
+ must_call = False
+
+ # FIXME: The statements below should be try/excepted
+ # Compare the function code with the previous to see if the
+ # function code has changed
+ if not (self._check_previous_func_code(stacklevel=4) and
+ self.store_backend.contains_item([func_id, args_id])):
+ if self._verbose > 10:
+ _, name = get_func_name(self.func)
+ self.warn('Computing func {0}, argument hash {1} '
+ 'in location {2}'
+ .format(name, args_id,
+ self.store_backend.
+ get_cached_func_info([func_id])['location']))
+ must_call = True
+ else:
+ try:
+ t0 = time.time()
+ if self._verbose:
+ msg = _format_load_msg(func_id, args_id,
+ timestamp=self.timestamp,
+ metadata=metadata)
+
+ if not shelving:
+ # When shelving, we do not need to load the output
+ out = self.store_backend.load_item(
+ [func_id, args_id],
+ msg=msg,
+ verbose=self._verbose)
+ else:
+ out = None
+
+ if self._verbose > 4:
+ t = time.time() - t0
+ _, name = get_func_name(self.func)
+ msg = '%s cache loaded - %s' % (name, format_time(t))
+ print(max(0, (80 - len(msg))) * '_' + msg)
+ except Exception:
+ # XXX: Should use an exception logger
+ _, signature = format_signature(self.func, *args, **kwargs)
+ self.warn('Exception while loading results for '
+ '{}\n {}'.format(signature, traceback.format_exc()))
+
+ must_call = True
+
+ if must_call:
+ out, metadata = self.call(*args, **kwargs)
+ if self.mmap_mode is not None:
+ # Memmap the output at the first call to be consistent with
+ # later calls
+ if self._verbose:
+ msg = _format_load_msg(func_id, args_id,
+ timestamp=self.timestamp,
+ metadata=metadata)
+ out = self.store_backend.load_item([func_id, args_id], msg=msg,
+ verbose=self._verbose)
+
+ return (out, args_id, metadata)
+
+ @property
+ def func_code_info(self):
+ # 3-tuple property containing: the function source code, source file,
+ # and first line of the code inside the source file
+ if hasattr(self.func, '__code__'):
+ if self._func_code_id is None:
+ self._func_code_id = id(self.func.__code__)
+ elif id(self.func.__code__) != self._func_code_id:
+ # Be robust to dynamic reassignments of self.func.__code__
+ self._func_code_info = None
+
+ if self._func_code_info is None:
+ # Cache the source code of self.func . Provided that get_func_code
+ # (which should be called once on self) gets called in the process
+ # in which self.func was defined, this caching mechanism prevents
+ # undesired cache clearing when the cached function is called in
+ # an environment where the introspection utilities get_func_code
+ # relies on do not work (typically, in joblib child processes).
+ # See #1035 for more info
+ # TODO (pierreglaser): do the same with get_func_name?
+ self._func_code_info = get_func_code(self.func)
+ return self._func_code_info
+
+ def call_and_shelve(self, *args, **kwargs):
+ """Call wrapped function, cache result and return a reference.
+
+ This method returns a reference to the cached result instead of the
+ result itself. The reference object is small and pickeable, allowing
+ to send or store it easily. Call .get() on reference object to get
+ result.
+
+ Returns
+ -------
+ cached_result: MemorizedResult or NotMemorizedResult
+ reference to the value returned by the wrapped function. The
+ class "NotMemorizedResult" is used when there is no cache
+ activated (e.g. location=None in Memory).
+ """
+ _, args_id, metadata = self._cached_call(args, kwargs, shelving=True)
+ return MemorizedResult(self.store_backend, self.func, args_id,
+ metadata=metadata, verbose=self._verbose - 1,
+ timestamp=self.timestamp)
+
+ def __call__(self, *args, **kwargs):
+ return self._cached_call(args, kwargs)[0]
+
+ def __getstate__(self):
+ # Make sure self.func's source is introspected prior to being pickled -
+ # code introspection utilities typically do not work inside child
+ # processes
+ _ = self.func_code_info
+
+ # We don't store the timestamp when pickling, to avoid the hash
+ # depending from it.
+ state = self.__dict__.copy()
+ state['timestamp'] = None
+
+ # Invalidate the code id as id(obj) will be different in the child
+ state['_func_code_id'] = None
+
+ return state
+
+ def check_call_in_cache(self, *args, **kwargs):
+ """Check if function call is in the memory cache.
+
+ Does not call the function or do any work besides func inspection
+ and arg hashing.
+
+ Returns
+ -------
+ is_call_in_cache: bool
+ Whether or not the result of the function has been cached
+ for the input arguments that have been passed.
+ """
+ func_id, args_id = self._get_output_identifiers(*args, **kwargs)
+ return self.store_backend.contains_item((func_id, args_id))
+
+ # ------------------------------------------------------------------------
+ # Private interface
+ # ------------------------------------------------------------------------
+
+ def _get_argument_hash(self, *args, **kwargs):
+ return hashing.hash(filter_args(self.func, self.ignore, args, kwargs),
+ coerce_mmap=(self.mmap_mode is not None))
+
+ def _get_output_identifiers(self, *args, **kwargs):
+ """Return the func identifier and input parameter hash of a result."""
+ func_id = _build_func_identifier(self.func)
+ argument_hash = self._get_argument_hash(*args, **kwargs)
+ return func_id, argument_hash
+
+ def _hash_func(self):
+ """Hash a function to key the online cache"""
+ func_code_h = hash(getattr(self.func, '__code__', None))
+ return id(self.func), hash(self.func), func_code_h
+
+ def _write_func_code(self, func_code, first_line):
+ """ Write the function code and the filename to a file.
+ """
+ # We store the first line because the filename and the function
+ # name is not always enough to identify a function: people
+ # sometimes have several functions named the same way in a
+ # file. This is bad practice, but joblib should be robust to bad
+ # practice.
+ func_id = _build_func_identifier(self.func)
+ func_code = u'%s %i\n%s' % (FIRST_LINE_TEXT, first_line, func_code)
+ self.store_backend.store_cached_func_code([func_id], func_code)
+
+ # Also store in the in-memory store of function hashes
+ is_named_callable = False
+ is_named_callable = (hasattr(self.func, '__name__') and
+ self.func.__name__ != '')
+ if is_named_callable:
+ # Don't do this for lambda functions or strange callable
+ # objects, as it ends up being too fragile
+ func_hash = self._hash_func()
+ try:
+ _FUNCTION_HASHES[self.func] = func_hash
+ except TypeError:
+ # Some callable are not hashable
+ pass
+
+ def _check_previous_func_code(self, stacklevel=2):
+ """
+ stacklevel is the depth a which this function is called, to
+ issue useful warnings to the user.
+ """
+ # First check if our function is in the in-memory store.
+ # Using the in-memory store not only makes things faster, but it
+ # also renders us robust to variations of the files when the
+ # in-memory version of the code does not vary
+ try:
+ if self.func in _FUNCTION_HASHES:
+ # We use as an identifier the id of the function and its
+ # hash. This is more likely to falsely change than have hash
+ # collisions, thus we are on the safe side.
+ func_hash = self._hash_func()
+ if func_hash == _FUNCTION_HASHES[self.func]:
+ return True
+ except TypeError:
+ # Some callables are not hashable
+ pass
+
+ # Here, we go through some effort to be robust to dynamically
+ # changing code and collision. We cannot inspect.getsource
+ # because it is not reliable when using IPython's magic "%run".
+ func_code, source_file, first_line = self.func_code_info
+ func_id = _build_func_identifier(self.func)
+
+ try:
+ old_func_code, old_first_line =\
+ extract_first_line(
+ self.store_backend.get_cached_func_code([func_id]))
+ except (IOError, OSError): # some backend can also raise OSError
+ self._write_func_code(func_code, first_line)
+ return False
+ if old_func_code == func_code:
+ return True
+
+ # We have differing code, is this because we are referring to
+ # different functions, or because the function we are referring to has
+ # changed?
+
+ _, func_name = get_func_name(self.func, resolv_alias=False,
+ win_characters=False)
+ if old_first_line == first_line == -1 or func_name == '':
+ if not first_line == -1:
+ func_description = ("{0} ({1}:{2})"
+ .format(func_name, source_file,
+ first_line))
+ else:
+ func_description = func_name
+ warnings.warn(JobLibCollisionWarning(
+ "Cannot detect name collisions for function '{0}'"
+ .format(func_description)), stacklevel=stacklevel)
+
+ # Fetch the code at the old location and compare it. If it is the
+ # same than the code store, we have a collision: the code in the
+ # file has not changed, but the name we have is pointing to a new
+ # code block.
+ if not old_first_line == first_line and source_file is not None:
+ possible_collision = False
+ if os.path.exists(source_file):
+ _, func_name = get_func_name(self.func, resolv_alias=False)
+ num_lines = len(func_code.split('\n'))
+ with open_py_source(source_file) as f:
+ on_disk_func_code = f.readlines()[
+ old_first_line - 1:old_first_line - 1 + num_lines - 1]
+ on_disk_func_code = ''.join(on_disk_func_code)
+ possible_collision = (on_disk_func_code.rstrip() ==
+ old_func_code.rstrip())
+ else:
+ possible_collision = source_file.startswith(' 10:
+ _, func_name = get_func_name(self.func, resolv_alias=False)
+ self.warn("Function {0} (identified by {1}) has changed"
+ ".".format(func_name, func_id))
+ self.clear(warn=True)
+ return False
+
+ def clear(self, warn=True):
+ """Empty the function's cache."""
+ func_id = _build_func_identifier(self.func)
+
+ if self._verbose > 0 and warn:
+ self.warn("Clearing function cache identified by %s" % func_id)
+ self.store_backend.clear_path([func_id, ])
+
+ func_code, _, first_line = self.func_code_info
+ self._write_func_code(func_code, first_line)
+
+ def call(self, *args, **kwargs):
+ """ Force the execution of the function with the given arguments and
+ persist the output values.
+ """
+ start_time = time.time()
+ func_id, args_id = self._get_output_identifiers(*args, **kwargs)
+ if self._verbose > 0:
+ print(format_call(self.func, args, kwargs))
+ output = self.func(*args, **kwargs)
+ self.store_backend.dump_item(
+ [func_id, args_id], output, verbose=self._verbose)
+
+ duration = time.time() - start_time
+ metadata = self._persist_input(duration, args, kwargs)
+
+ if self._verbose > 0:
+ _, name = get_func_name(self.func)
+ msg = '%s - %s' % (name, format_time(duration))
+ print(max(0, (80 - len(msg))) * '_' + msg)
+ return output, metadata
+
+ def _persist_input(self, duration, args, kwargs, this_duration_limit=0.5):
+ """ Save a small summary of the call using json format in the
+ output directory.
+
+ output_dir: string
+ directory where to write metadata.
+
+ duration: float
+ time taken by hashing input arguments, calling the wrapped
+ function and persisting its output.
+
+ args, kwargs: list and dict
+ input arguments for wrapped function
+
+ this_duration_limit: float
+ Max execution time for this function before issuing a warning.
+ """
+ start_time = time.time()
+ argument_dict = filter_args(self.func, self.ignore,
+ args, kwargs)
+
+ input_repr = dict((k, repr(v)) for k, v in argument_dict.items())
+ # This can fail due to race-conditions with multiple
+ # concurrent joblibs removing the file or the directory
+ metadata = {"duration": duration, "input_args": input_repr}
+
+ func_id, args_id = self._get_output_identifiers(*args, **kwargs)
+ self.store_backend.store_metadata([func_id, args_id], metadata)
+
+ this_duration = time.time() - start_time
+ if this_duration > this_duration_limit:
+ # This persistence should be fast. It will not be if repr() takes
+ # time and its output is large, because json.dump will have to
+ # write a large file. This should not be an issue with numpy arrays
+ # for which repr() always output a short representation, but can
+ # be with complex dictionaries. Fixing the problem should be a
+ # matter of replacing repr() above by something smarter.
+ warnings.warn("Persisting input arguments took %.2fs to run.\n"
+ "If this happens often in your code, it can cause "
+ "performance problems \n"
+ "(results will be correct in all cases). \n"
+ "The reason for this is probably some large input "
+ "arguments for a wrapped\n"
+ " function (e.g. large strings).\n"
+ "THIS IS A JOBLIB ISSUE. If you can, kindly provide "
+ "the joblib's team with an\n"
+ " example so that they can fix the problem."
+ % this_duration, stacklevel=5)
+ return metadata
+
+ # ------------------------------------------------------------------------
+ # Private `object` interface
+ # ------------------------------------------------------------------------
+
+ def __repr__(self):
+ return '{class_name}(func={func}, location={location})'.format(
+ class_name=self.__class__.__name__,
+ func=self.func,
+ location=self.store_backend.location,)
+
+
+###############################################################################
+# class `Memory`
+###############################################################################
+class Memory(Logger):
+ """ A context object for caching a function's return value each time it
+ is called with the same input arguments.
+
+ All values are cached on the filesystem, in a deep directory
+ structure.
+
+ Read more in the :ref:`User Guide `.
+
+ Parameters
+ ----------
+ location: str, pathlib.Path or None
+ The path of the base directory to use as a data store
+ or None. If None is given, no caching is done and
+ the Memory object is completely transparent. This option
+ replaces cachedir since version 0.12.
+
+ backend: str, optional
+ Type of store backend for reading/writing cache files.
+ Default: 'local'.
+ The 'local' backend is using regular filesystem operations to
+ manipulate data (open, mv, etc) in the backend.
+
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
+ The memmapping mode used when loading from cache
+ numpy arrays. See numpy.load for the meaning of the
+ arguments.
+
+ compress: boolean, or integer, optional
+ Whether to zip the stored data on disk. If an integer is
+ given, it should be between 1 and 9, and sets the amount
+ of compression. Note that compressed arrays cannot be
+ read by memmapping.
+
+ verbose: int, optional
+ Verbosity flag, controls the debug messages that are issued
+ as functions are evaluated.
+
+ bytes_limit: int, optional
+ Limit in bytes of the size of the cache. By default, the size of
+ the cache is unlimited. When reducing the size of the cache,
+ ``joblib`` keeps the most recently accessed items first.
+
+ **Note:** You need to call :meth:`joblib.Memory.reduce_size` to
+ actually reduce the cache size to be less than ``bytes_limit``.
+
+ backend_options: dict, optional
+ Contains a dictionary of named parameters used to configure
+ the store backend.
+ """
+ # ------------------------------------------------------------------------
+ # Public interface
+ # ------------------------------------------------------------------------
+
+ def __init__(self, location=None, backend='local',
+ mmap_mode=None, compress=False, verbose=1, bytes_limit=None,
+ backend_options=None):
+ Logger.__init__(self)
+ self._verbose = verbose
+ self.mmap_mode = mmap_mode
+ self.timestamp = time.time()
+ self.bytes_limit = bytes_limit
+ self.backend = backend
+ self.compress = compress
+ if backend_options is None:
+ backend_options = {}
+ self.backend_options = backend_options
+
+ if compress and mmap_mode is not None:
+ warnings.warn('Compressed results cannot be memmapped',
+ stacklevel=2)
+
+ self.location = location
+ if isinstance(location, str):
+ location = os.path.join(location, 'joblib')
+
+ self.store_backend = _store_backend_factory(
+ backend, location, verbose=self._verbose,
+ backend_options=dict(compress=compress, mmap_mode=mmap_mode,
+ **backend_options))
+
+ def cache(self, func=None, ignore=None, verbose=None, mmap_mode=False):
+ """ Decorates the given function func to only compute its return
+ value for input arguments not cached on disk.
+
+ Parameters
+ ----------
+ func: callable, optional
+ The function to be decorated
+ ignore: list of strings
+ A list of arguments name to ignore in the hashing
+ verbose: integer, optional
+ The verbosity mode of the function. By default that
+ of the memory object is used.
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
+ The memmapping mode used when loading from cache
+ numpy arrays. See numpy.load for the meaning of the
+ arguments. By default that of the memory object is used.
+
+ Returns
+ -------
+ decorated_func: MemorizedFunc object
+ The returned object is a MemorizedFunc object, that is
+ callable (behaves like a function), but offers extra
+ methods for cache lookup and management. See the
+ documentation for :class:`joblib.memory.MemorizedFunc`.
+ """
+ if func is None:
+ # Partial application, to be able to specify extra keyword
+ # arguments in decorators
+ return functools.partial(self.cache, ignore=ignore,
+ verbose=verbose, mmap_mode=mmap_mode)
+ if self.store_backend is None:
+ return NotMemorizedFunc(func)
+ if verbose is None:
+ verbose = self._verbose
+ if mmap_mode is False:
+ mmap_mode = self.mmap_mode
+ if isinstance(func, MemorizedFunc):
+ func = func.func
+ return MemorizedFunc(func, location=self.store_backend,
+ backend=self.backend,
+ ignore=ignore, mmap_mode=mmap_mode,
+ compress=self.compress,
+ verbose=verbose, timestamp=self.timestamp)
+
+ def clear(self, warn=True):
+ """ Erase the complete cache directory.
+ """
+ if warn:
+ self.warn('Flushing completely the cache')
+ if self.store_backend is not None:
+ self.store_backend.clear()
+
+ # As the cache in completely clear, make sure the _FUNCTION_HASHES
+ # cache is also reset. Else, for a function that is present in this
+ # table, results cached after this clear will be have cache miss
+ # as the function code is not re-written.
+ _FUNCTION_HASHES.clear()
+
+ def reduce_size(self):
+ """Remove cache elements to make cache size fit in ``bytes_limit``."""
+ if self.bytes_limit is not None and self.store_backend is not None:
+ self.store_backend.reduce_store_size(self.bytes_limit)
+
+ def eval(self, func, *args, **kwargs):
+ """ Eval function func with arguments `*args` and `**kwargs`,
+ in the context of the memory.
+
+ This method works similarly to the builtin `apply`, except
+ that the function is called only if the cache is not
+ up to date.
+
+ """
+ if self.store_backend is None:
+ return func(*args, **kwargs)
+ return self.cache(func)(*args, **kwargs)
+
+ # ------------------------------------------------------------------------
+ # Private `object` interface
+ # ------------------------------------------------------------------------
+
+ def __repr__(self):
+ return '{class_name}(location={location})'.format(
+ class_name=self.__class__.__name__,
+ location=(None if self.store_backend is None
+ else self.store_backend.location))
+
+ def __getstate__(self):
+ """ We don't store the timestamp when pickling, to avoid the hash
+ depending from it.
+ """
+ state = self.__dict__.copy()
+ state['timestamp'] = None
+ return state
diff --git a/runtime/Lib/site-packages/joblib/my_exceptions.py b/runtime/Lib/site-packages/joblib/my_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d379bb21e3986f348f5d0ceac73b85434c36ccfb
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/my_exceptions.py
@@ -0,0 +1,35 @@
+from sys import version_info
+from warnings import warn
+from . import _deprecated_my_exceptions
+
+"""
+Exceptions
+"""
+# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
+# Copyright: 2010, Gael Varoquaux
+# License: BSD 3 clause
+
+_deprecated_names = [
+ name for name in dir(_deprecated_my_exceptions) if
+ not name.startswith("__")
+]
+
+
+if version_info[:2] >= (3, 7):
+ def __getattr__(name):
+ if not name.startswith("__") and name in _deprecated_names:
+ warn("{} is deprecated and will be removed from joblib "
+ "in 0.16".format(name), DeprecationWarning)
+ return getattr(_deprecated_my_exceptions, name)
+ raise AttributeError
+else:
+ for name in _deprecated_names:
+ globals()[name] = getattr(_deprecated_my_exceptions, name)
+
+
+class WorkerInterrupt(Exception):
+ """ An exception that is not KeyboardInterrupt to allow subprocesses
+ to be interrupted.
+ """
+
+ pass
diff --git a/runtime/Lib/site-packages/joblib/numpy_pickle.py b/runtime/Lib/site-packages/joblib/numpy_pickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa450fbbaae9ea9ce8226e0ed4c983df7227d7f7
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/numpy_pickle.py
@@ -0,0 +1,659 @@
+"""Utilities for fast persistence of big data, with optional compression."""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import pickle
+import os
+import warnings
+import io
+from pathlib import Path
+
+from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
+from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
+from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
+ BZ2CompressorWrapper, LZMACompressorWrapper,
+ XZCompressorWrapper, LZ4CompressorWrapper)
+from .numpy_pickle_utils import Unpickler, Pickler
+from .numpy_pickle_utils import _read_fileobject, _write_fileobject
+from .numpy_pickle_utils import _read_bytes, BUFFER_SIZE
+from .numpy_pickle_utils import _ensure_native_byte_order
+from .numpy_pickle_compat import load_compatibility
+from .numpy_pickle_compat import NDArrayWrapper
+# For compatibility with old versions of joblib, we need ZNDArrayWrapper
+# to be visible in the current namespace.
+# Explicitly skipping next line from flake8 as it triggers an F401 warning
+# which we don't care.
+from .numpy_pickle_compat import ZNDArrayWrapper # noqa
+from .backports import make_memmap
+
+# Register supported compressors
+register_compressor('zlib', ZlibCompressorWrapper())
+register_compressor('gzip', GzipCompressorWrapper())
+register_compressor('bz2', BZ2CompressorWrapper())
+register_compressor('lzma', LZMACompressorWrapper())
+register_compressor('xz', XZCompressorWrapper())
+register_compressor('lz4', LZ4CompressorWrapper())
+
+
+###############################################################################
+# Utility objects for persistence.
+
+# For convenience, 16 bytes are used to be sure to cover all the possible
+# dtypes' alignments. For reference, see:
+# https://numpy.org/devdocs/dev/alignment.html
+NUMPY_ARRAY_ALIGNMENT_BYTES = 16
+
+
+class NumpyArrayWrapper(object):
+ """An object to be persisted instead of numpy arrays.
+
+ This object is used to hack into the pickle machinery and read numpy
+ array data from our custom persistence format.
+ More precisely, this object is used for:
+ * carrying the information of the persisted array: subclass, shape, order,
+ dtype. Those ndarray metadata are used to correctly reconstruct the array
+ with low level numpy functions.
+ * determining if memmap is allowed on the array.
+ * reading the array bytes from a file.
+ * reading the array using memorymap from a file.
+ * writing the array bytes to a file.
+
+ Attributes
+ ----------
+ subclass: numpy.ndarray subclass
+ Determine the subclass of the wrapped array.
+ shape: numpy.ndarray shape
+ Determine the shape of the wrapped array.
+ order: {'C', 'F'}
+ Determine the order of wrapped array data. 'C' is for C order, 'F' is
+ for fortran order.
+ dtype: numpy.ndarray dtype
+ Determine the data type of the wrapped array.
+ allow_mmap: bool
+ Determine if memory mapping is allowed on the wrapped array.
+ Default: False.
+ """
+
+ def __init__(self, subclass, shape, order, dtype, allow_mmap=False,
+ numpy_array_alignment_bytes=NUMPY_ARRAY_ALIGNMENT_BYTES):
+ """Constructor. Store the useful information for later."""
+ self.subclass = subclass
+ self.shape = shape
+ self.order = order
+ self.dtype = dtype
+ self.allow_mmap = allow_mmap
+ # We make numpy_array_alignment_bytes an instance attribute to allow us
+ # to change our mind about the default alignment and still load the old
+ # pickles (with the previous alignment) correctly
+ self.numpy_array_alignment_bytes = numpy_array_alignment_bytes
+
+ def safe_get_numpy_array_alignment_bytes(self):
+ # NumpyArrayWrapper instances loaded from joblib <= 1.1 pickles don't
+ # have an numpy_array_alignment_bytes attribute
+ return getattr(self, 'numpy_array_alignment_bytes', None)
+
+ def write_array(self, array, pickler):
+ """Write array bytes to pickler file handle.
+
+ This function is an adaptation of the numpy write_array function
+ available in version 1.10.1 in numpy/lib/format.py.
+ """
+ # Set buffer size to 16 MiB to hide the Python loop overhead.
+ buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
+ if array.dtype.hasobject:
+ # We contain Python objects so we cannot write out the data
+ # directly. Instead, we will pickle it out with version 2 of the
+ # pickle protocol.
+ pickle.dump(array, pickler.file_handle, protocol=2)
+ else:
+ numpy_array_alignment_bytes = \
+ self.safe_get_numpy_array_alignment_bytes()
+ if numpy_array_alignment_bytes is not None:
+ current_pos = pickler.file_handle.tell()
+ pos_after_padding_byte = current_pos + 1
+ padding_length = numpy_array_alignment_bytes - (
+ pos_after_padding_byte % numpy_array_alignment_bytes)
+ # A single byte is written that contains the padding length in
+ # bytes
+ padding_length_byte = int.to_bytes(
+ padding_length, length=1, byteorder='little')
+ pickler.file_handle.write(padding_length_byte)
+
+ if padding_length != 0:
+ padding = b'\xff' * padding_length
+ pickler.file_handle.write(padding)
+
+ for chunk in pickler.np.nditer(array,
+ flags=['external_loop',
+ 'buffered',
+ 'zerosize_ok'],
+ buffersize=buffersize,
+ order=self.order):
+ pickler.file_handle.write(chunk.tobytes('C'))
+
+ def read_array(self, unpickler):
+ """Read array from unpickler file handle.
+
+ This function is an adaptation of the numpy read_array function
+ available in version 1.10.1 in numpy/lib/format.py.
+ """
+ if len(self.shape) == 0:
+ count = 1
+ else:
+ # joblib issue #859: we cast the elements of self.shape to int64 to
+ # prevent a potential overflow when computing their product.
+ shape_int64 = [unpickler.np.int64(x) for x in self.shape]
+ count = unpickler.np.multiply.reduce(shape_int64)
+ # Now read the actual data.
+ if self.dtype.hasobject:
+ # The array contained Python objects. We need to unpickle the data.
+ array = pickle.load(unpickler.file_handle)
+ else:
+ numpy_array_alignment_bytes = \
+ self.safe_get_numpy_array_alignment_bytes()
+ if numpy_array_alignment_bytes is not None:
+ padding_byte = unpickler.file_handle.read(1)
+ padding_length = int.from_bytes(
+ padding_byte, byteorder='little')
+ if padding_length != 0:
+ unpickler.file_handle.read(padding_length)
+
+ # This is not a real file. We have to read it the
+ # memory-intensive way.
+ # crc32 module fails on reads greater than 2 ** 32 bytes,
+ # breaking large reads from gzip streams. Chunk reads to
+ # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
+ # of the read. In non-chunked case count < max_read_count, so
+ # only one read is performed.
+ max_read_count = BUFFER_SIZE // min(BUFFER_SIZE,
+ self.dtype.itemsize)
+
+ array = unpickler.np.empty(count, dtype=self.dtype)
+ for i in range(0, count, max_read_count):
+ read_count = min(max_read_count, count - i)
+ read_size = int(read_count * self.dtype.itemsize)
+ data = _read_bytes(unpickler.file_handle,
+ read_size, "array data")
+ array[i:i + read_count] = \
+ unpickler.np.frombuffer(data, dtype=self.dtype,
+ count=read_count)
+ del data
+
+ if self.order == 'F':
+ array.shape = self.shape[::-1]
+ array = array.transpose()
+ else:
+ array.shape = self.shape
+
+ # Detect byte order mismatch and swap as needed.
+ return _ensure_native_byte_order(array)
+
+ def read_mmap(self, unpickler):
+ """Read an array using numpy memmap."""
+ current_pos = unpickler.file_handle.tell()
+ offset = current_pos
+ numpy_array_alignment_bytes = \
+ self.safe_get_numpy_array_alignment_bytes()
+
+ if numpy_array_alignment_bytes is not None:
+ padding_byte = unpickler.file_handle.read(1)
+ padding_length = int.from_bytes(padding_byte, byteorder='little')
+ # + 1 is for the padding byte
+ offset += padding_length + 1
+
+ if unpickler.mmap_mode == 'w+':
+ unpickler.mmap_mode = 'r+'
+
+ marray = make_memmap(unpickler.filename,
+ dtype=self.dtype,
+ shape=self.shape,
+ order=self.order,
+ mode=unpickler.mmap_mode,
+ offset=offset)
+ # update the offset so that it corresponds to the end of the read array
+ unpickler.file_handle.seek(offset + marray.nbytes)
+
+ if (numpy_array_alignment_bytes is None and
+ current_pos % NUMPY_ARRAY_ALIGNMENT_BYTES != 0):
+ message = (
+ f'The memmapped array {marray} loaded from the file '
+ f'{unpickler.file_handle.name} is not not bytes aligned. '
+ 'This may cause segmentation faults if this memmapped array '
+ 'is used in some libraries like BLAS or PyTorch. '
+ 'To get rid of this warning, regenerate your pickle file '
+ 'with joblib >= 1.2.0. '
+ 'See https://github.com/joblib/joblib/issues/563 '
+ 'for more details'
+ )
+ warnings.warn(message)
+
+ return marray
+
+ def read(self, unpickler):
+ """Read the array corresponding to this wrapper.
+
+ Use the unpickler to get all information to correctly read the array.
+
+ Parameters
+ ----------
+ unpickler: NumpyUnpickler
+
+ Returns
+ -------
+ array: numpy.ndarray
+
+ """
+ # When requested, only use memmap mode if allowed.
+ if unpickler.mmap_mode is not None and self.allow_mmap:
+ array = self.read_mmap(unpickler)
+ else:
+ array = self.read_array(unpickler)
+
+ # Manage array subclass case
+ if (hasattr(array, '__array_prepare__') and
+ self.subclass not in (unpickler.np.ndarray,
+ unpickler.np.memmap)):
+ # We need to reconstruct another subclass
+ new_array = unpickler.np.core.multiarray._reconstruct(
+ self.subclass, (0,), 'b')
+ return new_array.__array_prepare__(array)
+ else:
+ return array
+
+###############################################################################
+# Pickler classes
+
+
+class NumpyPickler(Pickler):
+ """A pickler to persist big data efficiently.
+
+ The main features of this object are:
+ * persistence of numpy arrays in a single file.
+ * optional compression with a special care on avoiding memory copies.
+
+ Attributes
+ ----------
+ fp: file
+ File object handle used for serializing the input object.
+ protocol: int, optional
+ Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL.
+ """
+
+ dispatch = Pickler.dispatch.copy()
+
+ def __init__(self, fp, protocol=None):
+ self.file_handle = fp
+ self.buffered = isinstance(self.file_handle, BinaryZlibFile)
+
+ # By default we want a pickle protocol that only changes with
+ # the major python version and not the minor one
+ if protocol is None:
+ protocol = pickle.DEFAULT_PROTOCOL
+
+ Pickler.__init__(self, self.file_handle, protocol=protocol)
+ # delayed import of numpy, to avoid tight coupling
+ try:
+ import numpy as np
+ except ImportError:
+ np = None
+ self.np = np
+
+ def _create_array_wrapper(self, array):
+ """Create and returns a numpy array wrapper from a numpy array."""
+ order = 'F' if (array.flags.f_contiguous and
+ not array.flags.c_contiguous) else 'C'
+ allow_mmap = not self.buffered and not array.dtype.hasobject
+
+ kwargs = {}
+ try:
+ self.file_handle.tell()
+ except io.UnsupportedOperation:
+ kwargs = {'numpy_array_alignment_bytes': None}
+
+ wrapper = NumpyArrayWrapper(type(array),
+ array.shape, order, array.dtype,
+ allow_mmap=allow_mmap,
+ **kwargs)
+
+ return wrapper
+
+ def save(self, obj):
+ """Subclass the Pickler `save` method.
+
+ This is a total abuse of the Pickler class in order to use the numpy
+ persistence function `save` instead of the default pickle
+ implementation. The numpy array is replaced by a custom wrapper in the
+ pickle persistence stack and the serialized array is written right
+ after in the file. Warning: the file produced does not follow the
+ pickle format. As such it can not be read with `pickle.load`.
+ """
+ if self.np is not None and type(obj) in (self.np.ndarray,
+ self.np.matrix,
+ self.np.memmap):
+ if type(obj) is self.np.memmap:
+ # Pickling doesn't work with memmapped arrays
+ obj = self.np.asanyarray(obj)
+
+ # The array wrapper is pickled instead of the real array.
+ wrapper = self._create_array_wrapper(obj)
+ Pickler.save(self, wrapper)
+
+ # A framer was introduced with pickle protocol 4 and we want to
+ # ensure the wrapper object is written before the numpy array
+ # buffer in the pickle file.
+ # See https://www.python.org/dev/peps/pep-3154/#framing to get
+ # more information on the framer behavior.
+ if self.proto >= 4:
+ self.framer.commit_frame(force=True)
+
+ # And then array bytes are written right after the wrapper.
+ wrapper.write_array(obj, self)
+ return
+
+ return Pickler.save(self, obj)
+
+
+class NumpyUnpickler(Unpickler):
+ """A subclass of the Unpickler to unpickle our numpy pickles.
+
+ Attributes
+ ----------
+ mmap_mode: str
+ The memorymap mode to use for reading numpy arrays.
+ file_handle: file_like
+ File object to unpickle from.
+ filename: str
+ Name of the file to unpickle from. It should correspond to file_handle.
+ This parameter is required when using mmap_mode.
+ np: module
+ Reference to numpy module if numpy is installed else None.
+
+ """
+
+ dispatch = Unpickler.dispatch.copy()
+
+ def __init__(self, filename, file_handle, mmap_mode=None):
+ # The next line is for backward compatibility with pickle generated
+ # with joblib versions less than 0.10.
+ self._dirname = os.path.dirname(filename)
+
+ self.mmap_mode = mmap_mode
+ self.file_handle = file_handle
+ # filename is required for numpy mmap mode.
+ self.filename = filename
+ self.compat_mode = False
+ Unpickler.__init__(self, self.file_handle)
+ try:
+ import numpy as np
+ except ImportError:
+ np = None
+ self.np = np
+
+ def load_build(self):
+ """Called to set the state of a newly created object.
+
+ We capture it to replace our place-holder objects, NDArrayWrapper or
+ NumpyArrayWrapper, by the array we are interested in. We
+ replace them directly in the stack of pickler.
+ NDArrayWrapper is used for backward compatibility with joblib <= 0.9.
+ """
+ Unpickler.load_build(self)
+
+ # For backward compatibility, we support NDArrayWrapper objects.
+ if isinstance(self.stack[-1], (NDArrayWrapper, NumpyArrayWrapper)):
+ if self.np is None:
+ raise ImportError("Trying to unpickle an ndarray, "
+ "but numpy didn't import correctly")
+ array_wrapper = self.stack.pop()
+ # If any NDArrayWrapper is found, we switch to compatibility mode,
+ # this will be used to raise a DeprecationWarning to the user at
+ # the end of the unpickling.
+ if isinstance(array_wrapper, NDArrayWrapper):
+ self.compat_mode = True
+ self.stack.append(array_wrapper.read(self))
+
+ # Be careful to register our new method.
+ dispatch[pickle.BUILD[0]] = load_build
+
+
+###############################################################################
+# Utility functions
+
+def dump(value, filename, compress=0, protocol=None, cache_size=None):
+ """Persist an arbitrary Python object into one file.
+
+ Read more in the :ref:`User Guide `.
+
+ Parameters
+ -----------
+ value: any Python object
+ The object to store to disk.
+ filename: str, pathlib.Path, or file object.
+ The file object or path of the file in which it is to be stored.
+ The compression method corresponding to one of the supported filename
+ extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used
+ automatically.
+ compress: int from 0 to 9 or bool or 2-tuple, optional
+ Optional compression level for the data. 0 or False is no compression.
+ Higher value means more compression, but also slower read and
+ write times. Using a value of 3 is often a good compromise.
+ See the notes for more details.
+ If compress is True, the compression level used is 3.
+ If compress is a 2-tuple, the first element must correspond to a string
+ between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma'
+ 'xz'), the second element must be an integer from 0 to 9, corresponding
+ to the compression level.
+ protocol: int, optional
+ Pickle protocol, see pickle.dump documentation for more details.
+ cache_size: positive int, optional
+ This option is deprecated in 0.10 and has no effect.
+
+ Returns
+ -------
+ filenames: list of strings
+ The list of file names in which the data is stored. If
+ compress is false, each array is stored in a different file.
+
+ See Also
+ --------
+ joblib.load : corresponding loader
+
+ Notes
+ -----
+ Memmapping on load cannot be used for compressed files. Thus
+ using compression can significantly slow down loading. In
+ addition, compressed files take extra extra memory during
+ dump and load.
+
+ """
+
+ if Path is not None and isinstance(filename, Path):
+ filename = str(filename)
+
+ is_filename = isinstance(filename, str)
+ is_fileobj = hasattr(filename, "write")
+
+ compress_method = 'zlib' # zlib is the default compression method.
+ if compress is True:
+ # By default, if compress is enabled, we want the default compress
+ # level of the compressor.
+ compress_level = None
+ elif isinstance(compress, tuple):
+ # a 2-tuple was set in compress
+ if len(compress) != 2:
+ raise ValueError(
+ 'Compress argument tuple should contain exactly 2 elements: '
+ '(compress method, compress level), you passed {}'
+ .format(compress))
+ compress_method, compress_level = compress
+ elif isinstance(compress, str):
+ compress_method = compress
+ compress_level = None # Use default compress level
+ compress = (compress_method, compress_level)
+ else:
+ compress_level = compress
+
+ if compress_method == 'lz4' and lz4 is None:
+ raise ValueError(LZ4_NOT_INSTALLED_ERROR)
+
+ if (compress_level is not None and
+ compress_level is not False and
+ compress_level not in range(10)):
+ # Raising an error if a non valid compress level is given.
+ raise ValueError(
+ 'Non valid compress level given: "{}". Possible values are '
+ '{}.'.format(compress_level, list(range(10))))
+
+ if compress_method not in _COMPRESSORS:
+ # Raising an error if an unsupported compression method is given.
+ raise ValueError(
+ 'Non valid compression method given: "{}". Possible values are '
+ '{}.'.format(compress_method, _COMPRESSORS))
+
+ if not is_filename and not is_fileobj:
+ # People keep inverting arguments, and the resulting error is
+ # incomprehensible
+ raise ValueError(
+ 'Second argument should be a filename or a file-like object, '
+ '%s (type %s) was given.'
+ % (filename, type(filename))
+ )
+
+ if is_filename and not isinstance(compress, tuple):
+ # In case no explicit compression was requested using both compression
+ # method and level in a tuple and the filename has an explicit
+ # extension, we select the corresponding compressor.
+
+ # unset the variable to be sure no compression level is set afterwards.
+ compress_method = None
+ for name, compressor in _COMPRESSORS.items():
+ if filename.endswith(compressor.extension):
+ compress_method = name
+
+ if compress_method in _COMPRESSORS and compress_level == 0:
+ # we choose the default compress_level in case it was not given
+ # as an argument (using compress).
+ compress_level = None
+
+ if cache_size is not None:
+ # Cache size is deprecated starting from version 0.10
+ warnings.warn("Please do not set 'cache_size' in joblib.dump, "
+ "this parameter has no effect and will be removed. "
+ "You used 'cache_size={}'".format(cache_size),
+ DeprecationWarning, stacklevel=2)
+
+ if compress_level != 0:
+ with _write_fileobject(filename, compress=(compress_method,
+ compress_level)) as f:
+ NumpyPickler(f, protocol=protocol).dump(value)
+ elif is_filename:
+ with open(filename, 'wb') as f:
+ NumpyPickler(f, protocol=protocol).dump(value)
+ else:
+ NumpyPickler(filename, protocol=protocol).dump(value)
+
+ # If the target container is a file object, nothing is returned.
+ if is_fileobj:
+ return
+
+ # For compatibility, the list of created filenames (e.g with one element
+ # after 0.10.0) is returned by default.
+ return [filename]
+
+
+def _unpickle(fobj, filename="", mmap_mode=None):
+ """Internal unpickling function."""
+ # We are careful to open the file handle early and keep it open to
+ # avoid race-conditions on renames.
+ # That said, if data is stored in companion files, which can be
+ # the case with the old persistence format, moving the directory
+ # will create a race when joblib tries to access the companion
+ # files.
+ unpickler = NumpyUnpickler(filename, fobj, mmap_mode=mmap_mode)
+ obj = None
+ try:
+ obj = unpickler.load()
+ if unpickler.compat_mode:
+ warnings.warn("The file '%s' has been generated with a "
+ "joblib version less than 0.10. "
+ "Please regenerate this pickle file."
+ % filename,
+ DeprecationWarning, stacklevel=3)
+ except UnicodeDecodeError as exc:
+ # More user-friendly error message
+ new_exc = ValueError(
+ 'You may be trying to read with '
+ 'python 3 a joblib pickle generated with python 2. '
+ 'This feature is not supported by joblib.')
+ new_exc.__cause__ = exc
+ raise new_exc
+ return obj
+
+
+def load_temporary_memmap(filename, mmap_mode, unlink_on_gc_collect):
+ from ._memmapping_reducer import JOBLIB_MMAPS, add_maybe_unlink_finalizer
+ obj = load(filename, mmap_mode)
+ JOBLIB_MMAPS.add(obj.filename)
+ if unlink_on_gc_collect:
+ add_maybe_unlink_finalizer(obj)
+ return obj
+
+
+def load(filename, mmap_mode=None):
+ """Reconstruct a Python object from a file persisted with joblib.dump.
+
+ Read more in the :ref:`User Guide `.
+
+ WARNING: joblib.load relies on the pickle module and can therefore
+ execute arbitrary Python code. It should therefore never be used
+ to load files from untrusted sources.
+
+ Parameters
+ -----------
+ filename: str, pathlib.Path, or file object.
+ The file object or path of the file from which to load the object
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
+ If not None, the arrays are memory-mapped from the disk. This
+ mode has no effect for compressed files. Note that in this
+ case the reconstructed object might no longer match exactly
+ the originally pickled object.
+
+ Returns
+ -------
+ result: any Python object
+ The object stored in the file.
+
+ See Also
+ --------
+ joblib.dump : function to save an object
+
+ Notes
+ -----
+
+ This function can load numpy array files saved separately during the
+ dump. If the mmap_mode argument is given, it is passed to np.load and
+ arrays are loaded as memmaps. As a consequence, the reconstructed
+ object might not match the original pickled object. Note that if the
+ file was saved with compression, the arrays cannot be memmapped.
+ """
+ if Path is not None and isinstance(filename, Path):
+ filename = str(filename)
+
+ if hasattr(filename, "read"):
+ fobj = filename
+ filename = getattr(fobj, 'name', '')
+ with _read_fileobject(fobj, filename, mmap_mode) as fobj:
+ obj = _unpickle(fobj)
+ else:
+ with open(filename, 'rb') as f:
+ with _read_fileobject(f, filename, mmap_mode) as fobj:
+ if isinstance(fobj, str):
+ # if the returned file object is a string, this means we
+ # try to load a pickle file generated with an version of
+ # Joblib so we load it with joblib compatibility function.
+ return load_compatibility(fobj)
+
+ obj = _unpickle(fobj, filename, mmap_mode)
+ return obj
diff --git a/runtime/Lib/site-packages/joblib/numpy_pickle_compat.py b/runtime/Lib/site-packages/joblib/numpy_pickle_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..5316c0225b73ca8cd6cc86d9a31d9c4edddba59b
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/numpy_pickle_compat.py
@@ -0,0 +1,243 @@
+"""Numpy pickle compatibility functions."""
+
+import pickle
+import os
+import zlib
+import inspect
+
+from io import BytesIO
+
+from .numpy_pickle_utils import _ZFILE_PREFIX
+from .numpy_pickle_utils import Unpickler
+from .numpy_pickle_utils import _ensure_native_byte_order
+
+def hex_str(an_int):
+ """Convert an int to an hexadecimal string."""
+ return '{:#x}'.format(an_int)
+
+
+def asbytes(s):
+ if isinstance(s, bytes):
+ return s
+ return s.encode('latin1')
+
+
+_MAX_LEN = len(hex_str(2 ** 64))
+_CHUNK_SIZE = 64 * 1024
+
+
+def read_zfile(file_handle):
+ """Read the z-file and return the content as a string.
+
+ Z-files are raw data compressed with zlib used internally by joblib
+ for persistence. Backward compatibility is not guaranteed. Do not
+ use for external purposes.
+ """
+ file_handle.seek(0)
+ header_length = len(_ZFILE_PREFIX) + _MAX_LEN
+ length = file_handle.read(header_length)
+ length = length[len(_ZFILE_PREFIX):]
+ length = int(length, 16)
+
+ # With python2 and joblib version <= 0.8.4 compressed pickle header is one
+ # character wider so we need to ignore an additional space if present.
+ # Note: the first byte of the zlib data is guaranteed not to be a
+ # space according to
+ # https://tools.ietf.org/html/rfc6713#section-2.1
+ next_byte = file_handle.read(1)
+ if next_byte != b' ':
+ # The zlib compressed data has started and we need to go back
+ # one byte
+ file_handle.seek(header_length)
+
+ # We use the known length of the data to tell Zlib the size of the
+ # buffer to allocate.
+ data = zlib.decompress(file_handle.read(), 15, length)
+ assert len(data) == length, (
+ "Incorrect data length while decompressing %s."
+ "The file could be corrupted." % file_handle)
+ return data
+
+
+def write_zfile(file_handle, data, compress=1):
+ """Write the data in the given file as a Z-file.
+
+ Z-files are raw data compressed with zlib used internally by joblib
+ for persistence. Backward compatibility is not guaranteed. Do not
+ use for external purposes.
+ """
+ file_handle.write(_ZFILE_PREFIX)
+ length = hex_str(len(data))
+ # Store the length of the data
+ file_handle.write(asbytes(length.ljust(_MAX_LEN)))
+ file_handle.write(zlib.compress(asbytes(data), compress))
+
+###############################################################################
+# Utility objects for persistence.
+
+
+class NDArrayWrapper(object):
+ """An object to be persisted instead of numpy arrays.
+
+ The only thing this object does, is to carry the filename in which
+ the array has been persisted, and the array subclass.
+ """
+
+ def __init__(self, filename, subclass, allow_mmap=True):
+ """Constructor. Store the useful information for later."""
+ self.filename = filename
+ self.subclass = subclass
+ self.allow_mmap = allow_mmap
+
+ def read(self, unpickler):
+ """Reconstruct the array."""
+ filename = os.path.join(unpickler._dirname, self.filename)
+ # Load the array from the disk
+ # use getattr instead of self.allow_mmap to ensure backward compat
+ # with NDArrayWrapper instances pickled with joblib < 0.9.0
+ allow_mmap = getattr(self, 'allow_mmap', True)
+ kwargs = {}
+ if allow_mmap:
+ kwargs['mmap_mode'] = unpickler.mmap_mode
+ if "allow_pickle" in inspect.signature(unpickler.np.load).parameters:
+ # Required in numpy 1.16.3 and later to aknowledge the security
+ # risk.
+ kwargs["allow_pickle"] = True
+ array = unpickler.np.load(filename, **kwargs)
+
+ # Detect byte order mismatch and swap as needed.
+ array = _ensure_native_byte_order(array)
+
+ # Reconstruct subclasses. This does not work with old
+ # versions of numpy
+ if (hasattr(array, '__array_prepare__') and
+ self.subclass not in (unpickler.np.ndarray,
+ unpickler.np.memmap)):
+ # We need to reconstruct another subclass
+ new_array = unpickler.np.core.multiarray._reconstruct(
+ self.subclass, (0,), 'b')
+ return new_array.__array_prepare__(array)
+ else:
+ return array
+
+
+class ZNDArrayWrapper(NDArrayWrapper):
+ """An object to be persisted instead of numpy arrays.
+
+ This object store the Zfile filename in which
+ the data array has been persisted, and the meta information to
+ retrieve it.
+ The reason that we store the raw buffer data of the array and
+ the meta information, rather than array representation routine
+ (tobytes) is that it enables us to use completely the strided
+ model to avoid memory copies (a and a.T store as fast). In
+ addition saving the heavy information separately can avoid
+ creating large temporary buffers when unpickling data with
+ large arrays.
+ """
+
+ def __init__(self, filename, init_args, state):
+ """Constructor. Store the useful information for later."""
+ self.filename = filename
+ self.state = state
+ self.init_args = init_args
+
+ def read(self, unpickler):
+ """Reconstruct the array from the meta-information and the z-file."""
+ # Here we a simply reproducing the unpickling mechanism for numpy
+ # arrays
+ filename = os.path.join(unpickler._dirname, self.filename)
+ array = unpickler.np.core.multiarray._reconstruct(*self.init_args)
+ with open(filename, 'rb') as f:
+ data = read_zfile(f)
+ state = self.state + (data,)
+ array.__setstate__(state)
+ return array
+
+
+class ZipNumpyUnpickler(Unpickler):
+ """A subclass of the Unpickler to unpickle our numpy pickles."""
+
+ dispatch = Unpickler.dispatch.copy()
+
+ def __init__(self, filename, file_handle, mmap_mode=None):
+ """Constructor."""
+ self._filename = os.path.basename(filename)
+ self._dirname = os.path.dirname(filename)
+ self.mmap_mode = mmap_mode
+ self.file_handle = self._open_pickle(file_handle)
+ Unpickler.__init__(self, self.file_handle)
+ try:
+ import numpy as np
+ except ImportError:
+ np = None
+ self.np = np
+
+ def _open_pickle(self, file_handle):
+ return BytesIO(read_zfile(file_handle))
+
+ def load_build(self):
+ """Set the state of a newly created object.
+
+ We capture it to replace our place-holder objects,
+ NDArrayWrapper, by the array we are interested in. We
+ replace them directly in the stack of pickler.
+ """
+ Unpickler.load_build(self)
+ if isinstance(self.stack[-1], NDArrayWrapper):
+ if self.np is None:
+ raise ImportError("Trying to unpickle an ndarray, "
+ "but numpy didn't import correctly")
+ nd_array_wrapper = self.stack.pop()
+ array = nd_array_wrapper.read(self)
+ self.stack.append(array)
+
+ dispatch[pickle.BUILD[0]] = load_build
+
+
+def load_compatibility(filename):
+ """Reconstruct a Python object from a file persisted with joblib.dump.
+
+ This function ensures the compatibility with joblib old persistence format
+ (<= 0.9.3).
+
+ Parameters
+ -----------
+ filename: string
+ The name of the file from which to load the object
+
+ Returns
+ -------
+ result: any Python object
+ The object stored in the file.
+
+ See Also
+ --------
+ joblib.dump : function to save an object
+
+ Notes
+ -----
+
+ This function can load numpy array files saved separately during the
+ dump.
+ """
+ with open(filename, 'rb') as file_handle:
+ # We are careful to open the file handle early and keep it open to
+ # avoid race-conditions on renames. That said, if data is stored in
+ # companion files, moving the directory will create a race when
+ # joblib tries to access the companion files.
+ unpickler = ZipNumpyUnpickler(filename, file_handle=file_handle)
+ try:
+ obj = unpickler.load()
+ except UnicodeDecodeError as exc:
+ # More user-friendly error message
+ new_exc = ValueError(
+ 'You may be trying to read with '
+ 'python 3 a joblib pickle generated with python 2. '
+ 'This feature is not supported by joblib.')
+ new_exc.__cause__ = exc
+ raise new_exc
+ finally:
+ if hasattr(unpickler, 'file_handle'):
+ unpickler.file_handle.close()
+ return obj
diff --git a/runtime/Lib/site-packages/joblib/numpy_pickle_utils.py b/runtime/Lib/site-packages/joblib/numpy_pickle_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..71f2c7c59d226a71ec9e78c12c912c7a0433842e
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/numpy_pickle_utils.py
@@ -0,0 +1,253 @@
+"""Utilities for fast persistence of big data, with optional compression."""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import pickle
+import io
+import sys
+import warnings
+import contextlib
+
+from .compressor import _ZFILE_PREFIX
+from .compressor import _COMPRESSORS
+
+try:
+ import numpy as np
+except ImportError:
+ np = None
+
+Unpickler = pickle._Unpickler
+Pickler = pickle._Pickler
+xrange = range
+
+
+try:
+ # The python standard library can be built without bz2 so we make bz2
+ # usage optional.
+ # see https://github.com/scikit-learn/scikit-learn/issues/7526 for more
+ # details.
+ import bz2
+except ImportError:
+ bz2 = None
+
+# Buffer size used in io.BufferedReader and io.BufferedWriter
+_IO_BUFFER_SIZE = 1024 ** 2
+
+
+def _is_raw_file(fileobj):
+ """Check if fileobj is a raw file object, e.g created with open."""
+ fileobj = getattr(fileobj, 'raw', fileobj)
+ return isinstance(fileobj, io.FileIO)
+
+
+def _get_prefixes_max_len():
+ # Compute the max prefix len of registered compressors.
+ prefixes = [len(compressor.prefix) for compressor in _COMPRESSORS.values()]
+ prefixes += [len(_ZFILE_PREFIX)]
+ return max(prefixes)
+
+
+def _is_numpy_array_byte_order_mismatch(array):
+ """Check if numpy array is having byte order mismatch"""
+ return ((sys.byteorder == 'big' and
+ (array.dtype.byteorder == '<' or
+ (array.dtype.byteorder == '|' and array.dtype.fields and
+ all(e[0].byteorder == '<'
+ for e in array.dtype.fields.values())))) or
+ (sys.byteorder == 'little' and
+ (array.dtype.byteorder == '>' or
+ (array.dtype.byteorder == '|' and array.dtype.fields and
+ all(e[0].byteorder == '>'
+ for e in array.dtype.fields.values())))))
+
+
+def _ensure_native_byte_order(array):
+ """Use the byte order of the host while preserving values
+
+ Does nothing if array already uses the system byte order.
+ """
+ if _is_numpy_array_byte_order_mismatch(array):
+ array = array.byteswap().newbyteorder('=')
+ return array
+
+
+###############################################################################
+# Cache file utilities
+def _detect_compressor(fileobj):
+ """Return the compressor matching fileobj.
+
+ Parameters
+ ----------
+ fileobj: file object
+
+ Returns
+ -------
+ str in {'zlib', 'gzip', 'bz2', 'lzma', 'xz', 'compat', 'not-compressed'}
+ """
+ # Read the magic number in the first bytes of the file.
+ max_prefix_len = _get_prefixes_max_len()
+ if hasattr(fileobj, 'peek'):
+ # Peek allows to read those bytes without moving the cursor in the
+ # file whic.
+ first_bytes = fileobj.peek(max_prefix_len)
+ else:
+ # Fallback to seek if the fileobject is not peekable.
+ first_bytes = fileobj.read(max_prefix_len)
+ fileobj.seek(0)
+
+ if first_bytes.startswith(_ZFILE_PREFIX):
+ return "compat"
+ else:
+ for name, compressor in _COMPRESSORS.items():
+ if first_bytes.startswith(compressor.prefix):
+ return name
+
+ return "not-compressed"
+
+
+def _buffered_read_file(fobj):
+ """Return a buffered version of a read file object."""
+ return io.BufferedReader(fobj, buffer_size=_IO_BUFFER_SIZE)
+
+
+def _buffered_write_file(fobj):
+ """Return a buffered version of a write file object."""
+ return io.BufferedWriter(fobj, buffer_size=_IO_BUFFER_SIZE)
+
+
+@contextlib.contextmanager
+def _read_fileobject(fileobj, filename, mmap_mode=None):
+ """Utility function opening the right fileobject from a filename.
+
+ The magic number is used to choose between the type of file object to open:
+ * regular file object (default)
+ * zlib file object
+ * gzip file object
+ * bz2 file object
+ * lzma file object (for xz and lzma compressor)
+
+ Parameters
+ ----------
+ fileobj: file object
+ compressor: str in {'zlib', 'gzip', 'bz2', 'lzma', 'xz', 'compat',
+ 'not-compressed'}
+ filename: str
+ filename path corresponding to the fileobj parameter.
+ mmap_mode: str
+ memory map mode that should be used to open the pickle file. This
+ parameter is useful to verify that the user is not trying to one with
+ compression. Default: None.
+
+ Returns
+ -------
+ a file like object
+
+ """
+ # Detect if the fileobj contains compressed data.
+ compressor = _detect_compressor(fileobj)
+
+ if compressor == 'compat':
+ # Compatibility with old pickle mode: simply return the input
+ # filename "as-is" and let the compatibility function be called by the
+ # caller.
+ warnings.warn("The file '%s' has been generated with a joblib "
+ "version less than 0.10. "
+ "Please regenerate this pickle file." % filename,
+ DeprecationWarning, stacklevel=2)
+ yield filename
+ else:
+ if compressor in _COMPRESSORS:
+ # based on the compressor detected in the file, we open the
+ # correct decompressor file object, wrapped in a buffer.
+ compressor_wrapper = _COMPRESSORS[compressor]
+ inst = compressor_wrapper.decompressor_file(fileobj)
+ fileobj = _buffered_read_file(inst)
+
+ # Checking if incompatible load parameters with the type of file:
+ # mmap_mode cannot be used with compressed file or in memory buffers
+ # such as io.BytesIO.
+ if mmap_mode is not None:
+ if isinstance(fileobj, io.BytesIO):
+ warnings.warn('In memory persistence is not compatible with '
+ 'mmap_mode "%(mmap_mode)s" flag passed. '
+ 'mmap_mode option will be ignored.'
+ % locals(), stacklevel=2)
+ elif compressor != 'not-compressed':
+ warnings.warn('mmap_mode "%(mmap_mode)s" is not compatible '
+ 'with compressed file %(filename)s. '
+ '"%(mmap_mode)s" flag will be ignored.'
+ % locals(), stacklevel=2)
+ elif not _is_raw_file(fileobj):
+ warnings.warn('"%(fileobj)r" is not a raw file, mmap_mode '
+ '"%(mmap_mode)s" flag will be ignored.'
+ % locals(), stacklevel=2)
+
+ yield fileobj
+
+
+def _write_fileobject(filename, compress=("zlib", 3)):
+ """Return the right compressor file object in write mode."""
+ compressmethod = compress[0]
+ compresslevel = compress[1]
+
+ if compressmethod in _COMPRESSORS.keys():
+ file_instance = _COMPRESSORS[compressmethod].compressor_file(
+ filename, compresslevel=compresslevel)
+ return _buffered_write_file(file_instance)
+ else:
+ file_instance = _COMPRESSORS['zlib'].compressor_file(
+ filename, compresslevel=compresslevel)
+ return _buffered_write_file(file_instance)
+
+
+# Utility functions/variables from numpy required for writing arrays.
+# We need at least the functions introduced in version 1.9 of numpy. Here,
+# we use the ones from numpy 1.10.2.
+BUFFER_SIZE = 2 ** 18 # size of buffer for reading npz files in bytes
+
+
+def _read_bytes(fp, size, error_template="ran out of data"):
+ """Read from file-like object until size bytes are read.
+
+ TODO python2_drop: is it still needed? The docstring mentions python 2.6
+ and it looks like this can be at least simplified ...
+
+ Raises ValueError if not EOF is encountered before size bytes are read.
+ Non-blocking objects only supported if they derive from io objects.
+
+ Required as e.g. ZipExtFile in python 2.6 can return less data than
+ requested.
+
+ This function was taken from numpy/lib/format.py in version 1.10.2.
+
+ Parameters
+ ----------
+ fp: file-like object
+ size: int
+ error_template: str
+
+ Returns
+ -------
+ a bytes object
+ The data read in bytes.
+
+ """
+ data = bytes()
+ while True:
+ # io files (default in python3) return None or raise on
+ # would-block, python2 file will truncate, probably nothing can be
+ # done about that. note that regular files can't be non-blocking
+ try:
+ r = fp.read(size - len(data))
+ data += r
+ if len(r) == 0 or len(data) == size:
+ break
+ except io.BlockingIOError:
+ pass
+ if len(data) != size:
+ msg = "EOF: reading %s, expected %d bytes got %d"
+ raise ValueError(msg % (error_template, size, len(data)))
+ else:
+ return data
diff --git a/runtime/Lib/site-packages/joblib/parallel.py b/runtime/Lib/site-packages/joblib/parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e7b1b19a026c4f9c339138a19dd632a758be4e3
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/parallel.py
@@ -0,0 +1,1116 @@
+"""
+Helpers for embarrassingly parallel code.
+"""
+# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
+# Copyright: 2010, Gael Varoquaux
+# License: BSD 3 clause
+
+from __future__ import division
+
+import os
+import sys
+from math import sqrt
+import functools
+import time
+import threading
+import itertools
+from uuid import uuid4
+from numbers import Integral
+import warnings
+import queue
+
+from ._multiprocessing_helpers import mp
+
+from .logger import Logger, short_format_time
+from .disk import memstr_to_bytes
+from ._parallel_backends import (FallbackToBackend, MultiprocessingBackend,
+ ThreadingBackend, SequentialBackend,
+ LokyBackend)
+from .externals.cloudpickle import dumps, loads
+from ._utils import eval_expr
+
+# Make sure that those two classes are part of the public joblib.parallel API
+# so that 3rd party backend implementers can import them from here.
+from ._parallel_backends import AutoBatchingMixin # noqa
+from ._parallel_backends import ParallelBackendBase # noqa
+
+
+BACKENDS = {
+ 'threading': ThreadingBackend,
+ 'sequential': SequentialBackend,
+}
+# name of the backend used by default by Parallel outside of any context
+# managed by ``parallel_backend``.
+
+# threading is the only backend that is always everywhere
+DEFAULT_BACKEND = 'threading'
+
+DEFAULT_N_JOBS = 1
+
+MAYBE_AVAILABLE_BACKENDS = {'multiprocessing', 'loky'}
+
+# if multiprocessing is available, so is loky, we set it as the default
+# backend
+if mp is not None:
+ BACKENDS['multiprocessing'] = MultiprocessingBackend
+ from .externals import loky
+ BACKENDS['loky'] = LokyBackend
+ DEFAULT_BACKEND = 'loky'
+
+
+DEFAULT_THREAD_BACKEND = 'threading'
+
+# Thread local value that can be overridden by the ``parallel_backend`` context
+# manager
+_backend = threading.local()
+
+VALID_BACKEND_HINTS = ('processes', 'threads', None)
+VALID_BACKEND_CONSTRAINTS = ('sharedmem', None)
+
+
+def _register_dask():
+ """ Register Dask Backend if called with parallel_backend("dask") """
+ try:
+ from ._dask import DaskDistributedBackend
+ register_parallel_backend('dask', DaskDistributedBackend)
+ except ImportError as e:
+ msg = ("To use the dask.distributed backend you must install both "
+ "the `dask` and distributed modules.\n\n"
+ "See https://dask.pydata.org/en/latest/install.html for more "
+ "information.")
+ raise ImportError(msg) from e
+
+
+EXTERNAL_BACKENDS = {
+ 'dask': _register_dask,
+}
+
+
+def get_active_backend(prefer=None, require=None, verbose=0):
+ """Return the active default backend"""
+ if prefer not in VALID_BACKEND_HINTS:
+ raise ValueError("prefer=%r is not a valid backend hint, "
+ "expected one of %r" % (prefer, VALID_BACKEND_HINTS))
+ if require not in VALID_BACKEND_CONSTRAINTS:
+ raise ValueError("require=%r is not a valid backend constraint, "
+ "expected one of %r"
+ % (require, VALID_BACKEND_CONSTRAINTS))
+
+ if prefer == 'processes' and require == 'sharedmem':
+ raise ValueError("prefer == 'processes' and require == 'sharedmem'"
+ " are inconsistent settings")
+ backend_and_jobs = getattr(_backend, 'backend_and_jobs', None)
+ if backend_and_jobs is not None:
+ # Try to use the backend set by the user with the context manager.
+ backend, n_jobs = backend_and_jobs
+ nesting_level = backend.nesting_level
+ supports_sharedmem = getattr(backend, 'supports_sharedmem', False)
+ if require == 'sharedmem' and not supports_sharedmem:
+ # This backend does not match the shared memory constraint:
+ # fallback to the default thead-based backend.
+ sharedmem_backend = BACKENDS[DEFAULT_THREAD_BACKEND](
+ nesting_level=nesting_level)
+ if verbose >= 10:
+ print("Using %s as joblib.Parallel backend instead of %s "
+ "as the latter does not provide shared memory semantics."
+ % (sharedmem_backend.__class__.__name__,
+ backend.__class__.__name__))
+ return sharedmem_backend, DEFAULT_N_JOBS
+ else:
+ return backend_and_jobs
+
+ # We are outside of the scope of any parallel_backend context manager,
+ # create the default backend instance now.
+ backend = BACKENDS[DEFAULT_BACKEND](nesting_level=0)
+ supports_sharedmem = getattr(backend, 'supports_sharedmem', False)
+ uses_threads = getattr(backend, 'uses_threads', False)
+ if ((require == 'sharedmem' and not supports_sharedmem) or
+ (prefer == 'threads' and not uses_threads)):
+ # Make sure the selected default backend match the soft hints and
+ # hard constraints:
+ backend = BACKENDS[DEFAULT_THREAD_BACKEND](nesting_level=0)
+ return backend, DEFAULT_N_JOBS
+
+
+class parallel_backend(object):
+ """Change the default backend used by Parallel inside a with block.
+
+ If ``backend`` is a string it must match a previously registered
+ implementation using the :func:`~register_parallel_backend` function.
+
+ By default the following backends are available:
+
+ - 'loky': single-host, process-based parallelism (used by default),
+ - 'threading': single-host, thread-based parallelism,
+ - 'multiprocessing': legacy single-host, process-based parallelism.
+
+ 'loky' is recommended to run functions that manipulate Python objects.
+ 'threading' is a low-overhead alternative that is most efficient for
+ functions that release the Global Interpreter Lock: e.g. I/O-bound code or
+ CPU-bound code in a few calls to native code that explicitly releases the
+ GIL. Note that on some rare systems (such as pyiodine),
+ multiprocessing and loky may not be available, in which case joblib
+ defaults to threading.
+
+ In addition, if the `dask` and `distributed` Python packages are installed,
+ it is possible to use the 'dask' backend for better scheduling of nested
+ parallel calls without over-subscription and potentially distribute
+ parallel calls over a networked cluster of several hosts.
+
+ It is also possible to use the distributed 'ray' backend for distributing
+ the workload to a cluster of nodes. To use the 'ray' joblib backend add
+ the following lines::
+
+ >>> from ray.util.joblib import register_ray # doctest: +SKIP
+ >>> register_ray() # doctest: +SKIP
+ >>> with parallel_backend("ray"): # doctest: +SKIP
+ ... print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
+ [-1, -2, -3, -4, -5]
+
+ Alternatively the backend can be passed directly as an instance.
+
+ By default all available workers will be used (``n_jobs=-1``) unless the
+ caller passes an explicit value for the ``n_jobs`` parameter.
+
+ This is an alternative to passing a ``backend='backend_name'`` argument to
+ the :class:`~Parallel` class constructor. It is particularly useful when
+ calling into library code that uses joblib internally but does not expose
+ the backend argument in its own API.
+
+ >>> from operator import neg
+ >>> with parallel_backend('threading'):
+ ... print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
+ ...
+ [-1, -2, -3, -4, -5]
+
+ Warning: this function is experimental and subject to change in a future
+ version of joblib.
+
+ Joblib also tries to limit the oversubscription by limiting the number of
+ threads usable in some third-party library threadpools like OpenBLAS, MKL
+ or OpenMP. The default limit in each worker is set to
+ ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be
+ overwritten with the ``inner_max_num_threads`` argument which will be used
+ to set this limit in the child processes.
+
+ .. versionadded:: 0.10
+
+ """
+ def __init__(self, backend, n_jobs=-1, inner_max_num_threads=None,
+ **backend_params):
+ if isinstance(backend, str):
+ if backend not in BACKENDS:
+ if backend in EXTERNAL_BACKENDS:
+ register = EXTERNAL_BACKENDS[backend]
+ register()
+ elif backend in MAYBE_AVAILABLE_BACKENDS:
+ warnings.warn(
+ f"joblib backend '{backend}' is not available on "
+ f"your system, falling back to {DEFAULT_BACKEND}.",
+ UserWarning,
+ stacklevel=2)
+ BACKENDS[backend] = BACKENDS[DEFAULT_BACKEND]
+ else:
+ raise ValueError("Invalid backend: %s, expected one of %r"
+ % (backend, sorted(BACKENDS.keys())))
+
+ backend = BACKENDS[backend](**backend_params)
+
+ if inner_max_num_threads is not None:
+ msg = ("{} does not accept setting the inner_max_num_threads "
+ "argument.".format(backend.__class__.__name__))
+ assert backend.supports_inner_max_num_threads, msg
+ backend.inner_max_num_threads = inner_max_num_threads
+
+ # If the nesting_level of the backend is not set previously, use the
+ # nesting level from the previous active_backend to set it
+ current_backend_and_jobs = getattr(_backend, 'backend_and_jobs', None)
+ if backend.nesting_level is None:
+ if current_backend_and_jobs is None:
+ nesting_level = 0
+ else:
+ nesting_level = current_backend_and_jobs[0].nesting_level
+
+ backend.nesting_level = nesting_level
+
+ # Save the backends info and set the active backend
+ self.old_backend_and_jobs = current_backend_and_jobs
+ self.new_backend_and_jobs = (backend, n_jobs)
+
+ _backend.backend_and_jobs = (backend, n_jobs)
+
+ def __enter__(self):
+ return self.new_backend_and_jobs
+
+ def __exit__(self, type, value, traceback):
+ self.unregister()
+
+ def unregister(self):
+ if self.old_backend_and_jobs is None:
+ if getattr(_backend, 'backend_and_jobs', None) is not None:
+ del _backend.backend_and_jobs
+ else:
+ _backend.backend_and_jobs = self.old_backend_and_jobs
+
+
+# Under Linux or OS X the default start method of multiprocessing
+# can cause third party libraries to crash. Under Python 3.4+ it is possible
+# to set an environment variable to switch the default start method from
+# 'fork' to 'forkserver' or 'spawn' to avoid this issue albeit at the cost
+# of causing semantic changes and some additional pool instantiation overhead.
+DEFAULT_MP_CONTEXT = None
+if hasattr(mp, 'get_context'):
+ method = os.environ.get('JOBLIB_START_METHOD', '').strip() or None
+ if method is not None:
+ DEFAULT_MP_CONTEXT = mp.get_context(method=method)
+
+
+class BatchedCalls(object):
+ """Wrap a sequence of (func, args, kwargs) tuples as a single callable"""
+
+ def __init__(self, iterator_slice, backend_and_jobs, reducer_callback=None,
+ pickle_cache=None):
+ self.items = list(iterator_slice)
+ self._size = len(self.items)
+ self._reducer_callback = reducer_callback
+ if isinstance(backend_and_jobs, tuple):
+ self._backend, self._n_jobs = backend_and_jobs
+ else:
+ # this is for backward compatibility purposes. Before 0.12.6,
+ # nested backends were returned without n_jobs indications.
+ self._backend, self._n_jobs = backend_and_jobs, None
+ self._pickle_cache = pickle_cache if pickle_cache is not None else {}
+
+ def __call__(self):
+ # Set the default nested backend to self._backend but do not set the
+ # change the default number of processes to -1
+ with parallel_backend(self._backend, n_jobs=self._n_jobs):
+ return [func(*args, **kwargs)
+ for func, args, kwargs in self.items]
+
+ def __reduce__(self):
+ if self._reducer_callback is not None:
+ self._reducer_callback()
+ # no need pickle the callback.
+ return (
+ BatchedCalls,
+ (self.items, (self._backend, self._n_jobs), None,
+ self._pickle_cache)
+ )
+
+ def __len__(self):
+ return self._size
+
+
+###############################################################################
+# CPU count that works also when multiprocessing has been disabled via
+# the JOBLIB_MULTIPROCESSING environment variable
+def cpu_count(only_physical_cores=False):
+ """Return the number of CPUs.
+
+ This delegates to loky.cpu_count that takes into account additional
+ constraints such as Linux CFS scheduler quotas (typically set by container
+ runtimes such as docker) and CPU affinity (for instance using the taskset
+ command on Linux).
+
+ If only_physical_cores is True, do not take hyperthreading / SMT logical
+ cores into account.
+ """
+ if mp is None:
+ return 1
+
+ return loky.cpu_count(only_physical_cores=only_physical_cores)
+
+
+###############################################################################
+# For verbosity
+
+def _verbosity_filter(index, verbose):
+ """ Returns False for indices increasingly apart, the distance
+ depending on the value of verbose.
+
+ We use a lag increasing as the square of index
+ """
+ if not verbose:
+ return True
+ elif verbose > 10:
+ return False
+ if index == 0:
+ return False
+ verbose = .5 * (11 - verbose) ** 2
+ scale = sqrt(index / verbose)
+ next_scale = sqrt((index + 1) / verbose)
+ return (int(next_scale) == int(scale))
+
+
+###############################################################################
+def delayed(function):
+ """Decorator used to capture the arguments of a function."""
+
+ def delayed_function(*args, **kwargs):
+ return function, args, kwargs
+ try:
+ delayed_function = functools.wraps(function)(delayed_function)
+ except AttributeError:
+ " functools.wraps fails on some callable objects "
+ return delayed_function
+
+
+###############################################################################
+class BatchCompletionCallBack(object):
+ """Callback used by joblib.Parallel's multiprocessing backend.
+
+ This callable is executed by the parent process whenever a worker process
+ has returned the results of a batch of tasks.
+
+ It is used for progress reporting, to update estimate of the batch
+ processing duration and to schedule the next batch of tasks to be
+ processed.
+
+ """
+ def __init__(self, dispatch_timestamp, batch_size, parallel):
+ self.dispatch_timestamp = dispatch_timestamp
+ self.batch_size = batch_size
+ self.parallel = parallel
+
+ def __call__(self, out):
+ self.parallel.n_completed_tasks += self.batch_size
+ this_batch_duration = time.time() - self.dispatch_timestamp
+
+ self.parallel._backend.batch_completed(self.batch_size,
+ this_batch_duration)
+ self.parallel.print_progress()
+ with self.parallel._lock:
+ if self.parallel._original_iterator is not None:
+ self.parallel.dispatch_next()
+
+
+###############################################################################
+def register_parallel_backend(name, factory, make_default=False):
+ """Register a new Parallel backend factory.
+
+ The new backend can then be selected by passing its name as the backend
+ argument to the :class:`~Parallel` class. Moreover, the default backend can
+ be overwritten globally by setting make_default=True.
+
+ The factory can be any callable that takes no argument and return an
+ instance of ``ParallelBackendBase``.
+
+ Warning: this function is experimental and subject to change in a future
+ version of joblib.
+
+ .. versionadded:: 0.10
+
+ """
+ BACKENDS[name] = factory
+ if make_default:
+ global DEFAULT_BACKEND
+ DEFAULT_BACKEND = name
+
+
+def effective_n_jobs(n_jobs=-1):
+ """Determine the number of jobs that can actually run in parallel
+
+ n_jobs is the number of workers requested by the callers. Passing n_jobs=-1
+ means requesting all available workers for instance matching the number of
+ CPU cores on the worker host(s).
+
+ This method should return a guesstimate of the number of workers that can
+ actually perform work concurrently with the currently enabled default
+ backend. The primary use case is to make it possible for the caller to know
+ in how many chunks to slice the work.
+
+ In general working on larger data chunks is more efficient (less scheduling
+ overhead and better use of CPU cache prefetching heuristics) as long as all
+ the workers have enough work to do.
+
+ Warning: this function is experimental and subject to change in a future
+ version of joblib.
+
+ .. versionadded:: 0.10
+
+ """
+ backend, backend_n_jobs = get_active_backend()
+ if n_jobs is None:
+ n_jobs = backend_n_jobs
+ return backend.effective_n_jobs(n_jobs=n_jobs)
+
+
+###############################################################################
+class Parallel(Logger):
+ ''' Helper class for readable parallel mapping.
+
+ Read more in the :ref:`User Guide `.
+
+ Parameters
+ -----------
+ n_jobs: int, default: None
+ The maximum number of concurrently running jobs, such as the number
+ of Python worker processes when backend="multiprocessing"
+ or the size of the thread-pool when backend="threading".
+ If -1 all CPUs are used. If 1 is given, no parallel computing code
+ is used at all, which is useful for debugging. For n_jobs below -1,
+ (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all
+ CPUs but one are used.
+ None is a marker for 'unset' that will be interpreted as n_jobs=1
+ (sequential execution) unless the call is performed under a
+ :func:`~parallel_backend` context manager that sets another value
+ for n_jobs.
+ backend: str, ParallelBackendBase instance or None, default: 'loky'
+ Specify the parallelization backend implementation.
+ Supported backends are:
+
+ - "loky" used by default, can induce some
+ communication and memory overhead when exchanging input and
+ output data with the worker Python processes. On some rare
+ systems (such as Pyiodide), the loky backend may not be
+ available.
+ - "multiprocessing" previous process-based backend based on
+ `multiprocessing.Pool`. Less robust than `loky`.
+ - "threading" is a very low-overhead backend but it suffers
+ from the Python Global Interpreter Lock if the called function
+ relies a lot on Python objects. "threading" is mostly useful
+ when the execution bottleneck is a compiled extension that
+ explicitly releases the GIL (for instance a Cython loop wrapped
+ in a "with nogil" block or an expensive call to a library such
+ as NumPy).
+ - finally, you can register backends by calling
+ :func:`~register_parallel_backend`. This will allow you to
+ implement a backend of your liking.
+
+ It is not recommended to hard-code the backend name in a call to
+ :class:`~Parallel` in a library. Instead it is recommended to set
+ soft hints (prefer) or hard constraints (require) so as to make it
+ possible for library users to change the backend from the outside
+ using the :func:`~parallel_backend` context manager.
+ prefer: str in {'processes', 'threads'} or None, default: None
+ Soft hint to choose the default backend if no specific backend
+ was selected with the :func:`~parallel_backend` context manager.
+ The default process-based backend is 'loky' and the default
+ thread-based backend is 'threading'. Ignored if the ``backend``
+ parameter is specified.
+ require: 'sharedmem' or None, default None
+ Hard constraint to select the backend. If set to 'sharedmem',
+ the selected backend will be single-host and thread-based even
+ if the user asked for a non-thread based backend with
+ parallel_backend.
+ verbose: int, optional
+ The verbosity level: if non zero, progress messages are
+ printed. Above 50, the output is sent to stdout.
+ The frequency of the messages increases with the verbosity level.
+ If it more than 10, all iterations are reported.
+ timeout: float, optional
+ Timeout limit for each task to complete. If any task takes longer
+ a TimeOutError will be raised. Only applied when n_jobs != 1
+ pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'}
+ The number of batches (of tasks) to be pre-dispatched.
+ Default is '2*n_jobs'. When batch_size="auto" this is reasonable
+ default and the workers should never starve. Note that only basic
+ arithmetics are allowed here and no modules can be used in this
+ expression.
+ batch_size: int or 'auto', default: 'auto'
+ The number of atomic tasks to dispatch at once to each
+ worker. When individual evaluations are very fast, dispatching
+ calls to workers can be slower than sequential computation because
+ of the overhead. Batching fast computations together can mitigate
+ this.
+ The ``'auto'`` strategy keeps track of the time it takes for a batch
+ to complete, and dynamically adjusts the batch size to keep the time
+ on the order of half a second, using a heuristic. The initial batch
+ size is 1.
+ ``batch_size="auto"`` with ``backend="threading"`` will dispatch
+ batches of a single task at a time as the threading backend has
+ very little overhead and using larger batch size has not proved to
+ bring any gain in that case.
+ temp_folder: str, optional
+ Folder to be used by the pool for memmapping large arrays
+ for sharing memory with worker processes. If None, this will try in
+ order:
+
+ - a folder pointed by the JOBLIB_TEMP_FOLDER environment
+ variable,
+ - /dev/shm if the folder exists and is writable: this is a
+ RAM disk filesystem available by default on modern Linux
+ distributions,
+ - the default system temporary folder that can be
+ overridden with TMP, TMPDIR or TEMP environment
+ variables, typically /tmp under Unix operating systems.
+
+ Only active when backend="loky" or "multiprocessing".
+ max_nbytes int, str, or None, optional, 1M by default
+ Threshold on the size of arrays passed to the workers that
+ triggers automated memory mapping in temp_folder. Can be an int
+ in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte.
+ Use None to disable memmapping of large arrays.
+ Only active when backend="loky" or "multiprocessing".
+ mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default: 'r'
+ Memmapping mode for numpy arrays passed to workers. None will
+ disable memmapping, other modes defined in the numpy.memmap doc:
+ https://numpy.org/doc/stable/reference/generated/numpy.memmap.html
+ Also, see 'max_nbytes' parameter documentation for more details.
+
+ Notes
+ -----
+
+ This object uses workers to compute in parallel the application of a
+ function to many different arguments. The main functionality it brings
+ in addition to using the raw multiprocessing or concurrent.futures API
+ are (see examples for details):
+
+ * More readable code, in particular since it avoids
+ constructing list of arguments.
+
+ * Easier debugging:
+ - informative tracebacks even when the error happens on
+ the client side
+ - using 'n_jobs=1' enables to turn off parallel computing
+ for debugging without changing the codepath
+ - early capture of pickling errors
+
+ * An optional progress meter.
+
+ * Interruption of multiprocesses jobs with 'Ctrl-C'
+
+ * Flexible pickling control for the communication to and from
+ the worker processes.
+
+ * Ability to use shared memory efficiently with worker
+ processes for large numpy-based datastructures.
+
+ Examples
+ --------
+
+ A simple example:
+
+ >>> from math import sqrt
+ >>> from joblib import Parallel, delayed
+ >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
+ [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
+
+ Reshaping the output when the function has several return
+ values:
+
+ >>> from math import modf
+ >>> from joblib import Parallel, delayed
+ >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10))
+ >>> res, i = zip(*r)
+ >>> res
+ (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5)
+ >>> i
+ (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0)
+
+ The progress meter: the higher the value of `verbose`, the more
+ messages:
+
+ >>> from time import sleep
+ >>> from joblib import Parallel, delayed
+ >>> r = Parallel(n_jobs=2, verbose=10)(delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP
+ [Parallel(n_jobs=2)]: Done 1 tasks | elapsed: 0.6s
+ [Parallel(n_jobs=2)]: Done 4 tasks | elapsed: 0.8s
+ [Parallel(n_jobs=2)]: Done 10 out of 10 | elapsed: 1.4s finished
+
+ Traceback example, note how the line of the error is indicated
+ as well as the values of the parameter passed to the function that
+ triggered the exception, even though the traceback happens in the
+ child process:
+
+ >>> from heapq import nlargest
+ >>> from joblib import Parallel, delayed
+ >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP
+ #...
+ ---------------------------------------------------------------------------
+ Sub-process traceback:
+ ---------------------------------------------------------------------------
+ TypeError Mon Nov 12 11:37:46 2012
+ PID: 12934 Python 2.7.3: /usr/bin/python
+ ...........................................................................
+ /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None)
+ 419 if n >= size:
+ 420 return sorted(iterable, key=key, reverse=True)[:n]
+ 421
+ 422 # When key is none, use simpler decoration
+ 423 if key is None:
+ --> 424 it = izip(iterable, count(0,-1)) # decorate
+ 425 result = _nlargest(n, it)
+ 426 return map(itemgetter(0), result) # undecorate
+ 427
+ 428 # General case, slowest method
+ TypeError: izip argument #1 must support iteration
+ ___________________________________________________________________________
+
+
+ Using pre_dispatch in a producer/consumer situation, where the
+ data is generated on the fly. Note how the producer is first
+ called 3 times before the parallel loop is initiated, and then
+ called to generate new data on the fly:
+
+ >>> from math import sqrt
+ >>> from joblib import Parallel, delayed
+ >>> def producer():
+ ... for i in range(6):
+ ... print('Produced %s' % i)
+ ... yield i
+ >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')(
+ ... delayed(sqrt)(i) for i in producer()) #doctest: +SKIP
+ Produced 0
+ Produced 1
+ Produced 2
+ [Parallel(n_jobs=2)]: Done 1 jobs | elapsed: 0.0s
+ Produced 3
+ [Parallel(n_jobs=2)]: Done 2 jobs | elapsed: 0.0s
+ Produced 4
+ [Parallel(n_jobs=2)]: Done 3 jobs | elapsed: 0.0s
+ Produced 5
+ [Parallel(n_jobs=2)]: Done 4 jobs | elapsed: 0.0s
+ [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s remaining: 0.0s
+ [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed: 0.0s finished
+
+ '''
+ def __init__(self, n_jobs=None, backend=None, verbose=0, timeout=None,
+ pre_dispatch='2 * n_jobs', batch_size='auto',
+ temp_folder=None, max_nbytes='1M', mmap_mode='r',
+ prefer=None, require=None):
+ active_backend, context_n_jobs = get_active_backend(
+ prefer=prefer, require=require, verbose=verbose)
+ nesting_level = active_backend.nesting_level
+ if backend is None and n_jobs is None:
+ # If we are under a parallel_backend context manager, look up
+ # the default number of jobs and use that instead:
+ n_jobs = context_n_jobs
+ if n_jobs is None:
+ # No specific context override and no specific value request:
+ # default to 1.
+ n_jobs = 1
+ self.n_jobs = n_jobs
+ self.verbose = verbose
+ self.timeout = timeout
+ self.pre_dispatch = pre_dispatch
+ self._ready_batches = queue.Queue()
+ self._id = uuid4().hex
+ self._reducer_callback = None
+
+ if isinstance(max_nbytes, str):
+ max_nbytes = memstr_to_bytes(max_nbytes)
+
+ self._backend_args = dict(
+ max_nbytes=max_nbytes,
+ mmap_mode=mmap_mode,
+ temp_folder=temp_folder,
+ prefer=prefer,
+ require=require,
+ verbose=max(0, self.verbose - 50),
+ )
+ if DEFAULT_MP_CONTEXT is not None:
+ self._backend_args['context'] = DEFAULT_MP_CONTEXT
+ elif hasattr(mp, "get_context"):
+ self._backend_args['context'] = mp.get_context()
+
+ if backend is None:
+ backend = active_backend
+
+ elif isinstance(backend, ParallelBackendBase):
+ # Use provided backend as is, with the current nesting_level if it
+ # is not set yet.
+ if backend.nesting_level is None:
+ backend.nesting_level = nesting_level
+
+ elif hasattr(backend, 'Pool') and hasattr(backend, 'Lock'):
+ # Make it possible to pass a custom multiprocessing context as
+ # backend to change the start method to forkserver or spawn or
+ # preload modules on the forkserver helper process.
+ self._backend_args['context'] = backend
+ backend = MultiprocessingBackend(nesting_level=nesting_level)
+
+ elif backend not in BACKENDS and backend in MAYBE_AVAILABLE_BACKENDS:
+ warnings.warn(
+ f"joblib backend '{backend}' is not available on "
+ f"your system, falling back to {DEFAULT_BACKEND}.",
+ UserWarning,
+ stacklevel=2)
+ BACKENDS[backend] = BACKENDS[DEFAULT_BACKEND]
+ backend = BACKENDS[DEFAULT_BACKEND](nesting_level=nesting_level)
+
+ else:
+ try:
+ backend_factory = BACKENDS[backend]
+ except KeyError as e:
+ raise ValueError("Invalid backend: %s, expected one of %r"
+ % (backend, sorted(BACKENDS.keys()))) from e
+ backend = backend_factory(nesting_level=nesting_level)
+
+ if (require == 'sharedmem' and
+ not getattr(backend, 'supports_sharedmem', False)):
+ raise ValueError("Backend %s does not support shared memory"
+ % backend)
+
+ if (batch_size == 'auto' or isinstance(batch_size, Integral) and
+ batch_size > 0):
+ self.batch_size = batch_size
+ else:
+ raise ValueError(
+ "batch_size must be 'auto' or a positive integer, got: %r"
+ % batch_size)
+
+ self._backend = backend
+ self._output = None
+ self._jobs = list()
+ self._managed_backend = False
+
+ # This lock is used coordinate the main thread of this process with
+ # the async callback thread of our the pool.
+ self._lock = threading.RLock()
+
+ def __enter__(self):
+ self._managed_backend = True
+ self._initialize_backend()
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self._terminate_backend()
+ self._managed_backend = False
+
+ def _initialize_backend(self):
+ """Build a process or thread pool and return the number of workers"""
+ try:
+ n_jobs = self._backend.configure(n_jobs=self.n_jobs, parallel=self,
+ **self._backend_args)
+ if self.timeout is not None and not self._backend.supports_timeout:
+ warnings.warn(
+ 'The backend class {!r} does not support timeout. '
+ "You have set 'timeout={}' in Parallel but "
+ "the 'timeout' parameter will not be used.".format(
+ self._backend.__class__.__name__,
+ self.timeout))
+
+ except FallbackToBackend as e:
+ # Recursively initialize the backend in case of requested fallback.
+ self._backend = e.backend
+ n_jobs = self._initialize_backend()
+
+ return n_jobs
+
+ def _effective_n_jobs(self):
+ if self._backend:
+ return self._backend.effective_n_jobs(self.n_jobs)
+ return 1
+
+ def _terminate_backend(self):
+ if self._backend is not None:
+ self._backend.terminate()
+
+ def _dispatch(self, batch):
+ """Queue the batch for computing, with or without multiprocessing
+
+ WARNING: this method is not thread-safe: it should be only called
+ indirectly via dispatch_one_batch.
+
+ """
+ # If job.get() catches an exception, it closes the queue:
+ if self._aborting:
+ return
+
+ self.n_dispatched_tasks += len(batch)
+ self.n_dispatched_batches += 1
+
+ dispatch_timestamp = time.time()
+ cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self)
+ with self._lock:
+ job_idx = len(self._jobs)
+ job = self._backend.apply_async(batch, callback=cb)
+ # A job can complete so quickly than its callback is
+ # called before we get here, causing self._jobs to
+ # grow. To ensure correct results ordering, .insert is
+ # used (rather than .append) in the following line
+ self._jobs.insert(job_idx, job)
+
+ def dispatch_next(self):
+ """Dispatch more data for parallel processing
+
+ This method is meant to be called concurrently by the multiprocessing
+ callback. We rely on the thread-safety of dispatch_one_batch to protect
+ against concurrent consumption of the unprotected iterator.
+
+ """
+ if not self.dispatch_one_batch(self._original_iterator):
+ self._iterating = False
+ self._original_iterator = None
+
+ def dispatch_one_batch(self, iterator):
+ """Prefetch the tasks for the next batch and dispatch them.
+
+ The effective size of the batch is computed here.
+ If there are no more jobs to dispatch, return False, else return True.
+
+ The iterator consumption and dispatching is protected by the same
+ lock so calling this function should be thread safe.
+
+ """
+ if self.batch_size == 'auto':
+ batch_size = self._backend.compute_batch_size()
+ else:
+ # Fixed batch size strategy
+ batch_size = self.batch_size
+
+ with self._lock:
+ # to ensure an even distribution of the workolad between workers,
+ # we look ahead in the original iterators more than batch_size
+ # tasks - However, we keep consuming only one batch at each
+ # dispatch_one_batch call. The extra tasks are stored in a local
+ # queue, _ready_batches, that is looked-up prior to re-consuming
+ # tasks from the origal iterator.
+ try:
+ tasks = self._ready_batches.get(block=False)
+ except queue.Empty:
+ # slice the iterator n_jobs * batchsize items at a time. If the
+ # slice returns less than that, then the current batchsize puts
+ # too much weight on a subset of workers, while other may end
+ # up starving. So in this case, re-scale the batch size
+ # accordingly to distribute evenly the last items between all
+ # workers.
+ n_jobs = self._cached_effective_n_jobs
+ big_batch_size = batch_size * n_jobs
+
+ islice = list(itertools.islice(iterator, big_batch_size))
+ if len(islice) == 0:
+ return False
+ elif (iterator is self._original_iterator
+ and len(islice) < big_batch_size):
+ # We reached the end of the original iterator (unless
+ # iterator is the ``pre_dispatch``-long initial slice of
+ # the original iterator) -- decrease the batch size to
+ # account for potential variance in the batches running
+ # time.
+ final_batch_size = max(1, len(islice) // (10 * n_jobs))
+ else:
+ final_batch_size = max(1, len(islice) // n_jobs)
+
+ # enqueue n_jobs batches in a local queue
+ for i in range(0, len(islice), final_batch_size):
+ tasks = BatchedCalls(islice[i:i + final_batch_size],
+ self._backend.get_nested_backend(),
+ self._reducer_callback,
+ self._pickle_cache)
+ self._ready_batches.put(tasks)
+
+ # finally, get one task.
+ tasks = self._ready_batches.get(block=False)
+ if len(tasks) == 0:
+ # No more tasks available in the iterator: tell caller to stop.
+ return False
+ else:
+ self._dispatch(tasks)
+ return True
+
+ def _print(self, msg, msg_args):
+ """Display the message on stout or stderr depending on verbosity"""
+ # XXX: Not using the logger framework: need to
+ # learn to use logger better.
+ if not self.verbose:
+ return
+ if self.verbose < 50:
+ writer = sys.stderr.write
+ else:
+ writer = sys.stdout.write
+ msg = msg % msg_args
+ writer('[%s]: %s\n' % (self, msg))
+
+ def print_progress(self):
+ """Display the process of the parallel execution only a fraction
+ of time, controlled by self.verbose.
+ """
+ if not self.verbose:
+ return
+ elapsed_time = time.time() - self._start_time
+
+ # Original job iterator becomes None once it has been fully
+ # consumed : at this point we know the total number of jobs and we are
+ # able to display an estimation of the remaining time based on already
+ # completed jobs. Otherwise, we simply display the number of completed
+ # tasks.
+ if self._original_iterator is not None:
+ if _verbosity_filter(self.n_dispatched_batches, self.verbose):
+ return
+ self._print('Done %3i tasks | elapsed: %s',
+ (self.n_completed_tasks,
+ short_format_time(elapsed_time), ))
+ else:
+ index = self.n_completed_tasks
+ # We are finished dispatching
+ total_tasks = self.n_dispatched_tasks
+ # We always display the first loop
+ if not index == 0:
+ # Display depending on the number of remaining items
+ # A message as soon as we finish dispatching, cursor is 0
+ cursor = (total_tasks - index + 1 -
+ self._pre_dispatch_amount)
+ frequency = (total_tasks // self.verbose) + 1
+ is_last_item = (index + 1 == total_tasks)
+ if (is_last_item or cursor % frequency):
+ return
+ remaining_time = (elapsed_time / index) * \
+ (self.n_dispatched_tasks - index * 1.0)
+ # only display status if remaining time is greater or equal to 0
+ self._print('Done %3i out of %3i | elapsed: %s remaining: %s',
+ (index,
+ total_tasks,
+ short_format_time(elapsed_time),
+ short_format_time(remaining_time),
+ ))
+
+ def retrieve(self):
+ self._output = list()
+ while self._iterating or len(self._jobs) > 0:
+ if len(self._jobs) == 0:
+ # Wait for an async callback to dispatch new jobs
+ time.sleep(0.01)
+ continue
+ # We need to be careful: the job list can be filling up as
+ # we empty it and Python list are not thread-safe by default hence
+ # the use of the lock
+ with self._lock:
+ job = self._jobs.pop(0)
+
+ try:
+ if getattr(self._backend, 'supports_timeout', False):
+ self._output.extend(job.get(timeout=self.timeout))
+ else:
+ self._output.extend(job.get())
+
+ except BaseException as exception:
+ # Note: we catch any BaseException instead of just Exception
+ # instances to also include KeyboardInterrupt.
+
+ # Stop dispatching any new job in the async callback thread
+ self._aborting = True
+
+ # If the backend allows it, cancel or kill remaining running
+ # tasks without waiting for the results as we will raise
+ # the exception we got back to the caller instead of returning
+ # any result.
+ backend = self._backend
+ if (backend is not None and
+ hasattr(backend, 'abort_everything')):
+ # If the backend is managed externally we need to make sure
+ # to leave it in a working state to allow for future jobs
+ # scheduling.
+ ensure_ready = self._managed_backend
+ backend.abort_everything(ensure_ready=ensure_ready)
+ raise
+
+ def __call__(self, iterable):
+ if self._jobs:
+ raise ValueError('This Parallel instance is already running')
+ # A flag used to abort the dispatching of jobs in case an
+ # exception is found
+ self._aborting = False
+
+ if not self._managed_backend:
+ n_jobs = self._initialize_backend()
+ else:
+ n_jobs = self._effective_n_jobs()
+
+ if isinstance(self._backend, LokyBackend):
+ # For the loky backend, we add a callback executed when reducing
+ # BatchCalls, that makes the loky executor use a temporary folder
+ # specific to this Parallel object when pickling temporary memmaps.
+ # This callback is necessary to ensure that several Parallel
+ # objects using the same resuable executor don't use the same
+ # temporary resources.
+
+ def _batched_calls_reducer_callback():
+ # Relevant implementation detail: the following lines, called
+ # when reducing BatchedCalls, are called in a thread-safe
+ # situation, meaning that the context of the temporary folder
+ # manager will not be changed in between the callback execution
+ # and the end of the BatchedCalls pickling. The reason is that
+ # pickling (the only place where set_current_context is used)
+ # is done from a single thread (the queue_feeder_thread).
+ self._backend._workers._temp_folder_manager.set_current_context( # noqa
+ self._id
+ )
+ self._reducer_callback = _batched_calls_reducer_callback
+
+ # self._effective_n_jobs should be called in the Parallel.__call__
+ # thread only -- store its value in an attribute for further queries.
+ self._cached_effective_n_jobs = n_jobs
+
+ backend_name = self._backend.__class__.__name__
+ if n_jobs == 0:
+ raise RuntimeError("%s has no active worker." % backend_name)
+
+ self._print("Using backend %s with %d concurrent workers.",
+ (backend_name, n_jobs))
+ if hasattr(self._backend, 'start_call'):
+ self._backend.start_call()
+ iterator = iter(iterable)
+ pre_dispatch = self.pre_dispatch
+
+ if pre_dispatch == 'all' or n_jobs == 1:
+ # prevent further dispatch via multiprocessing callback thread
+ self._original_iterator = None
+ self._pre_dispatch_amount = 0
+ else:
+ self._original_iterator = iterator
+ if hasattr(pre_dispatch, 'endswith'):
+ pre_dispatch = eval_expr(
+ pre_dispatch.replace("n_jobs", str(n_jobs))
+ )
+ self._pre_dispatch_amount = pre_dispatch = int(pre_dispatch)
+
+ # The main thread will consume the first pre_dispatch items and
+ # the remaining items will later be lazily dispatched by async
+ # callbacks upon task completions.
+
+ # TODO: this iterator should be batch_size * n_jobs
+ iterator = itertools.islice(iterator, self._pre_dispatch_amount)
+
+ self._start_time = time.time()
+ self.n_dispatched_batches = 0
+ self.n_dispatched_tasks = 0
+ self.n_completed_tasks = 0
+ # Use a caching dict for callables that are pickled with cloudpickle to
+ # improve performances. This cache is used only in the case of
+ # functions that are defined in the __main__ module, functions that are
+ # defined locally (inside another function) and lambda expressions.
+ self._pickle_cache = dict()
+ try:
+ # Only set self._iterating to True if at least a batch
+ # was dispatched. In particular this covers the edge
+ # case of Parallel used with an exhausted iterator. If
+ # self._original_iterator is None, then this means either
+ # that pre_dispatch == "all", n_jobs == 1 or that the first batch
+ # was very quick and its callback already dispatched all the
+ # remaining jobs.
+ self._iterating = False
+ if self.dispatch_one_batch(iterator):
+ self._iterating = self._original_iterator is not None
+
+ while self.dispatch_one_batch(iterator):
+ pass
+
+ if pre_dispatch == "all" or n_jobs == 1:
+ # The iterable was consumed all at once by the above for loop.
+ # No need to wait for async callbacks to trigger to
+ # consumption.
+ self._iterating = False
+
+ with self._backend.retrieval_context():
+ self.retrieve()
+ # Make sure that we get a last message telling us we are done
+ elapsed_time = time.time() - self._start_time
+ self._print('Done %3i out of %3i | elapsed: %s finished',
+ (len(self._output), len(self._output),
+ short_format_time(elapsed_time)))
+ finally:
+ if hasattr(self._backend, 'stop_call'):
+ self._backend.stop_call()
+ if not self._managed_backend:
+ self._terminate_backend()
+ self._jobs = list()
+ self._pickle_cache = None
+ output = self._output
+ self._output = None
+ return output
+
+ def __repr__(self):
+ return '%s(n_jobs=%s)' % (self.__class__.__name__, self.n_jobs)
diff --git a/runtime/Lib/site-packages/joblib/pool.py b/runtime/Lib/site-packages/joblib/pool.py
new file mode 100644
index 0000000000000000000000000000000000000000..8443899339e45e3d9d971e9fc4ab656aeb5b8e64
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/pool.py
@@ -0,0 +1,352 @@
+"""Custom implementation of multiprocessing.Pool with custom pickler.
+
+This module provides efficient ways of working with data stored in
+shared memory with numpy.memmap arrays without inducing any memory
+copy between the parent and child processes.
+
+This module should not be imported if multiprocessing is not
+available as it implements subclasses of multiprocessing Pool
+that uses a custom alternative to SimpleQueue.
+
+"""
+# Author: Olivier Grisel
+# Copyright: 2012, Olivier Grisel
+# License: BSD 3 clause
+
+import copyreg
+import sys
+import warnings
+from time import sleep
+
+try:
+ WindowsError
+except NameError:
+ WindowsError = type(None)
+
+from pickle import Pickler
+
+from pickle import HIGHEST_PROTOCOL
+from io import BytesIO
+
+from ._memmapping_reducer import get_memmapping_reducers
+from ._memmapping_reducer import TemporaryResourcesManager
+from ._multiprocessing_helpers import mp, assert_spawning
+
+# We need the class definition to derive from it, not the multiprocessing.Pool
+# factory function
+from multiprocessing.pool import Pool
+
+try:
+ import numpy as np
+except ImportError:
+ np = None
+
+
+###############################################################################
+# Enable custom pickling in Pool queues
+
+class CustomizablePickler(Pickler):
+ """Pickler that accepts custom reducers.
+
+ TODO python2_drop : can this be simplified ?
+
+ HIGHEST_PROTOCOL is selected by default as this pickler is used
+ to pickle ephemeral datastructures for interprocess communication
+ hence no backward compatibility is required.
+
+ `reducers` is expected to be a dictionary with key/values
+ being `(type, callable)` pairs where `callable` is a function that
+ give an instance of `type` will return a tuple `(constructor,
+ tuple_of_objects)` to rebuild an instance out of the pickled
+ `tuple_of_objects` as would return a `__reduce__` method. See the
+ standard library documentation on pickling for more details.
+
+ """
+
+ # We override the pure Python pickler as its the only way to be able to
+ # customize the dispatch table without side effects in Python 2.7
+ # to 3.2. For Python 3.3+ leverage the new dispatch_table
+ # feature from https://bugs.python.org/issue14166 that makes it possible
+ # to use the C implementation of the Pickler which is faster.
+
+ def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL):
+ Pickler.__init__(self, writer, protocol=protocol)
+ if reducers is None:
+ reducers = {}
+ if hasattr(Pickler, 'dispatch'):
+ # Make the dispatch registry an instance level attribute instead of
+ # a reference to the class dictionary under Python 2
+ self.dispatch = Pickler.dispatch.copy()
+ else:
+ # Under Python 3 initialize the dispatch table with a copy of the
+ # default registry
+ self.dispatch_table = copyreg.dispatch_table.copy()
+ for type, reduce_func in reducers.items():
+ self.register(type, reduce_func)
+
+ def register(self, type, reduce_func):
+ """Attach a reducer function to a given type in the dispatch table."""
+ if hasattr(Pickler, 'dispatch'):
+ # Python 2 pickler dispatching is not explicitly customizable.
+ # Let us use a closure to workaround this limitation.
+ def dispatcher(self, obj):
+ reduced = reduce_func(obj)
+ self.save_reduce(obj=obj, *reduced)
+ self.dispatch[type] = dispatcher
+ else:
+ self.dispatch_table[type] = reduce_func
+
+
+class CustomizablePicklingQueue(object):
+ """Locked Pipe implementation that uses a customizable pickler.
+
+ This class is an alternative to the multiprocessing implementation
+ of SimpleQueue in order to make it possible to pass custom
+ pickling reducers, for instance to avoid memory copy when passing
+ memory mapped datastructures.
+
+ `reducers` is expected to be a dict with key / values being
+ `(type, callable)` pairs where `callable` is a function that, given an
+ instance of `type`, will return a tuple `(constructor, tuple_of_objects)`
+ to rebuild an instance out of the pickled `tuple_of_objects` as would
+ return a `__reduce__` method.
+
+ See the standard library documentation on pickling for more details.
+ """
+
+ def __init__(self, context, reducers=None):
+ self._reducers = reducers
+ self._reader, self._writer = context.Pipe(duplex=False)
+ self._rlock = context.Lock()
+ if sys.platform == 'win32':
+ self._wlock = None
+ else:
+ self._wlock = context.Lock()
+ self._make_methods()
+
+ def __getstate__(self):
+ assert_spawning(self)
+ return (self._reader, self._writer, self._rlock, self._wlock,
+ self._reducers)
+
+ def __setstate__(self, state):
+ (self._reader, self._writer, self._rlock, self._wlock,
+ self._reducers) = state
+ self._make_methods()
+
+ def empty(self):
+ return not self._reader.poll()
+
+ def _make_methods(self):
+ self._recv = recv = self._reader.recv
+ racquire, rrelease = self._rlock.acquire, self._rlock.release
+
+ def get():
+ racquire()
+ try:
+ return recv()
+ finally:
+ rrelease()
+
+ self.get = get
+
+ if self._reducers:
+ def send(obj):
+ buffer = BytesIO()
+ CustomizablePickler(buffer, self._reducers).dump(obj)
+ self._writer.send_bytes(buffer.getvalue())
+ self._send = send
+ else:
+ self._send = send = self._writer.send
+ if self._wlock is None:
+ # writes to a message oriented win32 pipe are atomic
+ self.put = send
+ else:
+ wlock_acquire, wlock_release = (
+ self._wlock.acquire, self._wlock.release)
+
+ def put(obj):
+ wlock_acquire()
+ try:
+ return send(obj)
+ finally:
+ wlock_release()
+
+ self.put = put
+
+
+class PicklingPool(Pool):
+ """Pool implementation with customizable pickling reducers.
+
+ This is useful to control how data is shipped between processes
+ and makes it possible to use shared memory without useless
+ copies induces by the default pickling methods of the original
+ objects passed as arguments to dispatch.
+
+ `forward_reducers` and `backward_reducers` are expected to be
+ dictionaries with key/values being `(type, callable)` pairs where
+ `callable` is a function that, given an instance of `type`, will return a
+ tuple `(constructor, tuple_of_objects)` to rebuild an instance out of the
+ pickled `tuple_of_objects` as would return a `__reduce__` method.
+ See the standard library documentation about pickling for more details.
+
+ """
+
+ def __init__(self, processes=None, forward_reducers=None,
+ backward_reducers=None, **kwargs):
+ if forward_reducers is None:
+ forward_reducers = dict()
+ if backward_reducers is None:
+ backward_reducers = dict()
+ self._forward_reducers = forward_reducers
+ self._backward_reducers = backward_reducers
+ poolargs = dict(processes=processes)
+ poolargs.update(kwargs)
+ super(PicklingPool, self).__init__(**poolargs)
+
+ def _setup_queues(self):
+ context = getattr(self, '_ctx', mp)
+ self._inqueue = CustomizablePicklingQueue(context,
+ self._forward_reducers)
+ self._outqueue = CustomizablePicklingQueue(context,
+ self._backward_reducers)
+ self._quick_put = self._inqueue._send
+ self._quick_get = self._outqueue._recv
+
+
+class MemmappingPool(PicklingPool):
+ """Process pool that shares large arrays to avoid memory copy.
+
+ This drop-in replacement for `multiprocessing.pool.Pool` makes
+ it possible to work efficiently with shared memory in a numpy
+ context.
+
+ Existing instances of numpy.memmap are preserved: the child
+ suprocesses will have access to the same shared memory in the
+ original mode except for the 'w+' mode that is automatically
+ transformed as 'r+' to avoid zeroing the original data upon
+ instantiation.
+
+ Furthermore large arrays from the parent process are automatically
+ dumped to a temporary folder on the filesystem such as child
+ processes to access their content via memmapping (file system
+ backed shared memory).
+
+ Note: it is important to call the terminate method to collect
+ the temporary folder used by the pool.
+
+ Parameters
+ ----------
+ processes: int, optional
+ Number of worker processes running concurrently in the pool.
+ initializer: callable, optional
+ Callable executed on worker process creation.
+ initargs: tuple, optional
+ Arguments passed to the initializer callable.
+ temp_folder: (str, callable) optional
+ If str:
+ Folder to be used by the pool for memmapping large arrays
+ for sharing memory with worker processes. If None, this will try in
+ order:
+ - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable,
+ - /dev/shm if the folder exists and is writable: this is a RAMdisk
+ filesystem available by default on modern Linux distributions,
+ - the default system temporary folder that can be overridden
+ with TMP, TMPDIR or TEMP environment variables, typically /tmp
+ under Unix operating systems.
+ if callable:
+ An callable in charge of dynamically resolving a temporary folder
+ for memmapping large arrays.
+ max_nbytes int or None, optional, 1e6 by default
+ Threshold on the size of arrays passed to the workers that
+ triggers automated memory mapping in temp_folder.
+ Use None to disable memmapping of large arrays.
+ mmap_mode: {'r+', 'r', 'w+', 'c'}
+ Memmapping mode for numpy arrays passed to workers.
+ See 'max_nbytes' parameter documentation for more details.
+ forward_reducers: dictionary, optional
+ Reducers used to pickle objects passed from master to worker
+ processes: see below.
+ backward_reducers: dictionary, optional
+ Reducers used to pickle return values from workers back to the
+ master process.
+ verbose: int, optional
+ Make it possible to monitor how the communication of numpy arrays
+ with the subprocess is handled (pickling or memmapping)
+ prewarm: bool or str, optional, "auto" by default.
+ If True, force a read on newly memmapped array to make sure that OS
+ pre-cache it in memory. This can be useful to avoid concurrent disk
+ access when the same data array is passed to different worker
+ processes. If "auto" (by default), prewarm is set to True, unless the
+ Linux shared memory partition /dev/shm is available and used as temp
+ folder.
+
+ `forward_reducers` and `backward_reducers` are expected to be
+ dictionaries with key/values being `(type, callable)` pairs where
+ `callable` is a function that give an instance of `type` will return
+ a tuple `(constructor, tuple_of_objects)` to rebuild an instance out
+ of the pickled `tuple_of_objects` as would return a `__reduce__`
+ method. See the standard library documentation on pickling for more
+ details.
+
+ """
+
+ def __init__(self, processes=None, temp_folder=None, max_nbytes=1e6,
+ mmap_mode='r', forward_reducers=None, backward_reducers=None,
+ verbose=0, context_id=None, prewarm=False, **kwargs):
+
+ if context_id is not None:
+ warnings.warn('context_id is deprecated and ignored in joblib'
+ ' 0.9.4 and will be removed in 0.11',
+ DeprecationWarning)
+
+ manager = TemporaryResourcesManager(temp_folder)
+ self._temp_folder_manager = manager
+
+ # The usage of a temp_folder_resolver over a simple temp_folder is
+ # superfluous for multiprocessing pools, as they don't get reused, see
+ # get_memmapping_executor for more details. We still use it for code
+ # simplicity.
+ forward_reducers, backward_reducers = \
+ get_memmapping_reducers(
+ temp_folder_resolver=manager.resolve_temp_folder_name,
+ max_nbytes=max_nbytes, mmap_mode=mmap_mode,
+ forward_reducers=forward_reducers,
+ backward_reducers=backward_reducers, verbose=verbose,
+ unlink_on_gc_collect=False, prewarm=prewarm)
+
+ poolargs = dict(
+ processes=processes,
+ forward_reducers=forward_reducers,
+ backward_reducers=backward_reducers)
+ poolargs.update(kwargs)
+ super(MemmappingPool, self).__init__(**poolargs)
+
+ def terminate(self):
+ n_retries = 10
+ for i in range(n_retries):
+ try:
+ super(MemmappingPool, self).terminate()
+ break
+ except OSError as e:
+ if isinstance(e, WindowsError):
+ # Workaround occasional "[Error 5] Access is denied" issue
+ # when trying to terminate a process under windows.
+ sleep(0.1)
+ if i + 1 == n_retries:
+ warnings.warn("Failed to terminate worker processes in"
+ " multiprocessing pool: %r" % e)
+ self._temp_folder_manager._unlink_temporary_resources()
+
+ @property
+ def _temp_folder(self):
+ # Legacy property in tests. could be removed if we refactored the
+ # memmapping tests. SHOULD ONLY BE USED IN TESTS!
+ # We cache this property because it is called late in the tests - at
+ # this point, all context have been unregistered, and
+ # resolve_temp_folder_name raises an error.
+ if getattr(self, '_cached_temp_folder', None) is not None:
+ return self._cached_temp_folder
+ else:
+ self._cached_temp_folder = self._temp_folder_manager.resolve_temp_folder_name() # noqa
+ return self._cached_temp_folder
diff --git a/runtime/Lib/site-packages/joblib/test/__init__.py b/runtime/Lib/site-packages/joblib/test/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..401de7897c9acf0a082e453ddf5a9d9ebb39caf5
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/__init__.py
@@ -0,0 +1,2 @@
+from joblib.test import test_memory
+from joblib.test import test_hashing
diff --git a/runtime/Lib/site-packages/joblib/test/common.py b/runtime/Lib/site-packages/joblib/test/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..6187894e8449fdb320b410a1e8550b6775284a75
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/common.py
@@ -0,0 +1,114 @@
+"""
+Small utilities for testing.
+"""
+import threading
+import signal
+import time
+import os
+import sys
+import gc
+
+from joblib._multiprocessing_helpers import mp
+from joblib.testing import SkipTest, skipif
+
+try:
+ import lz4
+except ImportError:
+ lz4 = None
+
+# A decorator to run tests only when numpy is available
+try:
+ import numpy as np
+
+ def with_numpy(func):
+ """A decorator to skip tests requiring numpy."""
+ return func
+
+except ImportError:
+ def with_numpy(func):
+ """A decorator to skip tests requiring numpy."""
+ def my_func():
+ raise SkipTest('Test requires numpy')
+ return my_func
+ np = None
+
+# TODO: Turn this back on after refactoring yield based tests in test_hashing
+# with_numpy = skipif(not np, reason='Test requires numpy.')
+
+# we use memory_profiler library for memory consumption checks
+try:
+ from memory_profiler import memory_usage
+
+ def with_memory_profiler(func):
+ """A decorator to skip tests requiring memory_profiler."""
+ return func
+
+ def memory_used(func, *args, **kwargs):
+ """Compute memory usage when executing func."""
+ gc.collect()
+ mem_use = memory_usage((func, args, kwargs), interval=.001)
+ return max(mem_use) - min(mem_use)
+
+except ImportError:
+ def with_memory_profiler(func):
+ """A decorator to skip tests requiring memory_profiler."""
+ def dummy_func():
+ raise SkipTest('Test requires memory_profiler.')
+ return dummy_func
+
+ memory_usage = memory_used = None
+
+# A utility to kill the test runner in case a multiprocessing assumption
+# triggers an infinite wait on a pipe by the master process for one of its
+# failed workers
+
+_KILLER_THREADS = dict()
+
+
+def setup_autokill(module_name, timeout=30):
+ """Timeout based suiciding thread to kill the test runner process
+
+ If some subprocess dies in an unexpected way we don't want the
+ parent process to block indefinitely.
+ """
+ if "NO_AUTOKILL" in os.environ or "--pdb" in sys.argv:
+ # Do not install the autokiller
+ return
+
+ # Renew any previous contract under that name by first cancelling the
+ # previous version (that should normally not happen in practice)
+ teardown_autokill(module_name)
+
+ def autokill():
+ pid = os.getpid()
+ print("Timeout exceeded: terminating stalled process: %d" % pid)
+ os.kill(pid, signal.SIGTERM)
+
+ # If were are still there ask the OS to kill ourself for real
+ time.sleep(0.5)
+ print("Timeout exceeded: killing stalled process: %d" % pid)
+ os.kill(pid, signal.SIGKILL)
+
+ _KILLER_THREADS[module_name] = t = threading.Timer(timeout, autokill)
+ t.start()
+
+
+def teardown_autokill(module_name):
+ """Cancel a previously started killer thread"""
+ killer = _KILLER_THREADS.get(module_name)
+ if killer is not None:
+ killer.cancel()
+
+
+with_multiprocessing = skipif(
+ mp is None, reason='Needs multiprocessing to run.')
+
+
+with_dev_shm = skipif(
+ not os.path.exists('/dev/shm'),
+ reason='This test requires a large /dev/shm shared memory fs.')
+
+with_lz4 = skipif(lz4 is None, reason='Needs lz4 compression to run')
+
+without_lz4 = skipif(
+ lz4 is not None, reason='Needs lz4 not being installed to run')
diff --git a/runtime/Lib/site-packages/joblib/test/data/__init__.py b/runtime/Lib/site-packages/joblib/test/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/runtime/Lib/site-packages/joblib/test/data/create_numpy_pickle.py b/runtime/Lib/site-packages/joblib/test/data/create_numpy_pickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3a311fee90bde907091a816bb5a4247562ffde
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/data/create_numpy_pickle.py
@@ -0,0 +1,94 @@
+"""
+This script is used to generate test data for joblib/test/test_numpy_pickle.py
+"""
+
+import sys
+import re
+
+# pytest needs to be able to import this module even when numpy is
+# not installed
+try:
+ import numpy as np
+except ImportError:
+ np = None
+
+import joblib
+
+
+def get_joblib_version(joblib_version=joblib.__version__):
+ """Normalize joblib version by removing suffix.
+
+ >>> get_joblib_version('0.8.4')
+ '0.8.4'
+ >>> get_joblib_version('0.8.4b1')
+ '0.8.4'
+ >>> get_joblib_version('0.9.dev0')
+ '0.9'
+ """
+ matches = [re.match(r'(\d+).*', each)
+ for each in joblib_version.split('.')]
+ return '.'.join([m.group(1) for m in matches if m is not None])
+
+
+def write_test_pickle(to_pickle, args):
+ kwargs = {}
+ compress = args.compress
+ method = args.method
+ joblib_version = get_joblib_version()
+ py_version = '{0[0]}{0[1]}'.format(sys.version_info)
+ numpy_version = ''.join(np.__version__.split('.')[:2])
+
+ # The game here is to generate the right filename according to the options.
+ body = '_compressed' if (compress and method == 'zlib') else ''
+ if compress:
+ if method == 'zlib':
+ kwargs['compress'] = True
+ extension = '.gz'
+ else:
+ kwargs['compress'] = (method, 3)
+ extension = '.pkl.{}'.format(method)
+ if args.cache_size:
+ kwargs['cache_size'] = 0
+ body += '_cache_size'
+ else:
+ extension = '.pkl'
+
+ pickle_filename = 'joblib_{}{}_pickle_py{}_np{}{}'.format(
+ joblib_version, body, py_version, numpy_version, extension)
+
+ try:
+ joblib.dump(to_pickle, pickle_filename, **kwargs)
+ except Exception as e:
+ # With old python version (=< 3.3.), we can arrive there when
+ # dumping compressed pickle with LzmaFile.
+ print("Error: cannot generate file '{}' with arguments '{}'. "
+ "Error was: {}".format(pickle_filename, kwargs, e))
+ else:
+ print("File '{}' generated successfully.".format(pickle_filename))
+
+if __name__ == '__main__':
+ import argparse
+ parser = argparse.ArgumentParser(description="Joblib pickle data "
+ "generator.")
+ parser.add_argument('--cache_size', action="store_true",
+ help="Force creation of companion numpy "
+ "files for pickled arrays.")
+ parser.add_argument('--compress', action="store_true",
+ help="Generate compress pickles.")
+ parser.add_argument('--method', type=str, default='zlib',
+ choices=['zlib', 'gzip', 'bz2', 'xz', 'lzma', 'lz4'],
+ help="Set compression method.")
+ # We need to be specific about dtypes in particular endianness
+ # because the pickles can be generated on one architecture and
+ # the tests run on another one. See
+ # https://github.com/joblib/joblib/issues/279.
+ to_pickle = [np.arange(5, dtype=np.dtype(' 10
+
+
+def random2():
+ return random()
+
+
+def test_dont_assume_function_purity(loop):
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client: # noqa: F841
+ with parallel_backend('dask') as (ba, _):
+ x, y = Parallel()(delayed(random2)() for i in range(2))
+ assert x != y
+
+
+@pytest.mark.parametrize("mixed", [True, False])
+def test_dask_funcname(loop, mixed):
+ from joblib._dask import Batch
+ if not mixed:
+ tasks = [delayed(inc)(i) for i in range(4)]
+ batch_repr = 'batch_of_inc_4_calls'
+ else:
+ tasks = [
+ delayed(abs)(i) if i % 2 else delayed(inc)(i) for i in range(4)
+ ]
+ batch_repr = 'mixed_batch_of_inc_4_calls'
+
+ assert repr(Batch(tasks)) == batch_repr
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client:
+ with parallel_backend('dask') as (ba, _):
+ _ = Parallel(batch_size=2, pre_dispatch='all')(tasks)
+
+ def f(dask_scheduler):
+ return list(dask_scheduler.transition_log)
+ batch_repr = batch_repr.replace('4', '2')
+ log = client.run_on_scheduler(f)
+ assert all('batch_of_inc' in tup[0] for tup in log)
+
+
+def test_no_undesired_distributed_cache_hit(loop):
+ # Dask has a pickle cache for callables that are called many times. Because
+ # the dask backends used to wrap both the functions and the arguments
+ # under instances of the Batch callable class this caching mechanism could
+ # lead to bugs as described in: https://github.com/joblib/joblib/pull/1055
+ # The joblib-dask backend has been refactored to avoid bundling the
+ # arguments as an attribute of the Batch instance to avoid this problem.
+ # This test serves as non-regression problem.
+
+ # Use a large number of input arguments to give the AutoBatchingMixin
+ # enough tasks to kick-in.
+ lists = [[] for _ in range(100)]
+ np = pytest.importorskip('numpy')
+ X = np.arange(int(1e6))
+
+ def isolated_operation(list_, data=None):
+ if data is not None:
+ np.testing.assert_array_equal(data, X)
+ list_.append(uuid4().hex)
+ return list_
+
+ cluster = LocalCluster(n_workers=1, threads_per_worker=2)
+ client = Client(cluster)
+ try:
+ with parallel_backend('dask') as (ba, _):
+ # dispatches joblib.parallel.BatchedCalls
+ res = Parallel()(
+ delayed(isolated_operation)(list_) for list_ in lists
+ )
+
+ # The original arguments should not have been mutated as the mutation
+ # happens in the dask worker process.
+ assert lists == [[] for _ in range(100)]
+
+ # Here we did not pass any large numpy array as argument to
+ # isolated_operation so no scattering event should happen under the
+ # hood.
+ counts = count_events('receive-from-scatter', client)
+ assert sum(counts.values()) == 0
+ assert all([len(r) == 1 for r in res])
+
+ with parallel_backend('dask') as (ba, _):
+ # Append a large array which will be scattered by dask, and
+ # dispatch joblib._dask.Batch
+ res = Parallel()(
+ delayed(isolated_operation)(list_, data=X) for list_ in lists
+ )
+
+ # This time, auto-scattering should have kicked it.
+ counts = count_events('receive-from-scatter', client)
+ assert sum(counts.values()) > 0
+ assert all([len(r) == 1 for r in res])
+ finally:
+ client.close()
+ cluster.close()
+
+
+class CountSerialized(object):
+ def __init__(self, x):
+ self.x = x
+ self.count = 0
+
+ def __add__(self, other):
+ return self.x + getattr(other, 'x', other)
+
+ __radd__ = __add__
+
+ def __reduce__(self):
+ self.count += 1
+ return (CountSerialized, (self.x,))
+
+
+def add5(a, b, c, d=0, e=0):
+ return a + b + c + d + e
+
+
+def test_manual_scatter(loop):
+ x = CountSerialized(1)
+ y = CountSerialized(2)
+ z = CountSerialized(3)
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client: # noqa: F841
+ with parallel_backend('dask', scatter=[x, y]) as (ba, _):
+ f = delayed(add5)
+ tasks = [f(x, y, z, d=4, e=5),
+ f(x, z, y, d=5, e=4),
+ f(y, x, z, d=x, e=5),
+ f(z, z, x, d=z, e=y)]
+ expected = [func(*args, **kwargs)
+ for func, args, kwargs in tasks]
+ results = Parallel()(tasks)
+
+ # Scatter must take a list/tuple
+ with pytest.raises(TypeError):
+ with parallel_backend('dask', loop=loop, scatter=1):
+ pass
+
+ assert results == expected
+
+ # Scattered variables only serialized once
+ assert x.count == 1
+ assert y.count == 1
+ # Depending on the version of distributed, the unscattered z variable
+ # is either pickled 4 or 6 times, possibly because of the memoization
+ # of objects that appear several times in the arguments of a delayed
+ # task.
+ assert z.count in (4, 6)
+
+
+# When the same IOLoop is used for multiple clients in a row, use
+# loop_in_thread instead of loop to prevent the Client from closing it. See
+# dask/distributed #4112
+def test_auto_scatter(loop_in_thread):
+ np = pytest.importorskip('numpy')
+ data1 = np.ones(int(1e4), dtype=np.uint8)
+ data2 = np.ones(int(1e4), dtype=np.uint8)
+ data_to_process = ([data1] * 3) + ([data2] * 3)
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop_in_thread) as client:
+ with parallel_backend('dask') as (ba, _):
+ # Passing the same data as arg and kwarg triggers a single
+ # scatter operation whose result is reused.
+ Parallel()(delayed(noop)(data, data, i, opt=data)
+ for i, data in enumerate(data_to_process))
+ # By default large array are automatically scattered with
+ # broadcast=1 which means that one worker must directly receive
+ # the data from the scatter operation once.
+ counts = count_events('receive-from-scatter', client)
+ assert counts[a['address']] + counts[b['address']] == 2
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop_in_thread) as client:
+ with parallel_backend('dask') as (ba, _):
+ Parallel()(delayed(noop)(data1[:3], i) for i in range(5))
+ # Small arrays are passed within the task definition without going
+ # through a scatter operation.
+ counts = count_events('receive-from-scatter', client)
+ assert counts[a['address']] == 0
+ assert counts[b['address']] == 0
+
+
+@pytest.mark.parametrize("retry_no", list(range(2)))
+def test_nested_scatter(loop, retry_no):
+
+ np = pytest.importorskip('numpy')
+
+ NUM_INNER_TASKS = 10
+ NUM_OUTER_TASKS = 10
+
+ def my_sum(x, i, j):
+ return np.sum(x)
+
+ def outer_function_joblib(array, i):
+ client = get_client() # noqa
+ with parallel_backend("dask"):
+ results = Parallel()(
+ delayed(my_sum)(array[j:], i, j) for j in range(
+ NUM_INNER_TASKS)
+ )
+ return sum(results)
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as _:
+ with parallel_backend("dask"):
+ my_array = np.ones(10000)
+ _ = Parallel()(
+ delayed(outer_function_joblib)(
+ my_array[i:], i) for i in range(NUM_OUTER_TASKS)
+ )
+
+
+def test_nested_backend_context_manager(loop_in_thread):
+ def get_nested_pids():
+ pids = set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2)))
+ pids |= set(Parallel(n_jobs=2)(delayed(os.getpid)() for _ in range(2)))
+ return pids
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop_in_thread) as client:
+ with parallel_backend('dask') as (ba, _):
+ pid_groups = Parallel(n_jobs=2)(
+ delayed(get_nested_pids)()
+ for _ in range(10)
+ )
+ for pid_group in pid_groups:
+ assert len(set(pid_group)) <= 2
+
+ # No deadlocks
+ with Client(s['address'], loop=loop_in_thread) as client: # noqa: F841
+ with parallel_backend('dask') as (ba, _):
+ pid_groups = Parallel(n_jobs=2)(
+ delayed(get_nested_pids)()
+ for _ in range(10)
+ )
+ for pid_group in pid_groups:
+ assert len(set(pid_group)) <= 2
+
+
+def test_nested_backend_context_manager_implicit_n_jobs(loop):
+ # Check that Parallel with no explicit n_jobs value automatically selects
+ # all the dask workers, including in nested calls.
+
+ def _backend_type(p):
+ return p._backend.__class__.__name__
+
+ def get_nested_implicit_n_jobs():
+ with Parallel() as p:
+ return _backend_type(p), p.n_jobs
+
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client: # noqa: F841
+ with parallel_backend('dask') as (ba, _):
+ with Parallel() as p:
+ assert _backend_type(p) == "DaskDistributedBackend"
+ assert p.n_jobs == -1
+ all_nested_n_jobs = p(
+ delayed(get_nested_implicit_n_jobs)()
+ for _ in range(2)
+ )
+ for backend_type, nested_n_jobs in all_nested_n_jobs:
+ assert backend_type == "DaskDistributedBackend"
+ assert nested_n_jobs == -1
+
+
+def test_errors(loop):
+ with pytest.raises(ValueError) as info:
+ with parallel_backend('dask'):
+ pass
+
+ assert "create a dask client" in str(info.value).lower()
+
+
+def test_correct_nested_backend(loop):
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client: # noqa: F841
+ # No requirement, should be us
+ with parallel_backend('dask') as (ba, _):
+ result = Parallel(n_jobs=2)(
+ delayed(outer)(nested_require=None) for _ in range(1))
+ assert isinstance(result[0][0][0], DaskDistributedBackend)
+
+ # Require threads, should be threading
+ with parallel_backend('dask') as (ba, _):
+ result = Parallel(n_jobs=2)(
+ delayed(outer)(nested_require='sharedmem')
+ for _ in range(1))
+ assert isinstance(result[0][0][0], ThreadingBackend)
+
+
+def outer(nested_require):
+ return Parallel(n_jobs=2, prefer='threads')(
+ delayed(middle)(nested_require) for _ in range(1)
+ )
+
+
+def middle(require):
+ return Parallel(n_jobs=2, require=require)(
+ delayed(inner)() for _ in range(1)
+ )
+
+
+def inner():
+ return Parallel()._backend
+
+
+def test_secede_with_no_processes(loop):
+ # https://github.com/dask/distributed/issues/1775
+ with Client(loop=loop, processes=False, set_as_default=True):
+ with parallel_backend('dask'):
+ Parallel(n_jobs=4)(delayed(id)(i) for i in range(2))
+
+
+def _worker_address(_):
+ from distributed import get_worker
+ return get_worker().address
+
+
+def test_dask_backend_keywords(loop):
+ with cluster() as (s, [a, b]):
+ with Client(s['address'], loop=loop) as client: # noqa: F841
+ with parallel_backend('dask', workers=a['address']) as (ba, _):
+ seq = Parallel()(
+ delayed(_worker_address)(i) for i in range(10))
+ assert seq == [a['address']] * 10
+
+ with parallel_backend('dask', workers=b['address']) as (ba, _):
+ seq = Parallel()(
+ delayed(_worker_address)(i) for i in range(10))
+ assert seq == [b['address']] * 10
+
+
+def test_cleanup(loop):
+ with Client(processes=False, loop=loop) as client:
+ with parallel_backend('dask'):
+ Parallel()(delayed(inc)(i) for i in range(10))
+
+ start = time()
+ while client.cluster.scheduler.tasks:
+ sleep(0.01)
+ assert time() < start + 5
+
+ assert not client.futures
+
+
+@pytest.mark.parametrize("cluster_strategy", ["adaptive", "late_scaling"])
+@pytest.mark.skipif(
+ distributed.__version__ <= '2.1.1' and distributed.__version__ >= '1.28.0',
+ reason="distributed bug - https://github.com/dask/distributed/pull/2841")
+def test_wait_for_workers(cluster_strategy):
+ cluster = LocalCluster(n_workers=0, processes=False, threads_per_worker=2)
+ client = Client(cluster)
+ if cluster_strategy == "adaptive":
+ cluster.adapt(minimum=0, maximum=2)
+ elif cluster_strategy == "late_scaling":
+ # Tell the cluster to start workers but this is a non-blocking call
+ # and new workers might take time to connect. In this case the Parallel
+ # call should wait for at least one worker to come up before starting
+ # to schedule work.
+ cluster.scale(2)
+ try:
+ with parallel_backend('dask'):
+ # The following should wait a bit for at least one worker to
+ # become available.
+ Parallel()(delayed(inc)(i) for i in range(10))
+ finally:
+ client.close()
+ cluster.close()
+
+
+def test_wait_for_workers_timeout():
+ # Start a cluster with 0 worker:
+ cluster = LocalCluster(n_workers=0, processes=False, threads_per_worker=2)
+ client = Client(cluster)
+ try:
+ with parallel_backend('dask', wait_for_workers_timeout=0.1):
+ # Short timeout: DaskDistributedBackend
+ msg = "DaskDistributedBackend has no worker after 0.1 seconds."
+ with pytest.raises(TimeoutError, match=msg):
+ Parallel()(delayed(inc)(i) for i in range(10))
+
+ with parallel_backend('dask', wait_for_workers_timeout=0):
+ # No timeout: fallback to generic joblib failure:
+ msg = "DaskDistributedBackend has no active worker"
+ with pytest.raises(RuntimeError, match=msg):
+ Parallel()(delayed(inc)(i) for i in range(10))
+ finally:
+ client.close()
+ cluster.close()
+
+
+@pytest.mark.parametrize("backend", ["loky", "multiprocessing"])
+def test_joblib_warning_inside_dask_daemonic_worker(backend):
+ cluster = LocalCluster(n_workers=2)
+ client = Client(cluster)
+
+ def func_using_joblib_parallel():
+ # Somehow trying to check the warning type here (e.g. with
+ # pytest.warns(UserWarning)) make the test hang. Work-around: return
+ # the warning record to the client and the warning check is done
+ # client-side.
+ with warnings.catch_warnings(record=True) as record:
+ Parallel(n_jobs=2, backend=backend)(
+ delayed(inc)(i) for i in range(10))
+
+ return record
+
+ fut = client.submit(func_using_joblib_parallel)
+ record = fut.result()
+
+ assert len(record) == 1
+ warning = record[0].message
+ assert isinstance(warning, UserWarning)
+ assert "distributed.worker.daemon" in str(warning)
diff --git a/runtime/Lib/site-packages/joblib/test/test_deprecated_objects.py b/runtime/Lib/site-packages/joblib/test/test_deprecated_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ca6b0882765aa6481211833f45c13427fa0ff61
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_deprecated_objects.py
@@ -0,0 +1,27 @@
+"""
+Tests making sure that deprecated objects properly raise a deprecation warning
+when imported/created.
+"""
+import pytest
+
+from joblib.my_exceptions import _deprecated_names as _deprecated_exceptions
+from joblib.format_stack import _deprecated_names as _deprecated_format_utils
+
+
+def test_deprecated_joblib_exceptions():
+ assert 'JoblibException' in _deprecated_exceptions
+ for name in _deprecated_exceptions:
+ msg = ('{} is deprecated and will be removed from joblib in '
+ '0.16'.format(name))
+ with pytest.warns(DeprecationWarning, match=msg):
+ exec('from joblib.my_exceptions import {}'.format(name))
+
+
+def test_deprecated_formatting_utilities(capsys):
+ assert 'safe_repr' in _deprecated_format_utils
+ assert 'eq_repr' in _deprecated_format_utils
+ for name in _deprecated_format_utils:
+ msg = ('{} is deprecated and will be removed from joblib in '
+ '0.16'.format(name))
+ with pytest.warns(DeprecationWarning, match=msg):
+ exec('from joblib.format_stack import {}'.format(name))
diff --git a/runtime/Lib/site-packages/joblib/test/test_disk.py b/runtime/Lib/site-packages/joblib/test/test_disk.py
new file mode 100644
index 0000000000000000000000000000000000000000..b825a8b3a5c18a3114f34ed9d7c90cce62799085
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_disk.py
@@ -0,0 +1,71 @@
+"""
+Unit tests for the disk utilities.
+"""
+
+# Authors: Gael Varoquaux
+# Lars Buitinck
+# Copyright (c) 2010 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+from __future__ import with_statement
+import array
+import os
+
+from joblib.disk import disk_used, memstr_to_bytes, mkdirp, rm_subdirs
+from joblib.testing import parametrize, raises
+
+###############################################################################
+
+
+def test_disk_used(tmpdir):
+ cachedir = tmpdir.strpath
+ # Not write a file that is 1M big in this directory, and check the
+ # size. The reason we use such a big file is that it makes us robust
+ # to errors due to block allocation.
+ a = array.array('i')
+ sizeof_i = a.itemsize
+ target_size = 1024
+ n = int(target_size * 1024 / sizeof_i)
+ a = array.array('i', n * (1,))
+ with open(os.path.join(cachedir, 'test'), 'wb') as output:
+ a.tofile(output)
+ assert disk_used(cachedir) >= target_size
+ assert disk_used(cachedir) < target_size + 12
+
+
+@parametrize('text,value',
+ [('80G', 80 * 1024 ** 3),
+ ('1.4M', int(1.4 * 1024 ** 2)),
+ ('120M', 120 * 1024 ** 2),
+ ('53K', 53 * 1024)])
+def test_memstr_to_bytes(text, value):
+ assert memstr_to_bytes(text) == value
+
+
+@parametrize('text,exception,regex',
+ [('fooG', ValueError, r'Invalid literal for size.*fooG.*'),
+ ('1.4N', ValueError, r'Invalid literal for size.*1.4N.*')])
+def test_memstr_to_bytes_exception(text, exception, regex):
+ with raises(exception) as excinfo:
+ memstr_to_bytes(text)
+ assert excinfo.match(regex)
+
+
+def test_mkdirp(tmpdir):
+ mkdirp(os.path.join(tmpdir.strpath, 'ham'))
+ mkdirp(os.path.join(tmpdir.strpath, 'ham'))
+ mkdirp(os.path.join(tmpdir.strpath, 'spam', 'spam'))
+
+ # Not all OSErrors are ignored
+ with raises(OSError):
+ mkdirp('')
+
+
+def test_rm_subdirs(tmpdir):
+ sub_path = os.path.join(tmpdir.strpath, "am", "stram")
+ full_path = os.path.join(sub_path, "gram")
+ mkdirp(os.path.join(full_path))
+
+ rm_subdirs(sub_path)
+ assert os.path.exists(sub_path)
+ assert not os.path.exists(full_path)
diff --git a/runtime/Lib/site-packages/joblib/test/test_format_stack.py b/runtime/Lib/site-packages/joblib/test/test_format_stack.py
new file mode 100644
index 0000000000000000000000000000000000000000..09fa26a7f7070546d87941548c608ded8e873e34
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_format_stack.py
@@ -0,0 +1,129 @@
+"""
+Unit tests for the stack formatting utilities
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2010 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import imp
+import os
+import re
+import sys
+import pytest
+
+from joblib.format_stack import safe_repr, _fixed_getframes, format_records
+from joblib.format_stack import format_exc
+from joblib.test.common import with_numpy, np
+
+###############################################################################
+
+
+class Vicious(object):
+ def __repr__(self):
+ raise ValueError
+
+
+def test_safe_repr():
+ safe_repr(Vicious())
+
+
+def _change_file_extensions_to_pyc(record):
+ _1, filename, _2, _3, _4, _5 = record
+ if filename.endswith('.py'):
+ filename += 'c'
+ return _1, filename, _2, _3, _4, _5
+
+
+def _raise_exception(a, b):
+ """Function that raises with a non trivial call stack
+ """
+ def helper(a, b):
+ raise ValueError('Nope, this can not work')
+
+ helper(a, b)
+
+
+def test_format_records():
+ try:
+ _raise_exception('a', 42)
+ except ValueError:
+ etb = sys.exc_info()[2]
+ records = _fixed_getframes(etb)
+
+ # Modify filenames in traceback records from .py to .pyc
+ pyc_records = [_change_file_extensions_to_pyc(record)
+ for record in records]
+
+ formatted_records = format_records(pyc_records)
+
+ # Check that the .py file and not the .pyc one is listed in
+ # the traceback
+ for fmt_rec in formatted_records:
+ assert 'test_format_stack.py in' in fmt_rec
+
+ # Check exception stack
+ arrow_regex = r'^-+>\s+\d+\s+'
+ assert re.search(arrow_regex + r"_raise_exception\('a', 42\)",
+ formatted_records[0],
+ re.MULTILINE)
+ assert re.search(arrow_regex + r'helper\(a, b\)',
+ formatted_records[1],
+ re.MULTILINE)
+ assert "a = 'a'" in formatted_records[1]
+ assert 'b = 42' in formatted_records[1]
+ assert re.search(arrow_regex +
+ r"raise ValueError\('Nope, this can not work'\)",
+ formatted_records[2],
+ re.MULTILINE)
+
+
+def test_format_records_file_with_less_lines_than_context(tmpdir):
+ # See https://github.com/joblib/joblib/issues/420
+ filename = os.path.join(tmpdir.strpath, 'small_file.py')
+ code_lines = ['def func():', ' 1/0']
+ code = '\n'.join(code_lines)
+ with open(filename, 'w') as f:
+ f.write(code)
+
+ small_file = imp.load_source('small_file', filename)
+ if not hasattr(small_file, 'func'):
+ pytest.skip("PyPy bug?")
+ try:
+ small_file.func()
+ except ZeroDivisionError:
+ etb = sys.exc_info()[2]
+
+ records = _fixed_getframes(etb, context=10)
+ # Check that if context is bigger than the number of lines in
+ # the file you do not get padding
+ frame, tb_filename, line, func_name, context, _ = records[-1]
+ assert [l.rstrip() for l in context] == code_lines
+
+ formatted_records = format_records(records)
+ # 2 lines for header in the traceback: lines of ...... +
+ # filename with function
+ len_header = 2
+ nb_lines_formatted_records = len(formatted_records[1].splitlines())
+ assert (nb_lines_formatted_records == len_header + len(code_lines))
+ # Check exception stack
+ arrow_regex = r'^-+>\s+\d+\s+'
+ assert re.search(arrow_regex + r'1/0',
+ formatted_records[1],
+ re.MULTILINE)
+
+
+@with_numpy
+def test_format_exc_with_compiled_code():
+ # Trying to tokenize compiled C code raise SyntaxError.
+ # See https://github.com/joblib/joblib/issues/101 for more details.
+ try:
+ np.random.uniform('invalid_value')
+ except Exception:
+ exc_type, exc_value, exc_traceback = sys.exc_info()
+ formatted_exc = format_exc(exc_type, exc_value,
+ exc_traceback, context=10)
+ # The name of the extension can be something like
+ # mtrand.cpython-33m.so
+ pattern = r'mtrand[a-z0-9._-]*\.(so|pyd)'
+ assert re.search(pattern, formatted_exc)
diff --git a/runtime/Lib/site-packages/joblib/test/test_func_inspect.py b/runtime/Lib/site-packages/joblib/test/test_func_inspect.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3b7b7b386a97c79055b63c4b215b901247faee9
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_func_inspect.py
@@ -0,0 +1,290 @@
+"""
+Test the func_inspect module.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import functools
+
+from joblib.func_inspect import filter_args, get_func_name, get_func_code
+from joblib.func_inspect import _clean_win_chars, format_signature
+from joblib.memory import Memory
+from joblib.test.common import with_numpy
+from joblib.testing import fixture, parametrize, raises
+
+
+###############################################################################
+# Module-level functions and fixture, for tests
+def f(x, y=0):
+ pass
+
+
+def g(x):
+ pass
+
+
+def h(x, y=0, *args, **kwargs):
+ pass
+
+
+def i(x=1):
+ pass
+
+
+def j(x, y, **kwargs):
+ pass
+
+
+def k(*args, **kwargs):
+ pass
+
+
+def m1(x, *, y):
+ pass
+
+
+def m2(x, *, y, z=3):
+ pass
+
+
+@fixture(scope='module')
+def cached_func(tmpdir_factory):
+ # Create a Memory object to test decorated functions.
+ # We should be careful not to call the decorated functions, so that
+ # cache directories are not created in the temp dir.
+ cachedir = tmpdir_factory.mktemp("joblib_test_func_inspect")
+ mem = Memory(cachedir.strpath)
+
+ @mem.cache
+ def cached_func_inner(x):
+ return x
+
+ return cached_func_inner
+
+
+class Klass(object):
+
+ def f(self, x):
+ return x
+
+
+###############################################################################
+# Tests
+
+@parametrize('func,args,filtered_args',
+ [(f, [[], (1, )], {'x': 1, 'y': 0}),
+ (f, [['x'], (1, )], {'y': 0}),
+ (f, [['y'], (0, )], {'x': 0}),
+ (f, [['y'], (0, ), {'y': 1}], {'x': 0}),
+ (f, [['x', 'y'], (0, )], {}),
+ (f, [[], (0,), {'y': 1}], {'x': 0, 'y': 1}),
+ (f, [['y'], (), {'x': 2, 'y': 1}], {'x': 2}),
+ (g, [[], (), {'x': 1}], {'x': 1}),
+ (i, [[], (2, )], {'x': 2})])
+def test_filter_args(func, args, filtered_args):
+ assert filter_args(func, *args) == filtered_args
+
+
+def test_filter_args_method():
+ obj = Klass()
+ assert filter_args(obj.f, [], (1, )) == {'x': 1, 'self': obj}
+
+
+@parametrize('func,args,filtered_args',
+ [(h, [[], (1, )],
+ {'x': 1, 'y': 0, '*': [], '**': {}}),
+ (h, [[], (1, 2, 3, 4)],
+ {'x': 1, 'y': 2, '*': [3, 4], '**': {}}),
+ (h, [[], (1, 25), {'ee': 2}],
+ {'x': 1, 'y': 25, '*': [], '**': {'ee': 2}}),
+ (h, [['*'], (1, 2, 25), {'ee': 2}],
+ {'x': 1, 'y': 2, '**': {'ee': 2}})])
+def test_filter_varargs(func, args, filtered_args):
+ assert filter_args(func, *args) == filtered_args
+
+
+test_filter_kwargs_extra_params = [
+ (m1, [[], (1,), {'y': 2}], {'x': 1, 'y': 2}),
+ (m2, [[], (1,), {'y': 2}], {'x': 1, 'y': 2, 'z': 3})
+]
+
+
+@parametrize('func,args,filtered_args',
+ [(k, [[], (1, 2), {'ee': 2}],
+ {'*': [1, 2], '**': {'ee': 2}}),
+ (k, [[], (3, 4)],
+ {'*': [3, 4], '**': {}})] +
+ test_filter_kwargs_extra_params)
+def test_filter_kwargs(func, args, filtered_args):
+ assert filter_args(func, *args) == filtered_args
+
+
+def test_filter_args_2():
+ assert (filter_args(j, [], (1, 2), {'ee': 2}) ==
+ {'x': 1, 'y': 2, '**': {'ee': 2}})
+
+ ff = functools.partial(f, 1)
+ # filter_args has to special-case partial
+ assert filter_args(ff, [], (1, )) == {'*': [1], '**': {}}
+ assert filter_args(ff, ['y'], (1, )) == {'*': [1], '**': {}}
+
+
+@parametrize('func,funcname', [(f, 'f'), (g, 'g'),
+ (cached_func, 'cached_func')])
+def test_func_name(func, funcname):
+ # Check that we are not confused by decoration
+ # here testcase 'cached_func' is the function itself
+ assert get_func_name(func)[1] == funcname
+
+
+def test_func_name_on_inner_func(cached_func):
+ # Check that we are not confused by decoration
+ # here testcase 'cached_func' is the 'cached_func_inner' function
+ # returned by 'cached_func' fixture
+ assert get_func_name(cached_func)[1] == 'cached_func_inner'
+
+
+def test_func_inspect_errors():
+ # Check that func_inspect is robust and will work on weird objects
+ assert get_func_name('a'.lower)[-1] == 'lower'
+ assert get_func_code('a'.lower)[1:] == (None, -1)
+ ff = lambda x: x
+ assert get_func_name(ff, win_characters=False)[-1] == ''
+ assert get_func_code(ff)[1] == __file__.replace('.pyc', '.py')
+ # Simulate a function defined in __main__
+ ff.__module__ = '__main__'
+ assert get_func_name(ff, win_characters=False)[-1] == ''
+ assert get_func_code(ff)[1] == __file__.replace('.pyc', '.py')
+
+
+def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'):
+ pass
+
+
+def func_with_signature(a: int, b: int) -> None:
+ pass
+
+
+def test_filter_args_edge_cases():
+ assert (
+ filter_args(func_with_kwonly_args, [], (1, 2),
+ {'kw1': 3, 'kw2': 4}) ==
+ {'a': 1, 'b': 2, 'kw1': 3, 'kw2': 4})
+
+ # filter_args doesn't care about keyword-only arguments so you
+ # can pass 'kw1' into *args without any problem
+ with raises(ValueError) as excinfo:
+ filter_args(func_with_kwonly_args, [], (1, 2, 3), {'kw2': 2})
+ excinfo.match("Keyword-only parameter 'kw1' was passed as positional "
+ "parameter")
+
+ assert (
+ filter_args(func_with_kwonly_args, ['b', 'kw2'], (1, 2),
+ {'kw1': 3, 'kw2': 4}) ==
+ {'a': 1, 'kw1': 3})
+
+ assert (filter_args(func_with_signature, ['b'], (1, 2)) == {'a': 1})
+
+
+def test_bound_methods():
+ """ Make sure that calling the same method on two different instances
+ of the same class does resolv to different signatures.
+ """
+ a = Klass()
+ b = Klass()
+ assert filter_args(a.f, [], (1, )) != filter_args(b.f, [], (1, ))
+
+
+@parametrize('exception,regex,func,args',
+ [(ValueError, 'ignore_lst must be a list of parameters to ignore',
+ f, ['bar', (None, )]),
+ (ValueError, r'Ignore list: argument \'(.*)\' is not defined',
+ g, [['bar'], (None, )]),
+ (ValueError, 'Wrong number of arguments',
+ h, [[]])])
+def test_filter_args_error_msg(exception, regex, func, args):
+ """ Make sure that filter_args returns decent error messages, for the
+ sake of the user.
+ """
+ with raises(exception) as excinfo:
+ filter_args(func, *args)
+ excinfo.match(regex)
+
+
+def test_filter_args_no_kwargs_mutation():
+ """None-regression test against 0.12.0 changes.
+
+ https://github.com/joblib/joblib/pull/75
+
+ Make sure filter args doesn't mutate the kwargs dict that gets passed in.
+ """
+ kwargs = {'x': 0}
+ filter_args(g, [], [], kwargs)
+ assert kwargs == {'x': 0}
+
+
+def test_clean_win_chars():
+ string = r'C:\foo\bar\main.py'
+ mangled_string = _clean_win_chars(string)
+ for char in ('\\', ':', '<', '>', '!'):
+ assert char not in mangled_string
+
+
+@parametrize('func,args,kwargs,sgn_expected',
+ [(g, [list(range(5))], {}, 'g([0, 1, 2, 3, 4])'),
+ (k, [1, 2, (3, 4)], {'y': True}, 'k(1, 2, (3, 4), y=True)')])
+def test_format_signature(func, args, kwargs, sgn_expected):
+ # Test signature formatting.
+ path, sgn_result = format_signature(func, *args, **kwargs)
+ assert sgn_result == sgn_expected
+
+
+def test_format_signature_long_arguments():
+ shortening_threshold = 1500
+ # shortening gets it down to 700 characters but there is the name
+ # of the function in the signature and a few additional things
+ # like dots for the ellipsis
+ shortening_target = 700 + 10
+
+ arg = 'a' * shortening_threshold
+ _, signature = format_signature(h, arg)
+ assert len(signature) < shortening_target
+
+ nb_args = 5
+ args = [arg for _ in range(nb_args)]
+ _, signature = format_signature(h, *args)
+ assert len(signature) < shortening_target * nb_args
+
+ kwargs = {str(i): arg for i, arg in enumerate(args)}
+ _, signature = format_signature(h, **kwargs)
+ assert len(signature) < shortening_target * nb_args
+
+ _, signature = format_signature(h, *args, **kwargs)
+ assert len(signature) < shortening_target * 2 * nb_args
+
+
+@with_numpy
+def test_format_signature_numpy():
+ """ Test the format signature formatting with numpy.
+ """
+
+
+def test_special_source_encoding():
+ from joblib.test.test_func_inspect_special_encoding import big5_f
+ func_code, source_file, first_line = get_func_code(big5_f)
+ assert first_line == 5
+ assert "def big5_f():" in func_code
+ assert "test_func_inspect_special_encoding" in source_file
+
+
+def _get_code():
+ from joblib.test.test_func_inspect_special_encoding import big5_f
+ return get_func_code(big5_f)[0]
+
+
+def test_func_code_consistency():
+ from joblib.parallel import Parallel, delayed
+ codes = Parallel(n_jobs=2)(delayed(_get_code)() for _ in range(5))
+ assert len(set(codes)) == 1
diff --git a/runtime/Lib/site-packages/joblib/test/test_func_inspect_special_encoding.py b/runtime/Lib/site-packages/joblib/test/test_func_inspect_special_encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b9fbe8b8d483a91f6d7638df2a1a824140d3cae
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_func_inspect_special_encoding.py
@@ -0,0 +1,10 @@
+# -*- coding: big5 -*-
+
+
+# Some Traditional Chinese characters: ¤@¨Ǥ¤¤å¦r²Å
+def big5_f():
+ """¥Ωó´ú¸ժº¨ç¼Æ
+ """
+ # µùÄÀ
+ return 0
+
diff --git a/runtime/Lib/site-packages/joblib/test/test_hashing.py b/runtime/Lib/site-packages/joblib/test/test_hashing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3d6316ccf0d0ef14d2da7a285f3d8e087ba95f
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_hashing.py
@@ -0,0 +1,497 @@
+"""
+Test the hashing module.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import time
+import hashlib
+import sys
+import os
+import gc
+import io
+import collections
+import itertools
+import pickle
+import random
+from concurrent.futures import ProcessPoolExecutor
+from decimal import Decimal
+import pytest
+
+from joblib.hashing import hash
+from joblib.func_inspect import filter_args
+from joblib.memory import Memory
+from joblib.testing import raises, skipif, fixture, parametrize
+from joblib.test.common import np, with_numpy
+
+
+def unicode(s):
+ return s
+
+
+###############################################################################
+# Helper functions for the tests
+def time_func(func, *args):
+ """ Time function func on *args.
+ """
+ times = list()
+ for _ in range(3):
+ t1 = time.time()
+ func(*args)
+ times.append(time.time() - t1)
+ return min(times)
+
+
+def relative_time(func1, func2, *args):
+ """ Return the relative time between func1 and func2 applied on
+ *args.
+ """
+ time_func1 = time_func(func1, *args)
+ time_func2 = time_func(func2, *args)
+ relative_diff = 0.5 * (abs(time_func1 - time_func2)
+ / (time_func1 + time_func2))
+ return relative_diff
+
+
+class Klass(object):
+
+ def f(self, x):
+ return x
+
+
+class KlassWithCachedMethod(object):
+
+ def __init__(self, cachedir):
+ mem = Memory(location=cachedir)
+ self.f = mem.cache(self.f)
+
+ def f(self, x):
+ return x
+
+
+###############################################################################
+# Tests
+
+input_list = [1, 2, 1., 2., 1 + 1j, 2. + 1j,
+ 'a', 'b',
+ (1,), (1, 1,), [1, ], [1, 1, ],
+ {1: 1}, {1: 2}, {2: 1},
+ None,
+ gc.collect,
+ [1, ].append,
+ # Next 2 sets have unorderable elements in python 3.
+ set(('a', 1)),
+ set(('a', 1, ('a', 1))),
+ # Next 2 dicts have unorderable type of keys in python 3.
+ {'a': 1, 1: 2},
+ {'a': 1, 1: 2, 'd': {'a': 1}}]
+
+
+@parametrize('obj1', input_list)
+@parametrize('obj2', input_list)
+def test_trivial_hash(obj1, obj2):
+ """Smoke test hash on various types."""
+ # Check that 2 objects have the same hash only if they are the same.
+ are_hashes_equal = hash(obj1) == hash(obj2)
+ are_objs_identical = obj1 is obj2
+ assert are_hashes_equal == are_objs_identical
+
+
+def test_hash_methods():
+ # Check that hashing instance methods works
+ a = io.StringIO(unicode('a'))
+ assert hash(a.flush) == hash(a.flush)
+ a1 = collections.deque(range(10))
+ a2 = collections.deque(range(9))
+ assert hash(a1.extend) != hash(a2.extend)
+
+
+@fixture(scope='function')
+@with_numpy
+def three_np_arrays():
+ rnd = np.random.RandomState(0)
+ arr1 = rnd.random_sample((10, 10))
+ arr2 = arr1.copy()
+ arr3 = arr2.copy()
+ arr3[0] += 1
+ return arr1, arr2, arr3
+
+
+def test_hash_numpy_arrays(three_np_arrays):
+ arr1, arr2, arr3 = three_np_arrays
+
+ for obj1, obj2 in itertools.product(three_np_arrays, repeat=2):
+ are_hashes_equal = hash(obj1) == hash(obj2)
+ are_arrays_equal = np.all(obj1 == obj2)
+ assert are_hashes_equal == are_arrays_equal
+
+ assert hash(arr1) != hash(arr1.T)
+
+
+def test_hash_numpy_dict_of_arrays(three_np_arrays):
+ arr1, arr2, arr3 = three_np_arrays
+
+ d1 = {1: arr1, 2: arr2}
+ d2 = {1: arr2, 2: arr1}
+ d3 = {1: arr2, 2: arr3}
+
+ assert hash(d1) == hash(d2)
+ assert hash(d1) != hash(d3)
+
+
+@with_numpy
+@parametrize('dtype', ['datetime64[s]', 'timedelta64[D]'])
+def test_numpy_datetime_array(dtype):
+ # memoryview is not supported for some dtypes e.g. datetime64
+ # see https://github.com/joblib/joblib/issues/188 for more details
+ a_hash = hash(np.arange(10))
+ array = np.arange(0, 10, dtype=dtype)
+ assert hash(array) != a_hash
+
+
+@with_numpy
+def test_hash_numpy_noncontiguous():
+ a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
+ order='F')[:, :1, :]
+ b = np.ascontiguousarray(a)
+ assert hash(a) != hash(b)
+
+ c = np.asfortranarray(a)
+ assert hash(a) != hash(c)
+
+
+@with_numpy
+@parametrize('coerce_mmap', [True, False])
+def test_hash_memmap(tmpdir, coerce_mmap):
+ """Check that memmap and arrays hash identically if coerce_mmap is True."""
+ filename = tmpdir.join('memmap_temp').strpath
+ try:
+ m = np.memmap(filename, shape=(10, 10), mode='w+')
+ a = np.asarray(m)
+ are_hashes_equal = (hash(a, coerce_mmap=coerce_mmap) ==
+ hash(m, coerce_mmap=coerce_mmap))
+ assert are_hashes_equal == coerce_mmap
+ finally:
+ if 'm' in locals():
+ del m
+ # Force a garbage-collection cycle, to be certain that the
+ # object is delete, and we don't run in a problem under
+ # Windows with a file handle still open.
+ gc.collect()
+
+
+@with_numpy
+@skipif(sys.platform == 'win32', reason='This test is not stable under windows'
+ ' for some reason')
+def test_hash_numpy_performance():
+ """ Check the performance of hashing numpy arrays:
+
+ In [22]: a = np.random.random(1000000)
+
+ In [23]: %timeit hashlib.md5(a).hexdigest()
+ 100 loops, best of 3: 20.7 ms per loop
+
+ In [24]: %timeit hashlib.md5(pickle.dumps(a, protocol=2)).hexdigest()
+ 1 loops, best of 3: 73.1 ms per loop
+
+ In [25]: %timeit hashlib.md5(cPickle.dumps(a, protocol=2)).hexdigest()
+ 10 loops, best of 3: 53.9 ms per loop
+
+ In [26]: %timeit hash(a)
+ 100 loops, best of 3: 20.8 ms per loop
+ """
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample(1000000)
+
+ def md5_hash(x):
+ return hashlib.md5(memoryview(x)).hexdigest()
+
+ relative_diff = relative_time(md5_hash, hash, a)
+ assert relative_diff < 0.3
+
+ # Check that hashing an tuple of 3 arrays takes approximately
+ # 3 times as much as hashing one array
+ time_hashlib = 3 * time_func(md5_hash, a)
+ time_hash = time_func(hash, (a, a, a))
+ relative_diff = 0.5 * (abs(time_hash - time_hashlib)
+ / (time_hash + time_hashlib))
+ assert relative_diff < 0.3
+
+
+def test_bound_methods_hash():
+ """ Make sure that calling the same method on two different instances
+ of the same class does resolve to the same hashes.
+ """
+ a = Klass()
+ b = Klass()
+ assert (hash(filter_args(a.f, [], (1, ))) ==
+ hash(filter_args(b.f, [], (1, ))))
+
+
+def test_bound_cached_methods_hash(tmpdir):
+ """ Make sure that calling the same _cached_ method on two different
+ instances of the same class does resolve to the same hashes.
+ """
+ a = KlassWithCachedMethod(tmpdir.strpath)
+ b = KlassWithCachedMethod(tmpdir.strpath)
+ assert (hash(filter_args(a.f.func, [], (1, ))) ==
+ hash(filter_args(b.f.func, [], (1, ))))
+
+
+@with_numpy
+def test_hash_object_dtype():
+ """ Make sure that ndarrays with dtype `object' hash correctly."""
+
+ a = np.array([np.arange(i) for i in range(6)], dtype=object)
+ b = np.array([np.arange(i) for i in range(6)], dtype=object)
+
+ assert hash(a) == hash(b)
+
+
+@with_numpy
+def test_numpy_scalar():
+ # Numpy scalars are built from compiled functions, and lead to
+ # strange pickling paths explored, that can give hash collisions
+ a = np.float64(2.0)
+ b = np.float64(3.0)
+ assert hash(a) != hash(b)
+
+
+def test_dict_hash(tmpdir):
+ # Check that dictionaries hash consistently, even though the ordering
+ # of the keys is not guaranteed
+ k = KlassWithCachedMethod(tmpdir.strpath)
+
+ d = {'#s12069__c_maps.nii.gz': [33],
+ '#s12158__c_maps.nii.gz': [33],
+ '#s12258__c_maps.nii.gz': [33],
+ '#s12277__c_maps.nii.gz': [33],
+ '#s12300__c_maps.nii.gz': [33],
+ '#s12401__c_maps.nii.gz': [33],
+ '#s12430__c_maps.nii.gz': [33],
+ '#s13817__c_maps.nii.gz': [33],
+ '#s13903__c_maps.nii.gz': [33],
+ '#s13916__c_maps.nii.gz': [33],
+ '#s13981__c_maps.nii.gz': [33],
+ '#s13982__c_maps.nii.gz': [33],
+ '#s13983__c_maps.nii.gz': [33]}
+
+ a = k.f(d)
+ b = k.f(a)
+
+ assert hash(a) == hash(b)
+
+
+def test_set_hash(tmpdir):
+ # Check that sets hash consistently, even though their ordering
+ # is not guaranteed
+ k = KlassWithCachedMethod(tmpdir.strpath)
+
+ s = set(['#s12069__c_maps.nii.gz',
+ '#s12158__c_maps.nii.gz',
+ '#s12258__c_maps.nii.gz',
+ '#s12277__c_maps.nii.gz',
+ '#s12300__c_maps.nii.gz',
+ '#s12401__c_maps.nii.gz',
+ '#s12430__c_maps.nii.gz',
+ '#s13817__c_maps.nii.gz',
+ '#s13903__c_maps.nii.gz',
+ '#s13916__c_maps.nii.gz',
+ '#s13981__c_maps.nii.gz',
+ '#s13982__c_maps.nii.gz',
+ '#s13983__c_maps.nii.gz'])
+
+ a = k.f(s)
+ b = k.f(a)
+
+ assert hash(a) == hash(b)
+
+
+def test_set_decimal_hash():
+ # Check that sets containing decimals hash consistently, even though
+ # ordering is not guaranteed
+ assert (hash(set([Decimal(0), Decimal('NaN')])) ==
+ hash(set([Decimal('NaN'), Decimal(0)])))
+
+
+def test_string():
+ # Test that we obtain the same hash for object owning several strings,
+ # whatever the past of these strings (which are immutable in Python)
+ string = 'foo'
+ a = {string: 'bar'}
+ b = {string: 'bar'}
+ c = pickle.loads(pickle.dumps(b))
+ assert hash([a, b]) == hash([a, c])
+
+
+@with_numpy
+def test_numpy_dtype_pickling():
+ # numpy dtype hashing is tricky to get right: see #231, #239, #251 #1080,
+ # #1082, and explanatory comments inside
+ # ``joblib.hashing.NumpyHasher.save``.
+
+ # In this test, we make sure that the pickling of numpy dtypes is robust to
+ # object identity and object copy.
+
+ dt1 = np.dtype('f4')
+ dt2 = np.dtype('f4')
+
+ # simple dtypes objects are interned
+ assert dt1 is dt2
+ assert hash(dt1) == hash(dt2)
+
+ dt1_roundtripped = pickle.loads(pickle.dumps(dt1))
+ assert dt1 is not dt1_roundtripped
+ assert hash(dt1) == hash(dt1_roundtripped)
+
+ assert hash([dt1, dt1]) == hash([dt1_roundtripped, dt1_roundtripped])
+ assert hash([dt1, dt1]) == hash([dt1, dt1_roundtripped])
+
+ complex_dt1 = np.dtype(
+ [('name', np.str_, 16), ('grades', np.float64, (2,))]
+ )
+ complex_dt2 = np.dtype(
+ [('name', np.str_, 16), ('grades', np.float64, (2,))]
+ )
+
+ # complex dtypes objects are not interned
+ assert hash(complex_dt1) == hash(complex_dt2)
+
+ complex_dt1_roundtripped = pickle.loads(pickle.dumps(complex_dt1))
+ assert complex_dt1_roundtripped is not complex_dt1
+ assert hash(complex_dt1) == hash(complex_dt1_roundtripped)
+
+ assert hash([complex_dt1, complex_dt1]) == hash(
+ [complex_dt1_roundtripped, complex_dt1_roundtripped]
+ )
+ assert hash([complex_dt1, complex_dt1]) == hash(
+ [complex_dt1_roundtripped, complex_dt1]
+ )
+
+
+@parametrize('to_hash,expected',
+ [('This is a string to hash',
+ '71b3f47df22cb19431d85d92d0b230b2'),
+ (u"C'est l\xe9t\xe9",
+ '2d8d189e9b2b0b2e384d93c868c0e576'),
+ ((123456, 54321, -98765),
+ 'e205227dd82250871fa25aa0ec690aa3'),
+ ([random.Random(42).random() for _ in range(5)],
+ 'a11ffad81f9682a7d901e6edc3d16c84'),
+ ({'abcde': 123, 'sadfas': [-9999, 2, 3]},
+ 'aeda150553d4bb5c69f0e69d51b0e2ef')])
+def test_hashes_stay_the_same(to_hash, expected):
+ # We want to make sure that hashes don't change with joblib
+ # version. For end users, that would mean that they have to
+ # regenerate their cache from scratch, which potentially means
+ # lengthy recomputations.
+ # Expected results have been generated with joblib 0.9.2
+ assert hash(to_hash) == expected
+
+
+@with_numpy
+def test_hashes_are_different_between_c_and_fortran_contiguous_arrays():
+ # We want to be sure that the c-contiguous and f-contiguous versions of the
+ # same array produce 2 different hashes.
+ rng = np.random.RandomState(0)
+ arr_c = rng.random_sample((10, 10))
+ arr_f = np.asfortranarray(arr_c)
+ assert hash(arr_c) != hash(arr_f)
+
+
+@with_numpy
+def test_0d_array():
+ hash(np.array(0))
+
+
+@with_numpy
+def test_0d_and_1d_array_hashing_is_different():
+ assert hash(np.array(0)) != hash(np.array([0]))
+
+
+@with_numpy
+def test_hashes_stay_the_same_with_numpy_objects():
+ # Note: joblib used to test numpy objects hashing by comparing the produced
+ # hash of an object with some hard-coded target value to guarantee that
+ # hashing remains the same across joblib versions. However, since numpy
+ # 1.20 and joblib 1.0, joblib relies on potentially unstable implementation
+ # details of numpy to hash np.dtype objects, which makes the stability of
+ # hash values across different environments hard to guarantee and to test.
+ # As a result, hashing stability across joblib versions becomes best-effort
+ # only, and we only test the consistency within a single environment by
+ # making sure:
+ # - the hash of two copies of the same objects is the same
+ # - hashing some object in two different python processes produces the same
+ # value. This should be viewed as a proxy for testing hash consistency
+ # through time between Python sessions (provided no change in the
+ # environment was done between sessions).
+
+ def create_objects_to_hash():
+ rng = np.random.RandomState(42)
+ # Being explicit about dtypes in order to avoid
+ # architecture-related differences. Also using 'f4' rather than
+ # 'f8' for float arrays because 'f8' arrays generated by
+ # rng.random.randn don't seem to be bit-identical on 32bit and
+ # 64bit machines.
+ to_hash_list = [
+ rng.randint(-1000, high=1000, size=50).astype('
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import re
+
+from joblib.logger import PrintTime
+
+
+def test_print_time(tmpdir, capsys):
+ # A simple smoke test for PrintTime.
+ logfile = tmpdir.join('test.log').strpath
+ print_time = PrintTime(logfile=logfile)
+ print_time('Foo')
+ # Create a second time, to smoke test log rotation.
+ print_time = PrintTime(logfile=logfile)
+ print_time('Foo')
+ # And a third time
+ print_time = PrintTime(logfile=logfile)
+ print_time('Foo')
+
+ out_printed_text, err_printed_text = capsys.readouterr()
+ # Use regexps to be robust to time variations
+ match = r"Foo: 0\..s, 0\..min\nFoo: 0\..s, 0..min\nFoo: " + \
+ r".\..s, 0..min\n"
+ if not re.match(match, err_printed_text):
+ raise AssertionError('Excepted %s, got %s' %
+ (match, err_printed_text))
diff --git a/runtime/Lib/site-packages/joblib/test/test_memmapping.py b/runtime/Lib/site-packages/joblib/test/test_memmapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdc825f0688029afbac2a9a59e1cc211f07c5be8
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_memmapping.py
@@ -0,0 +1,1173 @@
+import os
+import mmap
+import sys
+import platform
+import gc
+import pickle
+import itertools
+from time import sleep
+import subprocess
+import threading
+
+import pytest
+
+from joblib.test.common import with_numpy, np
+from joblib.test.common import setup_autokill
+from joblib.test.common import teardown_autokill
+from joblib.test.common import with_multiprocessing
+from joblib.test.common import with_dev_shm
+from joblib.testing import raises, parametrize, skipif, xfail, param
+from joblib.backports import make_memmap
+from joblib.parallel import Parallel, delayed
+
+from joblib.pool import MemmappingPool
+from joblib.executor import _TestingMemmappingExecutor as TestExecutor
+from joblib._memmapping_reducer import has_shareable_memory
+from joblib._memmapping_reducer import ArrayMemmapForwardReducer
+from joblib._memmapping_reducer import _strided_from_memmap
+from joblib._memmapping_reducer import _get_temp_dir
+from joblib._memmapping_reducer import _WeakArrayKeyMap
+from joblib._memmapping_reducer import _get_backing_memmap
+import joblib._memmapping_reducer as jmr
+
+
+def setup_module():
+ setup_autokill(__name__, timeout=300)
+
+
+def teardown_module():
+ teardown_autokill(__name__)
+
+
+def check_memmap_and_send_back(array):
+ assert _get_backing_memmap(array) is not None
+ return array
+
+
+def check_array(args):
+ """Dummy helper function to be executed in subprocesses
+
+ Check that the provided array has the expected values in the provided
+ range.
+
+ """
+ data, position, expected = args
+ np.testing.assert_array_equal(data[position], expected)
+
+
+def inplace_double(args):
+ """Dummy helper function to be executed in subprocesses
+
+
+ Check that the input array has the right values in the provided range
+ and perform an inplace modification to double the values in the range by
+ two.
+
+ """
+ data, position, expected = args
+ assert data[position] == expected
+ data[position] *= 2
+ np.testing.assert_array_equal(data[position], 2 * expected)
+
+
+@with_numpy
+@with_multiprocessing
+def test_memmap_based_array_reducing(tmpdir):
+ """Check that it is possible to reduce a memmap backed array"""
+ assert_array_equal = np.testing.assert_array_equal
+ filename = tmpdir.join('test.mmap').strpath
+
+ # Create a file larger than what will be used by a
+ buffer = np.memmap(filename, dtype=np.float64, shape=500, mode='w+')
+
+ # Fill the original buffer with negative markers to detect over of
+ # underflow in case of test failures
+ buffer[:] = - 1.0 * np.arange(buffer.shape[0], dtype=buffer.dtype)
+ buffer.flush()
+
+ # Memmap a 2D fortran array on a offsetted subsection of the previous
+ # buffer
+ a = np.memmap(filename, dtype=np.float64, shape=(3, 5, 4),
+ mode='r+', order='F', offset=4)
+ a[:] = np.arange(60).reshape(a.shape)
+
+ # Build various views that share the buffer with the original memmap
+
+ # b is an memmap sliced view on an memmap instance
+ b = a[1:-1, 2:-1, 2:4]
+
+ # c and d are array views
+ c = np.asarray(b)
+ d = c.T
+
+ # Array reducer with auto dumping disabled
+ reducer = ArrayMemmapForwardReducer(None, tmpdir.strpath, 'c', True)
+
+ def reconstruct_array_or_memmap(x):
+ cons, args = reducer(x)
+ return cons(*args)
+
+ # Reconstruct original memmap
+ a_reconstructed = reconstruct_array_or_memmap(a)
+ assert has_shareable_memory(a_reconstructed)
+ assert isinstance(a_reconstructed, np.memmap)
+ assert_array_equal(a_reconstructed, a)
+
+ # Reconstruct strided memmap view
+ b_reconstructed = reconstruct_array_or_memmap(b)
+ assert has_shareable_memory(b_reconstructed)
+ assert_array_equal(b_reconstructed, b)
+
+ # Reconstruct arrays views on memmap base
+ c_reconstructed = reconstruct_array_or_memmap(c)
+ assert not isinstance(c_reconstructed, np.memmap)
+ assert has_shareable_memory(c_reconstructed)
+ assert_array_equal(c_reconstructed, c)
+
+ d_reconstructed = reconstruct_array_or_memmap(d)
+ assert not isinstance(d_reconstructed, np.memmap)
+ assert has_shareable_memory(d_reconstructed)
+ assert_array_equal(d_reconstructed, d)
+
+ # Test graceful degradation on fake memmap instances with in-memory
+ # buffers
+ a3 = a * 3
+ assert not has_shareable_memory(a3)
+ a3_reconstructed = reconstruct_array_or_memmap(a3)
+ assert not has_shareable_memory(a3_reconstructed)
+ assert not isinstance(a3_reconstructed, np.memmap)
+ assert_array_equal(a3_reconstructed, a * 3)
+
+ # Test graceful degradation on arrays derived from fake memmap instances
+ b3 = np.asarray(a3)
+ assert not has_shareable_memory(b3)
+
+ b3_reconstructed = reconstruct_array_or_memmap(b3)
+ assert isinstance(b3_reconstructed, np.ndarray)
+ assert not has_shareable_memory(b3_reconstructed)
+ assert_array_equal(b3_reconstructed, b3)
+
+
+@with_multiprocessing
+@skipif((sys.platform != "win32") or (),
+ reason="PermissionError only easily triggerable on Windows")
+def test_resource_tracker_retries_when_permissionerror(tmpdir):
+ # Test resource_tracker retry mechanism when unlinking memmaps. See more
+ # thorough information in the ``unlink_file`` documentation of joblib.
+ filename = tmpdir.join('test.mmap').strpath
+ cmd = """if 1:
+ import os
+ import numpy as np
+ import time
+ from joblib.externals.loky.backend import resource_tracker
+ resource_tracker.VERBOSE = 1
+
+ # Start the resource tracker
+ resource_tracker.ensure_running()
+ time.sleep(1)
+
+ # Create a file containing numpy data
+ memmap = np.memmap(r"{filename}", dtype=np.float64, shape=10, mode='w+')
+ memmap[:] = np.arange(10).astype(np.int8).data
+ memmap.flush()
+ assert os.path.exists(r"{filename}")
+ del memmap
+
+ # Create a np.memmap backed by this file
+ memmap = np.memmap(r"{filename}", dtype=np.float64, shape=10, mode='w+')
+ resource_tracker.register(r"{filename}", "file")
+
+ # Ask the resource_tracker to delete the file backing the np.memmap , this
+ # should raise PermissionError that the resource_tracker will log.
+ resource_tracker.maybe_unlink(r"{filename}", "file")
+
+ # Wait for the resource_tracker to process the maybe_unlink before cleaning
+ # up the memmap
+ time.sleep(2)
+ """.format(filename=filename)
+ p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE)
+ p.wait()
+ out, err = p.communicate()
+ assert p.returncode == 0
+ assert out == b''
+ msg = 'tried to unlink {}, got PermissionError'.format(filename)
+ assert msg in err.decode()
+
+
+@with_numpy
+@with_multiprocessing
+def test_high_dimension_memmap_array_reducing(tmpdir):
+ assert_array_equal = np.testing.assert_array_equal
+
+ filename = tmpdir.join('test.mmap').strpath
+
+ # Create a high dimensional memmap
+ a = np.memmap(filename, dtype=np.float64, shape=(100, 15, 15, 3),
+ mode='w+')
+ a[:] = np.arange(100 * 15 * 15 * 3).reshape(a.shape)
+
+ # Create some slices/indices at various dimensions
+ b = a[0:10]
+ c = a[:, 5:10]
+ d = a[:, :, :, 0]
+ e = a[1:3:4]
+
+ # Array reducer with auto dumping disabled
+ reducer = ArrayMemmapForwardReducer(None, tmpdir.strpath, 'c', True)
+
+ def reconstruct_array_or_memmap(x):
+ cons, args = reducer(x)
+ return cons(*args)
+
+ a_reconstructed = reconstruct_array_or_memmap(a)
+ assert has_shareable_memory(a_reconstructed)
+ assert isinstance(a_reconstructed, np.memmap)
+ assert_array_equal(a_reconstructed, a)
+
+ b_reconstructed = reconstruct_array_or_memmap(b)
+ assert has_shareable_memory(b_reconstructed)
+ assert_array_equal(b_reconstructed, b)
+
+ c_reconstructed = reconstruct_array_or_memmap(c)
+ assert has_shareable_memory(c_reconstructed)
+ assert_array_equal(c_reconstructed, c)
+
+ d_reconstructed = reconstruct_array_or_memmap(d)
+ assert has_shareable_memory(d_reconstructed)
+ assert_array_equal(d_reconstructed, d)
+
+ e_reconstructed = reconstruct_array_or_memmap(e)
+ assert has_shareable_memory(e_reconstructed)
+ assert_array_equal(e_reconstructed, e)
+
+
+@with_numpy
+def test__strided_from_memmap(tmpdir):
+ fname = tmpdir.join('test.mmap').strpath
+ size = 5 * mmap.ALLOCATIONGRANULARITY
+ offset = mmap.ALLOCATIONGRANULARITY + 1
+ # This line creates the mmap file that is reused later
+ memmap_obj = np.memmap(fname, mode='w+', shape=size + offset)
+ # filename, dtype, mode, offset, order, shape, strides, total_buffer_len
+ memmap_obj = _strided_from_memmap(fname, dtype='uint8', mode='r',
+ offset=offset, order='C', shape=size,
+ strides=None, total_buffer_len=None,
+ unlink_on_gc_collect=False)
+ assert isinstance(memmap_obj, np.memmap)
+ assert memmap_obj.offset == offset
+ memmap_backed_obj = _strided_from_memmap(
+ fname, dtype='uint8', mode='r', offset=offset, order='C',
+ shape=(size // 2,), strides=(2,), total_buffer_len=size,
+ unlink_on_gc_collect=False
+ )
+ assert _get_backing_memmap(memmap_backed_obj).offset == offset
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_pool_with_memmap(factory, tmpdir):
+ """Check that subprocess can access and update shared memory memmap"""
+ assert_array_equal = np.testing.assert_array_equal
+
+ # Fork the subprocess before allocating the objects to be passed
+ pool_temp_folder = tmpdir.mkdir('pool').strpath
+ p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder)
+ try:
+ filename = tmpdir.join('test.mmap').strpath
+ a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
+ a.fill(1.0)
+
+ p.map(inplace_double, [(a, (i, j), 1.0)
+ for i in range(a.shape[0])
+ for j in range(a.shape[1])])
+
+ assert_array_equal(a, 2 * np.ones(a.shape))
+
+ # Open a copy-on-write view on the previous data
+ b = np.memmap(filename, dtype=np.float32, shape=(5, 3), mode='c')
+
+ p.map(inplace_double, [(b, (i, j), 2.0)
+ for i in range(b.shape[0])
+ for j in range(b.shape[1])])
+
+ # Passing memmap instances to the pool should not trigger the creation
+ # of new files on the FS
+ assert os.listdir(pool_temp_folder) == []
+
+ # the original data is untouched
+ assert_array_equal(a, 2 * np.ones(a.shape))
+ assert_array_equal(b, 2 * np.ones(b.shape))
+
+ # readonly maps can be read but not updated
+ c = np.memmap(filename, dtype=np.float32, shape=(10,), mode='r',
+ offset=5 * 4)
+
+ with raises(AssertionError):
+ p.map(check_array, [(c, i, 3.0) for i in range(c.shape[0])])
+
+ # depending on the version of numpy one can either get a RuntimeError
+ # or a ValueError
+ with raises((RuntimeError, ValueError)):
+ p.map(inplace_double, [(c, i, 2.0) for i in range(c.shape[0])])
+ finally:
+ # Clean all filehandlers held by the pool
+ p.terminate()
+ del p
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_pool_with_memmap_array_view(factory, tmpdir):
+ """Check that subprocess can access and update shared memory array"""
+ assert_array_equal = np.testing.assert_array_equal
+
+ # Fork the subprocess before allocating the objects to be passed
+ pool_temp_folder = tmpdir.mkdir('pool').strpath
+ p = factory(10, max_nbytes=2, temp_folder=pool_temp_folder)
+ try:
+
+ filename = tmpdir.join('test.mmap').strpath
+ a = np.memmap(filename, dtype=np.float32, shape=(3, 5), mode='w+')
+ a.fill(1.0)
+
+ # Create an ndarray view on the memmap instance
+ a_view = np.asarray(a)
+ assert not isinstance(a_view, np.memmap)
+ assert has_shareable_memory(a_view)
+
+ p.map(inplace_double, [(a_view, (i, j), 1.0)
+ for i in range(a.shape[0])
+ for j in range(a.shape[1])])
+
+ # Both a and the a_view have been updated
+ assert_array_equal(a, 2 * np.ones(a.shape))
+ assert_array_equal(a_view, 2 * np.ones(a.shape))
+
+ # Passing memmap array view to the pool should not trigger the
+ # creation of new files on the FS
+ assert os.listdir(pool_temp_folder) == []
+
+ finally:
+ p.terminate()
+ del p
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_permission_error_windows_reference_cycle(backend):
+ # Non regression test for:
+ # https://github.com/joblib/joblib/issues/806
+ #
+ # The issue happens when trying to delete a memory mapped file that has
+ # not yet been closed by one of the worker processes.
+ cmd = """if 1:
+ import numpy as np
+ from joblib import Parallel, delayed
+
+
+ data = np.random.rand(int(2e6)).reshape((int(1e6), 2))
+
+ # Build a complex cyclic reference that is likely to delay garbage
+ # collection of the memmapped array in the worker processes.
+ first_list = current_list = [data]
+ for i in range(10):
+ current_list = [current_list]
+ first_list.append(current_list)
+
+ if __name__ == "__main__":
+ results = Parallel(n_jobs=2, backend="{b}")(
+ delayed(len)(current_list) for i in range(10))
+ assert results == [1] * 10
+ """.format(b=backend)
+ p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE)
+ p.wait()
+ out, err = p.communicate()
+ assert p.returncode == 0, out.decode() + "\n\n" + err.decode()
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_permission_error_windows_memmap_sent_to_parent(backend):
+ # Second non-regression test for:
+ # https://github.com/joblib/joblib/issues/806
+ # previously, child process would not convert temporary memmaps to numpy
+ # arrays when sending the data back to the parent process. This would lead
+ # to permission errors on windows when deleting joblib's temporary folder,
+ # as the memmaped files handles would still opened in the parent process.
+ cmd = '''if 1:
+ import os
+ import time
+
+ import numpy as np
+
+ from joblib import Parallel, delayed
+ from testutils import return_slice_of_data
+
+ data = np.ones(int(2e6))
+
+ if __name__ == '__main__':
+ # warm-up call to launch the workers and start the resource_tracker
+ _ = Parallel(n_jobs=2, verbose=5, backend='{b}')(
+ delayed(id)(i) for i in range(20))
+
+ time.sleep(0.5)
+
+ slice_of_data = Parallel(n_jobs=2, verbose=5, backend='{b}')(
+ delayed(return_slice_of_data)(data, 0, 20) for _ in range(10))
+ '''.format(b=backend)
+
+ for _ in range(3):
+ env = os.environ.copy()
+ env['PYTHONPATH'] = os.path.dirname(__file__)
+ p = subprocess.Popen([sys.executable, '-c', cmd],
+ stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE, env=env)
+ p.wait()
+ out, err = p.communicate()
+ assert p.returncode == 0, err
+ assert out == b''
+ if sys.version_info[:3] not in [(3, 8, 0), (3, 8, 1)]:
+ # In early versions of Python 3.8, a reference leak
+ # https://github.com/cloudpipe/cloudpickle/issues/327, holds
+ # references to pickled objects, generating race condition during
+ # cleanup finalizers of joblib and noisy resource_tracker outputs.
+ assert b'resource_tracker' not in err
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_parallel_isolated_temp_folders(backend):
+ # Test that consecutive Parallel call use isolated subfolders, even
+ # for the loky backend that reuses its executor instance across calls.
+ array = np.arange(int(1e2))
+ [filename_1] = Parallel(n_jobs=2, backend=backend, max_nbytes=10)(
+ delayed(getattr)(array, 'filename') for _ in range(1)
+ )
+ [filename_2] = Parallel(n_jobs=2, backend=backend, max_nbytes=10)(
+ delayed(getattr)(array, 'filename') for _ in range(1)
+ )
+ assert os.path.dirname(filename_2) != os.path.dirname(filename_1)
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_managed_backend_reuse_temp_folder(backend):
+ # Test that calls to a managed parallel object reuse the same memmaps.
+ array = np.arange(int(1e2))
+ with Parallel(n_jobs=2, backend=backend, max_nbytes=10) as p:
+ [filename_1] = p(
+ delayed(getattr)(array, 'filename') for _ in range(1)
+ )
+ [filename_2] = p(
+ delayed(getattr)(array, 'filename') for _ in range(1)
+ )
+ assert os.path.dirname(filename_2) == os.path.dirname(filename_1)
+
+
+@with_numpy
+@with_multiprocessing
+def test_memmapping_temp_folder_thread_safety():
+ # Concurrent calls to Parallel with the loky backend will use the same
+ # executor, and thus the same reducers. Make sure that those reducers use
+ # different temporary folders depending on which Parallel objects called
+ # them, which is necessary to limit potential race conditions during the
+ # garbage collection of temporary memmaps.
+ array = np.arange(int(1e2))
+
+ temp_dirs_thread_1 = set()
+ temp_dirs_thread_2 = set()
+
+ def concurrent_get_filename(array, temp_dirs):
+ with Parallel(backend='loky', n_jobs=2, max_nbytes=10) as p:
+ for i in range(10):
+ [filename] = p(
+ delayed(getattr)(array, 'filename') for _ in range(1)
+ )
+ temp_dirs.add(os.path.dirname(filename))
+
+ t1 = threading.Thread(
+ target=concurrent_get_filename, args=(array, temp_dirs_thread_1)
+ )
+ t2 = threading.Thread(
+ target=concurrent_get_filename, args=(array, temp_dirs_thread_2)
+ )
+
+ t1.start()
+ t2.start()
+
+ t1.join()
+ t2.join()
+
+ assert len(temp_dirs_thread_1) == 1
+ assert len(temp_dirs_thread_2) == 1
+
+ assert temp_dirs_thread_1 != temp_dirs_thread_2
+
+
+@with_numpy
+@with_multiprocessing
+def test_multithreaded_parallel_termination_resource_tracker_silent():
+ # test that concurrent termination attempts of a same executor does not
+ # emit any spurious error from the resource_tracker. We test various
+ # situations making 0, 1 or both parallel call sending a task that will
+ # make the worker (and thus the whole Parallel call) error out.
+ cmd = '''if 1:
+ import os
+ import numpy as np
+ from joblib import Parallel, delayed
+ from joblib.externals.loky.backend import resource_tracker
+ from concurrent.futures import ThreadPoolExecutor, wait
+
+ resource_tracker.VERBOSE = 0
+
+ array = np.arange(int(1e2))
+
+ temp_dirs_thread_1 = set()
+ temp_dirs_thread_2 = set()
+
+
+ def raise_error(array):
+ raise ValueError
+
+
+ def parallel_get_filename(array, temp_dirs):
+ with Parallel(backend="loky", n_jobs=2, max_nbytes=10) as p:
+ for i in range(10):
+ [filename] = p(
+ delayed(getattr)(array, "filename") for _ in range(1)
+ )
+ temp_dirs.add(os.path.dirname(filename))
+
+
+ def parallel_raise(array, temp_dirs):
+ with Parallel(backend="loky", n_jobs=2, max_nbytes=10) as p:
+ for i in range(10):
+ [filename] = p(
+ delayed(raise_error)(array) for _ in range(1)
+ )
+ temp_dirs.add(os.path.dirname(filename))
+
+
+ executor = ThreadPoolExecutor(max_workers=2)
+
+ # both function calls will use the same loky executor, but with a
+ # different Parallel object.
+ future_1 = executor.submit({f1}, array, temp_dirs_thread_1)
+ future_2 = executor.submit({f2}, array, temp_dirs_thread_2)
+
+ # Wait for both threads to terminate their backend
+ wait([future_1, future_2])
+
+ future_1.result()
+ future_2.result()
+ '''
+ functions_and_returncodes = [
+ ("parallel_get_filename", "parallel_get_filename", 0),
+ ("parallel_get_filename", "parallel_raise", 1),
+ ("parallel_raise", "parallel_raise", 1)
+ ]
+
+ for f1, f2, returncode in functions_and_returncodes:
+ p = subprocess.Popen([sys.executable, '-c', cmd.format(f1=f1, f2=f2)],
+ stderr=subprocess.PIPE, stdout=subprocess.PIPE)
+ p.wait()
+ out, err = p.communicate()
+ assert p.returncode == returncode, out.decode()
+ assert b"resource_tracker" not in err, err.decode()
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_many_parallel_calls_on_same_object(backend):
+ # After #966 got merged, consecutive Parallel objects were sharing temp
+ # folder, which would lead to race conditions happening during the
+ # temporary resources management with the resource_tracker. This is a
+ # non-regression test that makes sure that consecutive Parallel operations
+ # on the same object do not error out.
+ cmd = '''if 1:
+ import os
+ import time
+
+ import numpy as np
+
+ from joblib import Parallel, delayed
+ from testutils import return_slice_of_data
+
+ data = np.ones(100)
+
+ if __name__ == '__main__':
+ for i in range(5):
+ slice_of_data = Parallel(
+ n_jobs=2, max_nbytes=1, backend='{b}')(
+ delayed(return_slice_of_data)(data, 0, 20)
+ for _ in range(10)
+ )
+ '''.format(b=backend)
+ env = os.environ.copy()
+ env['PYTHONPATH'] = os.path.dirname(__file__)
+ p = subprocess.Popen(
+ [sys.executable, '-c', cmd],
+ stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ env=env,
+ )
+ p.wait()
+ out, err = p.communicate()
+ assert p.returncode == 0, err
+ assert out == b''
+ if sys.version_info[:3] not in [(3, 8, 0), (3, 8, 1)]:
+ # In early versions of Python 3.8, a reference leak
+ # https://github.com/cloudpipe/cloudpickle/issues/327, holds
+ # references to pickled objects, generating race condition during
+ # cleanup finalizers of joblib and noisy resource_tracker outputs.
+ assert b'resource_tracker' not in err
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_memmap_returned_as_regular_array(backend):
+ data = np.ones(int(1e3))
+ # Check that child processes send temporary memmaps back as numpy arrays.
+ [result] = Parallel(n_jobs=2, backend=backend, max_nbytes=100)(
+ delayed(check_memmap_and_send_back)(data) for _ in range(1))
+ assert _get_backing_memmap(result) is None
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("backend", ["multiprocessing", "loky"])
+def test_resource_tracker_silent_when_reference_cycles(backend):
+ # There is a variety of reasons that can make joblib with loky backend
+ # output noisy warnings when a reference cycle is preventing a memmap from
+ # being garbage collected. Especially, joblib's main process finalizer
+ # deletes the temporary folder if it was not done before, which can
+ # interact badly with the resource_tracker. We don't risk leaking any
+ # resources, but this will likely make joblib output a lot of low-level
+ # confusing messages.
+ #
+ # This test makes sure that the resource_tracker is silent when a reference
+ # has been collected concurrently on non-Windows platforms.
+ #
+ # Note that the script in ``cmd`` is the exact same script as in
+ # test_permission_error_windows_reference_cycle.
+ if backend == "loky" and sys.platform.startswith('win'):
+ # XXX: on Windows, reference cycles can delay timely garbage collection
+ # and make it impossible to properly delete the temporary folder in the
+ # main process because of permission errors.
+ pytest.xfail(
+ "The temporary folder cannot be deleted on Windows in the "
+ "presence of a reference cycle"
+ )
+
+ cmd = """if 1:
+ import numpy as np
+ from joblib import Parallel, delayed
+
+
+ data = np.random.rand(int(2e6)).reshape((int(1e6), 2))
+
+ # Build a complex cyclic reference that is likely to delay garbage
+ # collection of the memmapped array in the worker processes.
+ first_list = current_list = [data]
+ for i in range(10):
+ current_list = [current_list]
+ first_list.append(current_list)
+
+ if __name__ == "__main__":
+ results = Parallel(n_jobs=2, backend="{b}")(
+ delayed(len)(current_list) for i in range(10))
+ assert results == [1] * 10
+ """.format(b=backend)
+ p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE)
+ p.wait()
+ out, err = p.communicate()
+ out = out.decode()
+ err = err.decode()
+ assert p.returncode == 0, out + "\n\n" + err
+ assert "resource_tracker" not in err, err
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_memmapping_pool_for_large_arrays(factory, tmpdir):
+ """Check that large arrays are not copied in memory"""
+
+ # Check that the tempfolder is empty
+ assert os.listdir(tmpdir.strpath) == []
+
+ # Build an array reducers that automatically dump large array content
+ # to filesystem backed memmap instances to avoid memory explosion
+ p = factory(3, max_nbytes=40, temp_folder=tmpdir.strpath, verbose=2)
+ try:
+ # The temporary folder for the pool is not provisioned in advance
+ assert os.listdir(tmpdir.strpath) == []
+ assert not os.path.exists(p._temp_folder)
+
+ small = np.ones(5, dtype=np.float32)
+ assert small.nbytes == 20
+ p.map(check_array, [(small, i, 1.0) for i in range(small.shape[0])])
+
+ # Memory has been copied, the pool filesystem folder is unused
+ assert os.listdir(tmpdir.strpath) == []
+
+ # Try with a file larger than the memmap threshold of 40 bytes
+ large = np.ones(100, dtype=np.float64)
+ assert large.nbytes == 800
+ p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])])
+
+ # The data has been dumped in a temp folder for subprocess to share it
+ # without per-child memory copies
+ assert os.path.isdir(p._temp_folder)
+ dumped_filenames = os.listdir(p._temp_folder)
+ assert len(dumped_filenames) == 1
+
+ # Check that memory mapping is not triggered for arrays with
+ # dtype='object'
+ objects = np.array(['abc'] * 100, dtype='object')
+ results = p.map(has_shareable_memory, [objects])
+ assert not results[0]
+
+ finally:
+ # check FS garbage upon pool termination
+ p.terminate()
+ for i in range(10):
+ sleep(.1)
+ if not os.path.exists(p._temp_folder):
+ break
+ else: # pragma: no cover
+ raise AssertionError(
+ 'temporary folder of {} was not deleted'.format(p)
+ )
+ del p
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize(
+ "backend",
+ [
+ pytest.param(
+ "multiprocessing",
+ marks=pytest.mark.xfail(
+ reason='https://github.com/joblib/joblib/issues/1086'
+ ),
+ ),
+ "loky",
+ ]
+)
+def test_child_raises_parent_exits_cleanly(backend):
+ # When a task executed by a child process raises an error, the parent
+ # process's backend is notified, and calls abort_everything.
+ # In loky, abort_everything itself calls shutdown(kill_workers=True) which
+ # sends SIGKILL to the worker, preventing it from running the finalizers
+ # supposed to signal the resource_tracker when the worker is done using
+ # objects relying on a shared resource (e.g np.memmaps). Because this
+ # behavior is prone to :
+ # - cause a resource leak
+ # - make the resource tracker emit noisy resource warnings
+ # we explicitly test that, when the said situation occurs:
+ # - no resources are actually leaked
+ # - the temporary resources are deleted as soon as possible (typically, at
+ # the end of the failing Parallel call)
+ # - the resource_tracker does not emit any warnings.
+ cmd = """if 1:
+ import os
+ from pathlib import Path
+ from time import sleep
+
+ import numpy as np
+ from joblib import Parallel, delayed
+ from testutils import print_filename_and_raise
+
+ data = np.random.rand(1000)
+
+ def get_temp_folder(parallel_obj, backend):
+ if "{b}" == "loky":
+ return Path(p._backend._workers._temp_folder)
+ else:
+ return Path(p._backend._pool._temp_folder)
+
+
+ if __name__ == "__main__":
+ try:
+ with Parallel(n_jobs=2, backend="{b}", max_nbytes=100) as p:
+ temp_folder = get_temp_folder(p, "{b}")
+ p(delayed(print_filename_and_raise)(data)
+ for i in range(1))
+ except ValueError as e:
+ # the temporary folder should be deleted by the end of this
+ # call but apparently on some file systems, this takes
+ # some time to be visible.
+ #
+ # We attempt to write into the temporary folder to test for
+ # its existence and we wait for a maximum of 10 seconds.
+ for i in range(100):
+ try:
+ with open(temp_folder / "some_file.txt", "w") as f:
+ f.write("some content")
+ except FileNotFoundError:
+ # temp_folder has been deleted, all is fine
+ break
+
+ # ... else, wait a bit and try again
+ sleep(.1)
+ else:
+ raise AssertionError(
+ str(temp_folder) + " was not deleted"
+ ) from e
+ """.format(b=backend)
+ env = os.environ.copy()
+ env['PYTHONPATH'] = os.path.dirname(__file__)
+ p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE,
+ stdout=subprocess.PIPE, env=env)
+ p.wait()
+ out, err = p.communicate()
+ out, err = out.decode(), err.decode()
+ filename = out.split('\n')[0]
+ assert p.returncode == 0, err or out
+ assert err == '' # no resource_tracker warnings.
+ assert not os.path.exists(filename)
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_memmapping_pool_for_large_arrays_disabled(factory, tmpdir):
+ """Check that large arrays memmapping can be disabled"""
+ # Set max_nbytes to None to disable the auto memmapping feature
+ p = factory(3, max_nbytes=None, temp_folder=tmpdir.strpath)
+ try:
+
+ # Check that the tempfolder is empty
+ assert os.listdir(tmpdir.strpath) == []
+
+ # Try with a file largish than the memmap threshold of 40 bytes
+ large = np.ones(100, dtype=np.float64)
+ assert large.nbytes == 800
+ p.map(check_array, [(large, i, 1.0) for i in range(large.shape[0])])
+
+ # Check that the tempfolder is still empty
+ assert os.listdir(tmpdir.strpath) == []
+
+ finally:
+ # Cleanup open file descriptors
+ p.terminate()
+ del p
+
+
+@with_numpy
+@with_multiprocessing
+@with_dev_shm
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_memmapping_on_large_enough_dev_shm(factory):
+ """Check that memmapping uses /dev/shm when possible"""
+ orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE
+ try:
+ # Make joblib believe that it can use /dev/shm even when running on a
+ # CI container where the size of the /dev/shm is not very large (that
+ # is at least 32 MB instead of 2 GB by default).
+ jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(32e6)
+ p = factory(3, max_nbytes=10)
+ try:
+ # Check that the pool has correctly detected the presence of the
+ # shared memory filesystem.
+ pool_temp_folder = p._temp_folder
+ folder_prefix = '/dev/shm/joblib_memmapping_folder_'
+ assert pool_temp_folder.startswith(folder_prefix)
+ assert os.path.exists(pool_temp_folder)
+
+ # Try with a file larger than the memmap threshold of 10 bytes
+ a = np.ones(100, dtype=np.float64)
+ assert a.nbytes == 800
+ p.map(id, [a] * 10)
+ # a should have been memmapped to the pool temp folder: the joblib
+ # pickling procedure generate one .pkl file:
+ assert len(os.listdir(pool_temp_folder)) == 1
+
+ # create a new array with content that is different from 'a' so
+ # that it is mapped to a different file in the temporary folder of
+ # the pool.
+ b = np.ones(100, dtype=np.float64) * 2
+ assert b.nbytes == 800
+ p.map(id, [b] * 10)
+ # A copy of both a and b are now stored in the shared memory folder
+ assert len(os.listdir(pool_temp_folder)) == 2
+ finally:
+ # Cleanup open file descriptors
+ p.terminate()
+ del p
+
+ for i in range(100):
+ # The temp folder is cleaned up upon pool termination
+ if not os.path.exists(pool_temp_folder):
+ break
+ sleep(.1)
+ else: # pragma: no cover
+ raise AssertionError('temporary folder of pool was not deleted')
+ finally:
+ jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size
+
+
+@with_numpy
+@with_multiprocessing
+@with_dev_shm
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_memmapping_on_too_small_dev_shm(factory):
+ orig_size = jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE
+ try:
+ # Make joblib believe that it cannot use /dev/shm unless there is
+ # 42 exabytes of available shared memory in /dev/shm
+ jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(42e18)
+
+ p = factory(3, max_nbytes=10)
+ try:
+ # Check that the pool has correctly detected the presence of the
+ # shared memory filesystem.
+ pool_temp_folder = p._temp_folder
+ assert not pool_temp_folder.startswith('/dev/shm')
+ finally:
+ # Cleanup open file descriptors
+ p.terminate()
+ del p
+
+ # The temp folder is cleaned up upon pool termination
+ assert not os.path.exists(pool_temp_folder)
+ finally:
+ jmr.SYSTEM_SHARED_MEM_FS_MIN_SIZE = orig_size
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_memmapping_pool_for_large_arrays_in_return(factory, tmpdir):
+ """Check that large arrays are not copied in memory in return"""
+ assert_array_equal = np.testing.assert_array_equal
+
+ # Build an array reducers that automatically dump large array content
+ # but check that the returned datastructure are regular arrays to avoid
+ # passing a memmap array pointing to a pool controlled temp folder that
+ # might be confusing to the user
+
+ # The MemmappingPool user can always return numpy.memmap object explicitly
+ # to avoid memory copy
+ p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath)
+ try:
+ res = p.apply_async(np.ones, args=(1000,))
+ large = res.get()
+ assert not has_shareable_memory(large)
+ assert_array_equal(large, np.ones(1000))
+ finally:
+ p.terminate()
+ del p
+
+
+def _worker_multiply(a, n_times):
+ """Multiplication function to be executed by subprocess"""
+ assert has_shareable_memory(a)
+ return a * n_times
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize("factory", [MemmappingPool, TestExecutor.get_memmapping_executor],
+ ids=["multiprocessing", "loky"])
+def test_workaround_against_bad_memmap_with_copied_buffers(factory, tmpdir):
+ """Check that memmaps with a bad buffer are returned as regular arrays
+
+ Unary operations and ufuncs on memmap instances return a new memmap
+ instance with an in-memory buffer (probably a numpy bug).
+ """
+ assert_array_equal = np.testing.assert_array_equal
+
+ p = factory(3, max_nbytes=10, temp_folder=tmpdir.strpath)
+ try:
+ # Send a complex, large-ish view on a array that will be converted to
+ # a memmap in the worker process
+ a = np.asarray(np.arange(6000).reshape((1000, 2, 3)),
+ order='F')[:, :1, :]
+
+ # Call a non-inplace multiply operation on the worker and memmap and
+ # send it back to the parent.
+ b = p.apply_async(_worker_multiply, args=(a, 3)).get()
+ assert not has_shareable_memory(b)
+ assert_array_equal(b, 3 * a)
+ finally:
+ p.terminate()
+ del p
+
+
+def identity(arg):
+ return arg
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize(
+ "factory,retry_no",
+ list(itertools.product(
+ [MemmappingPool, TestExecutor.get_memmapping_executor], range(3))),
+ ids=['{}, {}'.format(x, y) for x, y in itertools.product(
+ ["multiprocessing", "loky"], map(str, range(3)))])
+def test_pool_memmap_with_big_offset(factory, retry_no, tmpdir):
+ # Test that numpy memmap offset is set correctly if greater than
+ # mmap.ALLOCATIONGRANULARITY, see
+ # https://github.com/joblib/joblib/issues/451 and
+ # https://github.com/numpy/numpy/pull/8443 for more details.
+ fname = tmpdir.join('test.mmap').strpath
+ size = 5 * mmap.ALLOCATIONGRANULARITY
+ offset = mmap.ALLOCATIONGRANULARITY + 1
+ obj = make_memmap(fname, mode='w+', shape=size, dtype='uint8',
+ offset=offset)
+
+ p = factory(2, temp_folder=tmpdir.strpath)
+ result = p.apply_async(identity, args=(obj,)).get()
+ assert isinstance(result, np.memmap)
+ assert result.offset == offset
+ np.testing.assert_array_equal(obj, result)
+ p.terminate()
+
+
+def test_pool_get_temp_dir(tmpdir):
+ pool_folder_name = 'test.tmpdir'
+ pool_folder, shared_mem = _get_temp_dir(pool_folder_name, tmpdir.strpath)
+ assert shared_mem is False
+ assert pool_folder == tmpdir.join('test.tmpdir').strpath
+
+ pool_folder, shared_mem = _get_temp_dir(pool_folder_name, temp_folder=None)
+ if sys.platform.startswith('win'):
+ assert shared_mem is False
+ assert pool_folder.endswith(pool_folder_name)
+
+
+@with_numpy
+@skipif(sys.platform == 'win32', reason='This test fails with a '
+ 'PermissionError on Windows')
+@parametrize("mmap_mode", ["r+", "w+"])
+def test_numpy_arrays_use_different_memory(mmap_mode):
+ def func(arr, value):
+ arr[:] = value
+ return arr
+
+ arrays = [np.zeros((10, 10), dtype='float64') for i in range(10)]
+
+ results = Parallel(mmap_mode=mmap_mode, max_nbytes=0, n_jobs=2)(
+ delayed(func)(arr, i) for i, arr in enumerate(arrays))
+
+ for i, arr in enumerate(results):
+ np.testing.assert_array_equal(arr, i)
+
+
+@with_numpy
+def test_weak_array_key_map():
+
+ def assert_empty_after_gc_collect(container, retries=100):
+ for i in range(retries):
+ if len(container) == 0:
+ return
+ gc.collect()
+ sleep(.1)
+ assert len(container) == 0
+
+ a = np.ones(42)
+ m = _WeakArrayKeyMap()
+ m.set(a, 'a')
+ assert m.get(a) == 'a'
+
+ b = a
+ assert m.get(b) == 'a'
+ m.set(b, 'b')
+ assert m.get(a) == 'b'
+
+ del a
+ gc.collect()
+ assert len(m._data) == 1
+ assert m.get(b) == 'b'
+
+ del b
+ assert_empty_after_gc_collect(m._data)
+
+ c = np.ones(42)
+ m.set(c, 'c')
+ assert len(m._data) == 1
+ assert m.get(c) == 'c'
+
+ with raises(KeyError):
+ m.get(np.ones(42))
+
+ del c
+ assert_empty_after_gc_collect(m._data)
+
+ # Check that creating and dropping numpy arrays with potentially the same
+ # object id will not cause the map to get confused.
+ def get_set_get_collect(m, i):
+ a = np.ones(42)
+ with raises(KeyError):
+ m.get(a)
+ m.set(a, i)
+ assert m.get(a) == i
+ return id(a)
+
+ unique_ids = set([get_set_get_collect(m, i) for i in range(1000)])
+ if platform.python_implementation() == 'CPython':
+ # On CPython (at least) the same id is often reused many times for the
+ # temporary arrays created under the local scope of the
+ # get_set_get_collect function without causing any spurious lookups /
+ # insertions in the map.
+ assert len(unique_ids) < 100
+
+
+def test_weak_array_key_map_no_pickling():
+ m = _WeakArrayKeyMap()
+ with raises(pickle.PicklingError):
+ pickle.dumps(m)
+
+
+@with_numpy
+@with_multiprocessing
+def test_direct_mmap(tmpdir):
+ testfile = str(tmpdir.join('arr.dat'))
+ a = np.arange(10, dtype='uint8')
+ a.tofile(testfile)
+
+ def _read_array():
+ with open(testfile) as fd:
+ mm = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ, offset=0)
+ return np.ndarray((10,), dtype=np.uint8, buffer=mm, offset=0)
+
+ def func(x):
+ return x**2
+
+ arr = _read_array()
+
+ # this is expected to work and gives the reference
+ ref = Parallel(n_jobs=2)(delayed(func)(x) for x in [a])
+
+ # now test that it work with the mmap array
+ results = Parallel(n_jobs=2)(delayed(func)(x) for x in [arr])
+ np.testing.assert_array_equal(results, ref)
+
+ # also test with a mmap array read in the subprocess
+ def worker():
+ return _read_array()
+
+ results = Parallel(n_jobs=2)(delayed(worker)() for _ in range(1))
+ np.testing.assert_array_equal(results[0], arr)
diff --git a/runtime/Lib/site-packages/joblib/test/test_memory.py b/runtime/Lib/site-packages/joblib/test/test_memory.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaa7d169584b1d448b05cd665c323699e7fd2a65
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_memory.py
@@ -0,0 +1,1316 @@
+"""
+Test the memory module.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import functools
+import gc
+import shutil
+import os
+import os.path
+import pathlib
+import pickle
+import sys
+import time
+import datetime
+import textwrap
+
+import pytest
+
+from joblib.memory import Memory
+from joblib.memory import MemorizedFunc, NotMemorizedFunc
+from joblib.memory import MemorizedResult, NotMemorizedResult
+from joblib.memory import _FUNCTION_HASHES
+from joblib.memory import register_store_backend, _STORE_BACKENDS
+from joblib.memory import _build_func_identifier, _store_backend_factory
+from joblib.memory import JobLibCollisionWarning
+from joblib.parallel import Parallel, delayed
+from joblib._store_backends import StoreBackendBase, FileSystemStoreBackend
+from joblib.test.common import with_numpy, np
+from joblib.test.common import with_multiprocessing
+from joblib.testing import parametrize, raises, warns
+from joblib.hashing import hash
+
+
+
+###############################################################################
+# Module-level variables for the tests
+def f(x, y=1):
+ """ A module-level function for testing purposes.
+ """
+ return x ** 2 + y
+
+
+###############################################################################
+# Helper function for the tests
+def check_identity_lazy(func, accumulator, location):
+ """ Given a function and an accumulator (a list that grows every
+ time the function is called), check that the function can be
+ decorated by memory to be a lazy identity.
+ """
+ # Call each function with several arguments, and check that it is
+ # evaluated only once per argument.
+ memory = Memory(location=location, verbose=0)
+ func = memory.cache(func)
+ for i in range(3):
+ for _ in range(2):
+ assert func(i) == i
+ assert len(accumulator) == i + 1
+
+
+def corrupt_single_cache_item(memory):
+ single_cache_item, = memory.store_backend.get_items()
+ output_filename = os.path.join(single_cache_item.path, 'output.pkl')
+ with open(output_filename, 'w') as f:
+ f.write('garbage')
+
+
+def monkeypatch_cached_func_warn(func, monkeypatch_fixture):
+ # Need monkeypatch because pytest does not
+ # capture stdlib logging output (see
+ # https://github.com/pytest-dev/pytest/issues/2079)
+
+ recorded = []
+
+ def append_to_record(item):
+ recorded.append(item)
+ monkeypatch_fixture.setattr(func, 'warn', append_to_record)
+ return recorded
+
+
+###############################################################################
+# Tests
+def test_memory_integration(tmpdir):
+ """ Simple test of memory lazy evaluation.
+ """
+ accumulator = list()
+ # Rmk: this function has the same name than a module-level function,
+ # thus it serves as a test to see that both are identified
+ # as different.
+
+ def f(l):
+ accumulator.append(1)
+ return l
+
+ check_identity_lazy(f, accumulator, tmpdir.strpath)
+
+ # Now test clearing
+ for compress in (False, True):
+ for mmap_mode in ('r', None):
+ memory = Memory(location=tmpdir.strpath, verbose=10,
+ mmap_mode=mmap_mode, compress=compress)
+ # First clear the cache directory, to check that our code can
+ # handle that
+ # NOTE: this line would raise an exception, as the database file is
+ # still open; we ignore the error since we want to test what
+ # happens if the directory disappears
+ shutil.rmtree(tmpdir.strpath, ignore_errors=True)
+ g = memory.cache(f)
+ g(1)
+ g.clear(warn=False)
+ current_accumulator = len(accumulator)
+ out = g(1)
+
+ assert len(accumulator) == current_accumulator + 1
+ # Also, check that Memory.eval works similarly
+ assert memory.eval(f, 1) == out
+ assert len(accumulator) == current_accumulator + 1
+
+ # Now do a smoke test with a function defined in __main__, as the name
+ # mangling rules are more complex
+ f.__module__ = '__main__'
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ memory.cache(f)(1)
+
+
+@parametrize("call_before_reducing", [True, False])
+def test_parallel_call_cached_function_defined_in_jupyter(
+ tmpdir, call_before_reducing
+):
+ # Calling an interactively defined memory.cache()'d function inside a
+ # Parallel call used to clear the existing cache related to the said
+ # function (https://github.com/joblib/joblib/issues/1035)
+
+ # This tests checks that this is no longer the case.
+
+ # TODO: test that the cache related to the function cache persists across
+ # ipython sessions (provided that no code change were made to the
+ # function's source)?
+
+ # The first part of the test makes the necessary low-level calls to emulate
+ # the definition of a function in an jupyter notebook cell. Joblib has
+ # some custom code to treat functions defined specifically in jupyter
+ # notebooks/ipython session -- we want to test this code, which requires
+ # the emulation to be rigorous.
+ for session_no in [0, 1]:
+ ipython_cell_source = '''
+ def f(x):
+ return x
+ '''
+
+ ipython_cell_id = ''.format(session_no)
+
+ exec(
+ compile(
+ textwrap.dedent(ipython_cell_source),
+ filename=ipython_cell_id,
+ mode='exec'
+ )
+ )
+ # f is now accessible in the locals mapping - but for some unknown
+ # reason, f = locals()['f'] throws a KeyError at runtime, we need to
+ # bind locals()['f'] to a different name in the local namespace
+ aliased_f = locals()['f']
+ aliased_f.__module__ = "__main__"
+
+ # Preliminary sanity checks, and tests checking that joblib properly
+ # identified f as an interactive function defined in a jupyter notebook
+ assert aliased_f(1) == 1
+ assert aliased_f.__code__.co_filename == ipython_cell_id
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ cached_f = memory.cache(aliased_f)
+
+ assert len(os.listdir(tmpdir / 'joblib')) == 1
+ f_cache_relative_directory = os.listdir(tmpdir / 'joblib')[0]
+ assert 'ipython-input' in f_cache_relative_directory
+
+ f_cache_directory = tmpdir / 'joblib' / f_cache_relative_directory
+
+ if session_no == 0:
+ # The cache should be empty as cached_f has not been called yet.
+ assert os.listdir(f_cache_directory) == ['f']
+ assert os.listdir(f_cache_directory / 'f') == []
+
+ if call_before_reducing:
+ cached_f(3)
+ # Two files were just created, func_code.py, and a folder
+ # containing the information (inputs hash/ouptput) of
+ # cached_f(3)
+ assert len(os.listdir(f_cache_directory / 'f')) == 2
+
+ # Now, testing #1035: when calling a cached function, joblib
+ # used to dynamically inspect the underlying function to
+ # extract its source code (to verify it matches the source code
+ # of the function as last inspected by joblib) -- however,
+ # source code introspection fails for dynamic functions sent to
+ # child processes - which would eventually make joblib clear
+ # the cache associated to f
+ res = Parallel(n_jobs=2)(delayed(cached_f)(i) for i in [1, 2])
+ else:
+ # Submit the function to the joblib child processes, although
+ # the function has never been called in the parent yet. This
+ # triggers a specific code branch inside
+ # MemorizedFunc.__reduce__.
+ res = Parallel(n_jobs=2)(delayed(cached_f)(i) for i in [1, 2])
+ assert len(os.listdir(f_cache_directory / 'f')) == 3
+
+ cached_f(3)
+
+ # Making sure f's cache does not get cleared after the parallel
+ # calls, and contains ALL cached functions calls (f(1), f(2), f(3))
+ # and 'func_code.py'
+ assert len(os.listdir(f_cache_directory / 'f')) == 4
+ else:
+ # For the second session, there should be an already existing cache
+ assert len(os.listdir(f_cache_directory / 'f')) == 4
+
+ cached_f(3)
+
+ # The previous cache should not be invalidated after calling the
+ # function in a new session
+ assert len(os.listdir(f_cache_directory / 'f')) == 4
+
+
+def test_no_memory():
+ """ Test memory with location=None: no memoize """
+ accumulator = list()
+
+ def ff(l):
+ accumulator.append(1)
+ return l
+
+ memory = Memory(location=None, verbose=0)
+ gg = memory.cache(ff)
+ for _ in range(4):
+ current_accumulator = len(accumulator)
+ gg(1)
+ assert len(accumulator) == current_accumulator + 1
+
+
+def test_memory_kwarg(tmpdir):
+ " Test memory with a function with keyword arguments."
+ accumulator = list()
+
+ def g(l=None, m=1):
+ accumulator.append(1)
+ return l
+
+ check_identity_lazy(g, accumulator, tmpdir.strpath)
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ g = memory.cache(g)
+ # Smoke test with an explicit keyword argument:
+ assert g(l=30, m=2) == 30
+
+
+def test_memory_lambda(tmpdir):
+ " Test memory with a function with a lambda."
+ accumulator = list()
+
+ def helper(x):
+ """ A helper function to define l as a lambda.
+ """
+ accumulator.append(1)
+ return x
+
+ l = lambda x: helper(x)
+
+ check_identity_lazy(l, accumulator, tmpdir.strpath)
+
+
+def test_memory_name_collision(tmpdir):
+ " Check that name collisions with functions will raise warnings"
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ @memory.cache
+ def name_collision(x):
+ """ A first function called name_collision
+ """
+ return x
+
+ a = name_collision
+
+ @memory.cache
+ def name_collision(x):
+ """ A second function called name_collision
+ """
+ return x
+
+ b = name_collision
+
+ with warns(JobLibCollisionWarning) as warninfo:
+ a(1)
+ b(1)
+
+ assert len(warninfo) == 1
+ assert "collision" in str(warninfo[0].message)
+
+
+def test_memory_warning_lambda_collisions(tmpdir):
+ # Check that multiple use of lambda will raise collisions
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ a = lambda x: x
+ a = memory.cache(a)
+ b = lambda x: x + 1
+ b = memory.cache(b)
+
+ with warns(JobLibCollisionWarning) as warninfo:
+ assert a(0) == 0
+ assert b(1) == 2
+ assert a(1) == 1
+
+ # In recent Python versions, we can retrieve the code of lambdas,
+ # thus nothing is raised
+ assert len(warninfo) == 4
+
+
+def test_memory_warning_collision_detection(tmpdir):
+ # Check that collisions impossible to detect will raise appropriate
+ # warnings.
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ a1 = eval('lambda x: x')
+ a1 = memory.cache(a1)
+ b1 = eval('lambda x: x+1')
+ b1 = memory.cache(b1)
+
+ with warns(JobLibCollisionWarning) as warninfo:
+ a1(1)
+ b1(1)
+ a1(0)
+
+ assert len(warninfo) == 2
+ assert "cannot detect" in str(warninfo[0].message).lower()
+
+
+def test_memory_partial(tmpdir):
+ " Test memory with functools.partial."
+ accumulator = list()
+
+ def func(x, y):
+ """ A helper function to define l as a lambda.
+ """
+ accumulator.append(1)
+ return y
+
+ import functools
+ function = functools.partial(func, 1)
+
+ check_identity_lazy(function, accumulator, tmpdir.strpath)
+
+
+def test_memory_eval(tmpdir):
+ " Smoke test memory with a function with a function defined in an eval."
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ m = eval('lambda x: x')
+ mm = memory.cache(m)
+
+ assert mm(1) == 1
+
+
+def count_and_append(x=[]):
+ """ A function with a side effect in its arguments.
+
+ Return the length of its argument and append one element.
+ """
+ len_x = len(x)
+ x.append(None)
+ return len_x
+
+
+def test_argument_change(tmpdir):
+ """ Check that if a function has a side effect in its arguments, it
+ should use the hash of changing arguments.
+ """
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ func = memory.cache(count_and_append)
+ # call the function for the first time, is should cache it with
+ # argument x=[]
+ assert func() == 0
+ # the second time the argument is x=[None], which is not cached
+ # yet, so the functions should be called a second time
+ assert func() == 1
+
+
+@with_numpy
+@parametrize('mmap_mode', [None, 'r'])
+def test_memory_numpy(tmpdir, mmap_mode):
+ " Test memory with a function with numpy arrays."
+ accumulator = list()
+
+ def n(l=None):
+ accumulator.append(1)
+ return l
+
+ memory = Memory(location=tmpdir.strpath, mmap_mode=mmap_mode,
+ verbose=0)
+ cached_n = memory.cache(n)
+
+ rnd = np.random.RandomState(0)
+ for i in range(3):
+ a = rnd.random_sample((10, 10))
+ for _ in range(3):
+ assert np.all(cached_n(a) == a)
+ assert len(accumulator) == i + 1
+
+
+@with_numpy
+def test_memory_numpy_check_mmap_mode(tmpdir, monkeypatch):
+ """Check that mmap_mode is respected even at the first call"""
+
+ memory = Memory(location=tmpdir.strpath, mmap_mode='r', verbose=0)
+
+ @memory.cache()
+ def twice(a):
+ return a * 2
+
+ a = np.ones(3)
+
+ b = twice(a)
+ c = twice(a)
+
+ assert isinstance(c, np.memmap)
+ assert c.mode == 'r'
+
+ assert isinstance(b, np.memmap)
+ assert b.mode == 'r'
+
+ # Corrupts the file, Deleting b and c mmaps
+ # is necessary to be able edit the file
+ del b
+ del c
+ gc.collect()
+ corrupt_single_cache_item(memory)
+
+ # Make sure that corrupting the file causes recomputation and that
+ # a warning is issued.
+ recorded_warnings = monkeypatch_cached_func_warn(twice, monkeypatch)
+ d = twice(a)
+ assert len(recorded_warnings) == 1
+ exception_msg = 'Exception while loading results'
+ assert exception_msg in recorded_warnings[0]
+ # Asserts that the recomputation returns a mmap
+ assert isinstance(d, np.memmap)
+ assert d.mode == 'r'
+
+
+def test_memory_exception(tmpdir):
+ """ Smoketest the exception handling of Memory.
+ """
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ class MyException(Exception):
+ pass
+
+ @memory.cache
+ def h(exc=0):
+ if exc:
+ raise MyException
+
+ # Call once, to initialise the cache
+ h()
+
+ for _ in range(3):
+ # Call 3 times, to be sure that the Exception is always raised
+ with raises(MyException):
+ h(1)
+
+
+def test_memory_ignore(tmpdir):
+ " Test the ignore feature of memory "
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ accumulator = list()
+
+ @memory.cache(ignore=['y'])
+ def z(x, y=1):
+ accumulator.append(1)
+
+ assert z.ignore == ['y']
+
+ z(0, y=1)
+ assert len(accumulator) == 1
+ z(0, y=1)
+ assert len(accumulator) == 1
+ z(0, y=2)
+ assert len(accumulator) == 1
+
+
+def test_memory_ignore_decorated(tmpdir):
+ " Test the ignore feature of memory on a decorated function "
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ accumulator = list()
+
+ def decorate(f):
+ @functools.wraps(f)
+ def wrapped(*args, **kwargs):
+ return f(*args, **kwargs)
+ return wrapped
+
+ @memory.cache(ignore=['y'])
+ @decorate
+ def z(x, y=1):
+ accumulator.append(1)
+
+ assert z.ignore == ['y']
+
+ z(0, y=1)
+ assert len(accumulator) == 1
+ z(0, y=1)
+ assert len(accumulator) == 1
+ z(0, y=2)
+ assert len(accumulator) == 1
+
+
+def test_memory_args_as_kwargs(tmpdir):
+ """Non-regression test against 0.12.0 changes.
+
+ https://github.com/joblib/joblib/pull/751
+ """
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ @memory.cache
+ def plus_one(a):
+ return a + 1
+
+ # It's possible to call a positional arg as a kwarg.
+ assert plus_one(1) == 2
+ assert plus_one(a=1) == 2
+
+ # However, a positional argument that joblib hadn't seen
+ # before would cause a failure if it was passed as a kwarg.
+ assert plus_one(a=2) == 3
+
+
+@parametrize('ignore, verbose, mmap_mode', [(['x'], 100, 'r'),
+ ([], 10, None)])
+def test_partial_decoration(tmpdir, ignore, verbose, mmap_mode):
+ "Check cache may be called with kwargs before decorating"
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ @memory.cache(ignore=ignore, verbose=verbose, mmap_mode=mmap_mode)
+ def z(x):
+ pass
+
+ assert z.ignore == ignore
+ assert z._verbose == verbose
+ assert z.mmap_mode == mmap_mode
+
+
+def test_func_dir(tmpdir):
+ # Test the creation of the memory cache directory for the function.
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ path = __name__.split('.')
+ path.append('f')
+ path = tmpdir.join('joblib', *path).strpath
+
+ g = memory.cache(f)
+ # Test that the function directory is created on demand
+ func_id = _build_func_identifier(f)
+ location = os.path.join(g.store_backend.location, func_id)
+ assert location == path
+ assert os.path.exists(path)
+ assert memory.location == os.path.dirname(g.store_backend.location)
+
+ # Test that the code is stored.
+ # For the following test to be robust to previous execution, we clear
+ # the in-memory store
+ _FUNCTION_HASHES.clear()
+ assert not g._check_previous_func_code()
+ assert os.path.exists(os.path.join(path, 'func_code.py'))
+ assert g._check_previous_func_code()
+
+ # Test the robustness to failure of loading previous results.
+ func_id, args_id = g._get_output_identifiers(1)
+ output_dir = os.path.join(g.store_backend.location, func_id, args_id)
+ a = g(1)
+ assert os.path.exists(output_dir)
+ os.remove(os.path.join(output_dir, 'output.pkl'))
+ assert a == g(1)
+
+
+def test_persistence(tmpdir):
+ # Test the memorized functions can be pickled and restored.
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ g = memory.cache(f)
+ output = g(1)
+
+ h = pickle.loads(pickle.dumps(g))
+
+ func_id, args_id = h._get_output_identifiers(1)
+ output_dir = os.path.join(h.store_backend.location, func_id, args_id)
+ assert os.path.exists(output_dir)
+ assert output == h.store_backend.load_item([func_id, args_id])
+ memory2 = pickle.loads(pickle.dumps(memory))
+ assert memory.store_backend.location == memory2.store_backend.location
+
+ # Smoke test that pickling a memory with location=None works
+ memory = Memory(location=None, verbose=0)
+ pickle.loads(pickle.dumps(memory))
+ g = memory.cache(f)
+ gp = pickle.loads(pickle.dumps(g))
+ gp(1)
+
+
+def test_check_call_in_cache(tmpdir):
+ for func in (MemorizedFunc(f, tmpdir.strpath),
+ Memory(location=tmpdir.strpath, verbose=0).cache(f)):
+ result = func.check_call_in_cache(2)
+ assert not result
+ assert isinstance(result, bool)
+ assert func(2) == 5
+ result = func.check_call_in_cache(2)
+ assert result
+ assert isinstance(result, bool)
+ func.clear()
+
+
+def test_call_and_shelve(tmpdir):
+ # Test MemorizedFunc outputting a reference to cache.
+
+ for func, Result in zip((MemorizedFunc(f, tmpdir.strpath),
+ NotMemorizedFunc(f),
+ Memory(location=tmpdir.strpath,
+ verbose=0).cache(f),
+ Memory(location=None).cache(f),
+ ),
+ (MemorizedResult, NotMemorizedResult,
+ MemorizedResult, NotMemorizedResult)):
+ assert func(2) == 5
+ result = func.call_and_shelve(2)
+ assert isinstance(result, Result)
+ assert result.get() == 5
+
+ result.clear()
+ with raises(KeyError):
+ result.get()
+ result.clear() # Do nothing if there is no cache.
+
+
+def test_call_and_shelve_argument_hash(tmpdir):
+ # Verify that a warning is raised when accessing arguments_hash
+ # attribute from MemorizedResult
+ func = Memory(location=tmpdir.strpath, verbose=0).cache(f)
+ result = func.call_and_shelve(2)
+ assert isinstance(result, MemorizedResult)
+ with warns(DeprecationWarning) as w:
+ assert result.argument_hash == result.args_id
+ assert len(w) == 1
+ assert "The 'argument_hash' attribute has been deprecated" \
+ in str(w[-1].message)
+
+
+def test_call_and_shelve_lazily_load_stored_result(tmpdir):
+ """Check call_and_shelve only load stored data if needed."""
+ test_access_time_file = tmpdir.join('test_access')
+ test_access_time_file.write('test_access')
+ test_access_time = os.stat(test_access_time_file.strpath).st_atime
+ # check file system access time stats resolution is lower than test wait
+ # timings.
+ time.sleep(0.5)
+ assert test_access_time_file.read() == 'test_access'
+
+ if test_access_time == os.stat(test_access_time_file.strpath).st_atime:
+ # Skip this test when access time cannot be retrieved with enough
+ # precision from the file system (e.g. NTFS on windows).
+ pytest.skip("filesystem does not support fine-grained access time "
+ "attribute")
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ func = memory.cache(f)
+ func_id, argument_hash = func._get_output_identifiers(2)
+ result_path = os.path.join(memory.store_backend.location,
+ func_id, argument_hash, 'output.pkl')
+ assert func(2) == 5
+ first_access_time = os.stat(result_path).st_atime
+ time.sleep(1)
+
+ # Should not access the stored data
+ result = func.call_and_shelve(2)
+ assert isinstance(result, MemorizedResult)
+ assert os.stat(result_path).st_atime == first_access_time
+ time.sleep(1)
+
+ # Read the stored data => last access time is greater than first_access
+ assert result.get() == 5
+ assert os.stat(result_path).st_atime > first_access_time
+
+
+def test_memorized_pickling(tmpdir):
+ for func in (MemorizedFunc(f, tmpdir.strpath), NotMemorizedFunc(f)):
+ filename = tmpdir.join('pickling_test.dat').strpath
+ result = func.call_and_shelve(2)
+ with open(filename, 'wb') as fp:
+ pickle.dump(result, fp)
+ with open(filename, 'rb') as fp:
+ result2 = pickle.load(fp)
+ assert result2.get() == result.get()
+ os.remove(filename)
+
+
+def test_memorized_repr(tmpdir):
+ func = MemorizedFunc(f, tmpdir.strpath)
+ result = func.call_and_shelve(2)
+
+ func2 = MemorizedFunc(f, tmpdir.strpath)
+ result2 = func2.call_and_shelve(2)
+ assert result.get() == result2.get()
+ assert repr(func) == repr(func2)
+
+ # Smoke test with NotMemorizedFunc
+ func = NotMemorizedFunc(f)
+ repr(func)
+ repr(func.call_and_shelve(2))
+
+ # Smoke test for message output (increase code coverage)
+ func = MemorizedFunc(f, tmpdir.strpath, verbose=11, timestamp=time.time())
+ result = func.call_and_shelve(11)
+ result.get()
+
+ func = MemorizedFunc(f, tmpdir.strpath, verbose=11)
+ result = func.call_and_shelve(11)
+ result.get()
+
+ func = MemorizedFunc(f, tmpdir.strpath, verbose=5, timestamp=time.time())
+ result = func.call_and_shelve(11)
+ result.get()
+
+ func = MemorizedFunc(f, tmpdir.strpath, verbose=5)
+ result = func.call_and_shelve(11)
+ result.get()
+
+
+def test_memory_file_modification(capsys, tmpdir, monkeypatch):
+ # Test that modifying a Python file after loading it does not lead to
+ # Recomputation
+ dir_name = tmpdir.mkdir('tmp_import').strpath
+ filename = os.path.join(dir_name, 'tmp_joblib_.py')
+ content = 'def f(x):\n print(x)\n return x\n'
+ with open(filename, 'w') as module_file:
+ module_file.write(content)
+
+ # Load the module:
+ monkeypatch.syspath_prepend(dir_name)
+ import tmp_joblib_ as tmp
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ f = memory.cache(tmp.f)
+ # First call f a few times
+ f(1)
+ f(2)
+ f(1)
+
+ # Now modify the module where f is stored without modifying f
+ with open(filename, 'w') as module_file:
+ module_file.write('\n\n' + content)
+
+ # And call f a couple more times
+ f(1)
+ f(1)
+
+ # Flush the .pyc files
+ shutil.rmtree(dir_name)
+ os.mkdir(dir_name)
+ # Now modify the module where f is stored, modifying f
+ content = 'def f(x):\n print("x=%s" % x)\n return x\n'
+ with open(filename, 'w') as module_file:
+ module_file.write(content)
+
+ # And call f more times prior to reloading: the cache should not be
+ # invalidated at this point as the active function definition has not
+ # changed in memory yet.
+ f(1)
+ f(1)
+
+ # Now reload
+ sys.stdout.write('Reloading\n')
+ sys.modules.pop('tmp_joblib_')
+ import tmp_joblib_ as tmp
+ f = memory.cache(tmp.f)
+
+ # And call f more times
+ f(1)
+ f(1)
+
+ out, err = capsys.readouterr()
+ assert out == '1\n2\nReloading\nx=1\n'
+
+
+def _function_to_cache(a, b):
+ # Just a place holder function to be mutated by tests
+ pass
+
+
+def _sum(a, b):
+ return a + b
+
+
+def _product(a, b):
+ return a * b
+
+
+def test_memory_in_memory_function_code_change(tmpdir):
+ _function_to_cache.__code__ = _sum.__code__
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ f = memory.cache(_function_to_cache)
+
+ assert f(1, 2) == 3
+ assert f(1, 2) == 3
+
+ with warns(JobLibCollisionWarning):
+ # Check that inline function modification triggers a cache invalidation
+ _function_to_cache.__code__ = _product.__code__
+ assert f(1, 2) == 2
+ assert f(1, 2) == 2
+
+
+def test_clear_memory_with_none_location():
+ memory = Memory(location=None)
+ memory.clear()
+
+
+def func_with_kwonly_args(a, b, *, kw1='kw1', kw2='kw2'):
+ return a, b, kw1, kw2
+
+
+def func_with_signature(a: int, b: float) -> float:
+ return a + b
+
+
+def test_memory_func_with_kwonly_args(tmpdir):
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ func_cached = memory.cache(func_with_kwonly_args)
+
+ assert func_cached(1, 2, kw1=3) == (1, 2, 3, 'kw2')
+
+ # Making sure that providing a keyword-only argument by
+ # position raises an exception
+ with raises(ValueError) as excinfo:
+ func_cached(1, 2, 3, kw2=4)
+ excinfo.match("Keyword-only parameter 'kw1' was passed as positional "
+ "parameter")
+
+ # Keyword-only parameter passed by position with cached call
+ # should still raise ValueError
+ func_cached(1, 2, kw1=3, kw2=4)
+
+ with raises(ValueError) as excinfo:
+ func_cached(1, 2, 3, kw2=4)
+ excinfo.match("Keyword-only parameter 'kw1' was passed as positional "
+ "parameter")
+
+ # Test 'ignore' parameter
+ func_cached = memory.cache(func_with_kwonly_args, ignore=['kw2'])
+ assert func_cached(1, 2, kw1=3, kw2=4) == (1, 2, 3, 4)
+ assert func_cached(1, 2, kw1=3, kw2='ignored') == (1, 2, 3, 4)
+
+
+def test_memory_func_with_signature(tmpdir):
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ func_cached = memory.cache(func_with_signature)
+
+ assert func_cached(1, 2.) == 3.
+
+
+def _setup_toy_cache(tmpdir, num_inputs=10):
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+
+ @memory.cache()
+ def get_1000_bytes(arg):
+ return 'a' * 1000
+
+ inputs = list(range(num_inputs))
+ for arg in inputs:
+ get_1000_bytes(arg)
+
+ func_id = _build_func_identifier(get_1000_bytes)
+ hash_dirnames = [get_1000_bytes._get_output_identifiers(arg)[1]
+ for arg in inputs]
+
+ full_hashdirs = [os.path.join(get_1000_bytes.store_backend.location,
+ func_id, dirname)
+ for dirname in hash_dirnames]
+ return memory, full_hashdirs, get_1000_bytes
+
+
+def test__get_items(tmpdir):
+ memory, expected_hash_dirs, _ = _setup_toy_cache(tmpdir)
+ items = memory.store_backend.get_items()
+ hash_dirs = [ci.path for ci in items]
+ assert set(hash_dirs) == set(expected_hash_dirs)
+
+ def get_files_size(directory):
+ full_paths = [os.path.join(directory, fn)
+ for fn in os.listdir(directory)]
+ return sum(os.path.getsize(fp) for fp in full_paths)
+
+ expected_hash_cache_sizes = [get_files_size(hash_dir)
+ for hash_dir in hash_dirs]
+ hash_cache_sizes = [ci.size for ci in items]
+ assert hash_cache_sizes == expected_hash_cache_sizes
+
+ output_filenames = [os.path.join(hash_dir, 'output.pkl')
+ for hash_dir in hash_dirs]
+
+ expected_last_accesses = [
+ datetime.datetime.fromtimestamp(os.path.getatime(fn))
+ for fn in output_filenames]
+ last_accesses = [ci.last_access for ci in items]
+ assert last_accesses == expected_last_accesses
+
+
+def test__get_items_to_delete(tmpdir):
+ memory, expected_hash_cachedirs, _ = _setup_toy_cache(tmpdir)
+ items = memory.store_backend.get_items()
+ # bytes_limit set to keep only one cache item (each hash cache
+ # folder is about 1000 bytes + metadata)
+ items_to_delete = memory.store_backend._get_items_to_delete('2K')
+ nb_hashes = len(expected_hash_cachedirs)
+ assert set.issubset(set(items_to_delete), set(items))
+ assert len(items_to_delete) == nb_hashes - 1
+
+ # Sanity check bytes_limit=2048 is the same as bytes_limit='2K'
+ items_to_delete_2048b = memory.store_backend._get_items_to_delete(2048)
+ assert sorted(items_to_delete) == sorted(items_to_delete_2048b)
+
+ # bytes_limit greater than the size of the cache
+ items_to_delete_empty = memory.store_backend._get_items_to_delete('1M')
+ assert items_to_delete_empty == []
+
+ # All the cache items need to be deleted
+ bytes_limit_too_small = 500
+ items_to_delete_500b = memory.store_backend._get_items_to_delete(
+ bytes_limit_too_small)
+ assert set(items_to_delete_500b), set(items)
+
+ # Test LRU property: surviving cache items should all have a more
+ # recent last_access that the ones that have been deleted
+ items_to_delete_6000b = memory.store_backend._get_items_to_delete(6000)
+ surviving_items = set(items).difference(items_to_delete_6000b)
+
+ assert (max(ci.last_access for ci in items_to_delete_6000b) <=
+ min(ci.last_access for ci in surviving_items))
+
+
+def test_memory_reduce_size(tmpdir):
+ memory, _, _ = _setup_toy_cache(tmpdir)
+ ref_cache_items = memory.store_backend.get_items()
+
+ # By default memory.bytes_limit is None and reduce_size is a noop
+ memory.reduce_size()
+ cache_items = memory.store_backend.get_items()
+ assert sorted(ref_cache_items) == sorted(cache_items)
+
+ # No cache items deleted if bytes_limit greater than the size of
+ # the cache
+ memory.bytes_limit = '1M'
+ memory.reduce_size()
+ cache_items = memory.store_backend.get_items()
+ assert sorted(ref_cache_items) == sorted(cache_items)
+
+ # bytes_limit is set so that only two cache items are kept
+ memory.bytes_limit = '3K'
+ memory.reduce_size()
+ cache_items = memory.store_backend.get_items()
+ assert set.issubset(set(cache_items), set(ref_cache_items))
+ assert len(cache_items) == 2
+
+ # bytes_limit set so that no cache item is kept
+ bytes_limit_too_small = 500
+ memory.bytes_limit = bytes_limit_too_small
+ memory.reduce_size()
+ cache_items = memory.store_backend.get_items()
+ assert cache_items == []
+
+
+def test_memory_clear(tmpdir):
+ memory, _, g = _setup_toy_cache(tmpdir)
+ memory.clear()
+
+ assert os.listdir(memory.store_backend.location) == []
+
+ # Check that the cache for functions hash is also reset.
+ assert not g._check_previous_func_code(stacklevel=4)
+
+
+def fast_func_with_complex_output():
+ complex_obj = ['a' * 1000] * 1000
+ return complex_obj
+
+
+def fast_func_with_conditional_complex_output(complex_output=True):
+ complex_obj = {str(i): i for i in range(int(1e5))}
+ return complex_obj if complex_output else 'simple output'
+
+
+@with_multiprocessing
+def test_cached_function_race_condition_when_persisting_output(tmpdir, capfd):
+ # Test race condition where multiple processes are writing into
+ # the same output.pkl. See
+ # https://github.com/joblib/joblib/issues/490 for more details.
+ memory = Memory(location=tmpdir.strpath)
+ func_cached = memory.cache(fast_func_with_complex_output)
+
+ Parallel(n_jobs=2)(delayed(func_cached)() for i in range(3))
+
+ stdout, stderr = capfd.readouterr()
+
+ # Checking both stdout and stderr (ongoing PR #434 may change
+ # logging destination) to make sure there is no exception while
+ # loading the results
+ exception_msg = 'Exception while loading results'
+ assert exception_msg not in stdout
+ assert exception_msg not in stderr
+
+
+@with_multiprocessing
+def test_cached_function_race_condition_when_persisting_output_2(tmpdir,
+ capfd):
+ # Test race condition in first attempt at solving
+ # https://github.com/joblib/joblib/issues/490. The race condition
+ # was due to the delay between seeing the cache directory created
+ # (interpreted as the result being cached) and the output.pkl being
+ # pickled.
+ memory = Memory(location=tmpdir.strpath)
+ func_cached = memory.cache(fast_func_with_conditional_complex_output)
+
+ Parallel(n_jobs=2)(delayed(func_cached)(True if i % 2 == 0 else False)
+ for i in range(3))
+
+ stdout, stderr = capfd.readouterr()
+
+ # Checking both stdout and stderr (ongoing PR #434 may change
+ # logging destination) to make sure there is no exception while
+ # loading the results
+ exception_msg = 'Exception while loading results'
+ assert exception_msg not in stdout
+ assert exception_msg not in stderr
+
+
+def test_memory_recomputes_after_an_error_while_loading_results(
+ tmpdir, monkeypatch):
+ memory = Memory(location=tmpdir.strpath)
+
+ def func(arg):
+ # This makes sure that the timestamp returned by two calls of
+ # func are different. This is needed on Windows where
+ # time.time resolution may not be accurate enough
+ time.sleep(0.01)
+ return arg, time.time()
+
+ cached_func = memory.cache(func)
+ input_arg = 'arg'
+ arg, timestamp = cached_func(input_arg)
+
+ # Make sure the function is correctly cached
+ assert arg == input_arg
+
+ # Corrupting output.pkl to make sure that an error happens when
+ # loading the cached result
+ corrupt_single_cache_item(memory)
+
+ # Make sure that corrupting the file causes recomputation and that
+ # a warning is issued.
+ recorded_warnings = monkeypatch_cached_func_warn(cached_func, monkeypatch)
+ recomputed_arg, recomputed_timestamp = cached_func(arg)
+ assert len(recorded_warnings) == 1
+ exception_msg = 'Exception while loading results'
+ assert exception_msg in recorded_warnings[0]
+ assert recomputed_arg == arg
+ assert recomputed_timestamp > timestamp
+
+ # Corrupting output.pkl to make sure that an error happens when
+ # loading the cached result
+ corrupt_single_cache_item(memory)
+ reference = cached_func.call_and_shelve(arg)
+ try:
+ reference.get()
+ raise AssertionError(
+ "It normally not possible to load a corrupted"
+ " MemorizedResult"
+ )
+ except KeyError as e:
+ message = "is corrupted"
+ assert message in str(e.args)
+
+
+class IncompleteStoreBackend(StoreBackendBase):
+ """This backend cannot be instantiated and should raise a TypeError."""
+ pass
+
+
+class DummyStoreBackend(StoreBackendBase):
+ """A dummy store backend that does nothing."""
+
+ def _open_item(self, *args, **kwargs):
+ """Open an item on store."""
+ "Does nothing"
+
+ def _item_exists(self, location):
+ """Check if an item location exists."""
+ "Does nothing"
+
+ def _move_item(self, src, dst):
+ """Move an item from src to dst in store."""
+ "Does nothing"
+
+ def create_location(self, location):
+ """Create location on store."""
+ "Does nothing"
+
+ def exists(self, obj):
+ """Check if an object exists in the store"""
+ return False
+
+ def clear_location(self, obj):
+ """Clear object on store"""
+ "Does nothing"
+
+ def get_items(self):
+ """Returns the whole list of items available in cache."""
+ return []
+
+ def configure(self, location, *args, **kwargs):
+ """Configure the store"""
+ "Does nothing"
+
+
+@parametrize("invalid_prefix", [None, dict(), list()])
+def test_register_invalid_store_backends_key(invalid_prefix):
+ # verify the right exceptions are raised when passing a wrong backend key.
+ with raises(ValueError) as excinfo:
+ register_store_backend(invalid_prefix, None)
+ excinfo.match(r'Store backend name should be a string*')
+
+
+def test_register_invalid_store_backends_object():
+ # verify the right exceptions are raised when passing a wrong backend
+ # object.
+ with raises(ValueError) as excinfo:
+ register_store_backend("fs", None)
+ excinfo.match(r'Store backend should inherit StoreBackendBase*')
+
+
+def test_memory_default_store_backend():
+ # test an unknown backend falls back into a FileSystemStoreBackend
+ with raises(TypeError) as excinfo:
+ Memory(location='/tmp/joblib', backend='unknown')
+ excinfo.match(r"Unknown location*")
+
+
+def test_warning_on_unknown_location_type():
+ class NonSupportedLocationClass:
+ pass
+ unsupported_location = NonSupportedLocationClass()
+
+ with warns(UserWarning) as warninfo:
+ _store_backend_factory("local", location=unsupported_location)
+
+ expected_mesage = ("Instantiating a backend using a "
+ "NonSupportedLocationClass as a location is not "
+ "supported by joblib")
+ assert expected_mesage in str(warninfo[0].message)
+
+
+def test_instanciate_incomplete_store_backend():
+ # Verify that registering an external incomplete store backend raises an
+ # exception when one tries to instantiate it.
+ backend_name = "isb"
+ register_store_backend(backend_name, IncompleteStoreBackend)
+ assert (backend_name, IncompleteStoreBackend) in _STORE_BACKENDS.items()
+ with raises(TypeError) as excinfo:
+ _store_backend_factory(backend_name, "fake_location")
+ excinfo.match(r"Can't instantiate abstract class "
+ "IncompleteStoreBackend with abstract methods*")
+
+
+def test_dummy_store_backend():
+ # Verify that registering an external store backend works.
+
+ backend_name = "dsb"
+ register_store_backend(backend_name, DummyStoreBackend)
+ assert (backend_name, DummyStoreBackend) in _STORE_BACKENDS.items()
+
+ backend_obj = _store_backend_factory(backend_name, "dummy_location")
+ assert isinstance(backend_obj, DummyStoreBackend)
+
+
+def test_instanciate_store_backend_with_pathlib_path():
+ # Instantiate a FileSystemStoreBackend using a pathlib.Path object
+ path = pathlib.Path("some_folder")
+ backend_obj = _store_backend_factory("local", path)
+ assert backend_obj.location == "some_folder"
+
+
+def test_filesystem_store_backend_repr(tmpdir):
+ # Verify string representation of a filesystem store backend.
+
+ repr_pattern = 'FileSystemStoreBackend(location="{location}")'
+ backend = FileSystemStoreBackend()
+ assert backend.location is None
+
+ repr(backend) # Should not raise an exception
+
+ assert str(backend) == repr_pattern.format(location=None)
+
+ # backend location is passed explicitly via the configure method (called
+ # by the internal _store_backend_factory function)
+ backend.configure(tmpdir.strpath)
+
+ assert str(backend) == repr_pattern.format(location=tmpdir.strpath)
+
+ repr(backend) # Should not raise an exception
+
+
+def test_memory_objects_repr(tmpdir):
+ # Verify printable reprs of MemorizedResult, MemorizedFunc and Memory.
+
+ def my_func(a, b):
+ return a + b
+
+ memory = Memory(location=tmpdir.strpath, verbose=0)
+ memorized_func = memory.cache(my_func)
+
+ memorized_func_repr = 'MemorizedFunc(func={func}, location={location})'
+
+ assert str(memorized_func) == memorized_func_repr.format(
+ func=my_func,
+ location=memory.store_backend.location)
+
+ memorized_result = memorized_func.call_and_shelve(42, 42)
+
+ memorized_result_repr = ('MemorizedResult(location="{location}", '
+ 'func="{func}", args_id="{args_id}")')
+
+ assert str(memorized_result) == memorized_result_repr.format(
+ location=memory.store_backend.location,
+ func=memorized_result.func_id,
+ args_id=memorized_result.args_id)
+
+ assert str(memory) == 'Memory(location={location})'.format(
+ location=memory.store_backend.location)
+
+
+def test_memorized_result_pickle(tmpdir):
+ # Verify a MemoryResult object can be pickled/depickled. Non regression
+ # test introduced following issue
+ # https://github.com/joblib/joblib/issues/747
+
+ memory = Memory(location=tmpdir.strpath)
+
+ @memory.cache
+ def g(x):
+ return x**2
+
+ memorized_result = g.call_and_shelve(4)
+ memorized_result_pickle = pickle.dumps(memorized_result)
+ memorized_result_loads = pickle.loads(memorized_result_pickle)
+
+ assert memorized_result.store_backend.location == \
+ memorized_result_loads.store_backend.location
+ assert memorized_result.func == memorized_result_loads.func
+ assert memorized_result.args_id == memorized_result_loads.args_id
+ assert str(memorized_result) == str(memorized_result_loads)
+
+
+def compare(left, right, ignored_attrs=None):
+ if ignored_attrs is None:
+ ignored_attrs = []
+
+ left_vars = vars(left)
+ right_vars = vars(right)
+ assert set(left_vars.keys()) == set(right_vars.keys())
+ for attr in left_vars.keys():
+ if attr in ignored_attrs:
+ continue
+ assert left_vars[attr] == right_vars[attr]
+
+
+@pytest.mark.parametrize('memory_kwargs',
+ [{'compress': 3, 'verbose': 2},
+ {'mmap_mode': 'r', 'verbose': 5, 'bytes_limit': 1e6,
+ 'backend_options': {'parameter': 'unused'}}])
+def test_memory_pickle_dump_load(tmpdir, memory_kwargs):
+ memory = Memory(location=tmpdir.strpath, **memory_kwargs)
+
+ memory_reloaded = pickle.loads(pickle.dumps(memory))
+
+ # Compare Memory instance before and after pickle roundtrip
+ compare(memory.store_backend, memory_reloaded.store_backend)
+ compare(memory, memory_reloaded,
+ ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id']))
+ assert hash(memory) == hash(memory_reloaded)
+
+ func_cached = memory.cache(f)
+
+ func_cached_reloaded = pickle.loads(pickle.dumps(func_cached))
+
+ # Compare MemorizedFunc instance before/after pickle roundtrip
+ compare(func_cached.store_backend, func_cached_reloaded.store_backend)
+ compare(func_cached, func_cached_reloaded,
+ ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id']))
+ assert hash(func_cached) == hash(func_cached_reloaded)
+
+ # Compare MemorizedResult instance before/after pickle roundtrip
+ memorized_result = func_cached.call_and_shelve(1)
+ memorized_result_reloaded = pickle.loads(pickle.dumps(memorized_result))
+
+ compare(memorized_result.store_backend,
+ memorized_result_reloaded.store_backend)
+ compare(memorized_result, memorized_result_reloaded,
+ ignored_attrs=set(['store_backend', 'timestamp', '_func_code_id']))
+ assert hash(memorized_result) == hash(memorized_result_reloaded)
diff --git a/runtime/Lib/site-packages/joblib/test/test_missing_multiprocessing.py b/runtime/Lib/site-packages/joblib/test/test_missing_multiprocessing.py
new file mode 100644
index 0000000000000000000000000000000000000000..251925ced5208b4aaf09d9aab305eb44c7102818
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_missing_multiprocessing.py
@@ -0,0 +1,32 @@
+"""
+Pyodide and other single-threaded Python builds will be missing the
+_multiprocessing module. Test that joblib still works in this environment.
+"""
+
+import os
+import subprocess
+import sys
+
+
+def test_missing_multiprocessing(tmp_path):
+ """
+ Test that import joblib works even if _multiprocessing is missing.
+
+ pytest has already imported everything from joblib. The most reasonable way
+ to test importing joblib with modified environment is to invoke a separate
+ Python process. This also ensures that we don't break other tests by
+ importing a bad `_multiprocessing` module.
+ """
+ (tmp_path / "_multiprocessing.py").write_text(
+ 'raise ImportError("No _multiprocessing module!")'
+ )
+ env = dict(os.environ)
+ # For subprocess, use current sys.path with our custom version of
+ # multiprocessing inserted.
+ env["PYTHONPATH"] = ":".join([str(tmp_path)] + sys.path)
+ subprocess.check_call(
+ [sys.executable, "-c",
+ "import joblib, math; "
+ "joblib.Parallel(n_jobs=1)("
+ "joblib.delayed(math.sqrt)(i**2) for i in range(10))"
+ ], env=env)
diff --git a/runtime/Lib/site-packages/joblib/test/test_module.py b/runtime/Lib/site-packages/joblib/test/test_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2257a4142d79996f3d299cb820927ae48a05810
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_module.py
@@ -0,0 +1,53 @@
+import sys
+import joblib
+from joblib.testing import check_subprocess_call
+from joblib.test.common import with_multiprocessing
+
+
+def test_version():
+ assert hasattr(joblib, '__version__'), (
+ "There are no __version__ argument on the joblib module")
+
+
+@with_multiprocessing
+def test_no_start_method_side_effect_on_import():
+ # check that importing joblib does not implicitly set the global
+ # start_method for multiprocessing.
+ code = """if True:
+ import joblib
+ import multiprocessing as mp
+ # The following line would raise RuntimeError if the
+ # start_method is already set.
+ mp.set_start_method("loky")
+ """
+ check_subprocess_call([sys.executable, '-c', code])
+
+
+@with_multiprocessing
+def test_no_semaphore_tracker_on_import():
+ # check that importing joblib does not implicitly spawn a resource tracker
+ # or a semaphore tracker
+ code = """if True:
+ import joblib
+ from multiprocessing import semaphore_tracker
+ # The following line would raise RuntimeError if the
+ # start_method is already set.
+ msg = "multiprocessing.semaphore_tracker has been spawned on import"
+ assert semaphore_tracker._semaphore_tracker._fd is None, msg"""
+ if sys.version_info >= (3, 8):
+ # semaphore_tracker was renamed in Python 3.8:
+ code = code.replace("semaphore_tracker", "resource_tracker")
+ check_subprocess_call([sys.executable, '-c', code])
+
+
+@with_multiprocessing
+def test_no_resource_tracker_on_import():
+ code = """if True:
+ import joblib
+ from joblib.externals.loky.backend import resource_tracker
+ # The following line would raise RuntimeError if the
+ # start_method is already set.
+ msg = "loky.resource_tracker has been spawned on import"
+ assert resource_tracker._resource_tracker._fd is None, msg
+ """
+ check_subprocess_call([sys.executable, '-c', code])
diff --git a/runtime/Lib/site-packages/joblib/test/test_my_exceptions.py b/runtime/Lib/site-packages/joblib/test/test_my_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..272bc17c693fed171e24324de2a02287d94e12a2
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_my_exceptions.py
@@ -0,0 +1,60 @@
+"""
+Test my automatically generate exceptions
+"""
+from joblib.my_exceptions import (
+ JoblibException, JoblibNameError, _mk_exception)
+
+
+class CustomException(Exception):
+ def __init__(self, a, b, c, d):
+ self.a, self.b, self.c, self.d = a, b, c, d
+
+
+class CustomException2(Exception):
+ """A custom exception with a .args attribute
+
+ Just to check that the JoblibException created from it
+ has it args set correctly
+ """
+ def __init__(self, a, *args):
+ self.a = a
+ self.args = args
+
+
+def test_inheritance():
+ assert isinstance(JoblibNameError(), NameError)
+ assert isinstance(JoblibNameError(), JoblibException)
+ assert (JoblibNameError is _mk_exception(NameError)[0])
+
+
+def test_inheritance_special_cases():
+ # _mk_exception should transform Exception to JoblibException
+ assert (_mk_exception(Exception)[0] is JoblibException)
+
+ # Subclasses of JoblibException should be mapped to
+ # them-selves by _mk_exception
+ assert (_mk_exception(JoblibException)[0] is JoblibException)
+
+ # Non-inheritable exception classes should be mapped to
+ # JoblibException by _mk_exception. That can happen with classes
+ # generated with SWIG. See
+ # https://github.com/joblib/joblib/issues/269 for a concrete
+ # example.
+ non_inheritable_classes = [type(lambda: None), bool]
+ for exception in non_inheritable_classes:
+ assert (_mk_exception(exception)[0] is JoblibException)
+
+
+def test__mk_exception():
+ # Check that _mk_exception works on a bunch of different exceptions
+ for klass in (Exception, TypeError, SyntaxError, ValueError,
+ ImportError, CustomException, CustomException2):
+ message = 'This message should be in the exception repr'
+ exc = _mk_exception(klass)[0](
+ message, 'some', 'other', 'args', 'that are not', 'in the repr')
+ exc_repr = repr(exc)
+
+ assert isinstance(exc, klass)
+ assert isinstance(exc, JoblibException)
+ assert exc.__class__.__name__ in exc_repr
+ assert message in exc_repr
diff --git a/runtime/Lib/site-packages/joblib/test/test_numpy_pickle.py b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9d1d5bdb33ac1b17109ae7902c682be79fc160d
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle.py
@@ -0,0 +1,1158 @@
+"""Test the numpy pickler as a replacement of the standard pickler."""
+
+import copy
+import os
+import random
+import re
+import io
+import sys
+import warnings
+import gzip
+import zlib
+import bz2
+import pickle
+import socket
+from contextlib import closing
+import mmap
+from pathlib import Path
+
+try:
+ import lzma
+except ImportError:
+ lzma = None
+
+import pytest
+
+from joblib.test.common import np, with_numpy, with_lz4, without_lz4
+from joblib.test.common import with_memory_profiler, memory_used
+from joblib.testing import parametrize, raises, warns
+
+# numpy_pickle is not a drop-in replacement of pickle, as it takes
+# filenames instead of open files as arguments.
+from joblib import numpy_pickle, register_compressor
+from joblib.test import data
+
+from joblib.numpy_pickle_utils import _IO_BUFFER_SIZE
+from joblib.numpy_pickle_utils import _detect_compressor
+from joblib.numpy_pickle_utils import _is_numpy_array_byte_order_mismatch
+from joblib.numpy_pickle_utils import _ensure_native_byte_order
+from joblib.compressor import (_COMPRESSORS, _LZ4_PREFIX, CompressorWrapper,
+ LZ4_NOT_INSTALLED_ERROR, BinaryZlibFile)
+
+
+###############################################################################
+# Define a list of standard types.
+# Borrowed from dill, initial author: Micheal McKerns:
+# http://dev.danse.us/trac/pathos/browser/dill/dill_test2.py
+
+typelist = []
+
+# testing types
+_none = None
+typelist.append(_none)
+_type = type
+typelist.append(_type)
+_bool = bool(1)
+typelist.append(_bool)
+_int = int(1)
+typelist.append(_int)
+_float = float(1)
+typelist.append(_float)
+_complex = complex(1)
+typelist.append(_complex)
+_string = str(1)
+typelist.append(_string)
+_tuple = ()
+typelist.append(_tuple)
+_list = []
+typelist.append(_list)
+_dict = {}
+typelist.append(_dict)
+_builtin = len
+typelist.append(_builtin)
+
+
+def _function(x):
+ yield x
+
+
+class _class:
+ def _method(self):
+ pass
+
+
+class _newclass(object):
+ def _method(self):
+ pass
+
+
+typelist.append(_function)
+typelist.append(_class)
+typelist.append(_newclass) #
+_instance = _class()
+typelist.append(_instance)
+_object = _newclass()
+typelist.append(_object) #
+
+
+###############################################################################
+# Tests
+
+@parametrize('compress', [0, 1])
+@parametrize('member', typelist)
+def test_standard_types(tmpdir, compress, member):
+ # Test pickling and saving with standard types.
+ filename = tmpdir.join('test.pkl').strpath
+ numpy_pickle.dump(member, filename, compress=compress)
+ _member = numpy_pickle.load(filename)
+ # We compare the pickled instance to the reloaded one only if it
+ # can be compared to a copied one
+ if member == copy.deepcopy(member):
+ assert member == _member
+
+
+def test_value_error():
+ # Test inverting the input arguments to dump
+ with raises(ValueError):
+ numpy_pickle.dump('foo', dict())
+
+
+@parametrize('wrong_compress', [-1, 10, dict()])
+def test_compress_level_error(wrong_compress):
+ # Verify that passing an invalid compress argument raises an error.
+ exception_msg = ('Non valid compress level given: '
+ '"{0}"'.format(wrong_compress))
+ with raises(ValueError) as excinfo:
+ numpy_pickle.dump('dummy', 'foo', compress=wrong_compress)
+ excinfo.match(exception_msg)
+
+
+@with_numpy
+@parametrize('compress', [False, True, 0, 3, 'zlib'])
+def test_numpy_persistence(tmpdir, compress):
+ filename = tmpdir.join('test.pkl').strpath
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample((10, 2))
+ # We use 'a.T' to have a non C-contiguous array.
+ for index, obj in enumerate(((a,), (a.T,), (a, a), [a, a, a])):
+ filenames = numpy_pickle.dump(obj, filename, compress=compress)
+
+ # All is cached in one file
+ assert len(filenames) == 1
+ # Check that only one file was created
+ assert filenames[0] == filename
+ # Check that this file does exist
+ assert os.path.exists(filenames[0])
+
+ # Unpickle the object
+ obj_ = numpy_pickle.load(filename)
+ # Check that the items are indeed arrays
+ for item in obj_:
+ assert isinstance(item, np.ndarray)
+ # And finally, check that all the values are equal.
+ np.testing.assert_array_equal(np.array(obj), np.array(obj_))
+
+ # Now test with an array subclass
+ obj = np.memmap(filename + 'mmap', mode='w+', shape=4, dtype=np.float64)
+ filenames = numpy_pickle.dump(obj, filename, compress=compress)
+ # All is cached in one file
+ assert len(filenames) == 1
+
+ obj_ = numpy_pickle.load(filename)
+ if (type(obj) is not np.memmap and
+ hasattr(obj, '__array_prepare__')):
+ # We don't reconstruct memmaps
+ assert isinstance(obj_, type(obj))
+
+ np.testing.assert_array_equal(obj_, obj)
+
+ # Test with an object containing multiple numpy arrays
+ obj = ComplexTestObject()
+ filenames = numpy_pickle.dump(obj, filename, compress=compress)
+ # All is cached in one file
+ assert len(filenames) == 1
+
+ obj_loaded = numpy_pickle.load(filename)
+ assert isinstance(obj_loaded, type(obj))
+ np.testing.assert_array_equal(obj_loaded.array_float, obj.array_float)
+ np.testing.assert_array_equal(obj_loaded.array_int, obj.array_int)
+ np.testing.assert_array_equal(obj_loaded.array_obj, obj.array_obj)
+
+
+@with_numpy
+def test_numpy_persistence_bufferred_array_compression(tmpdir):
+ big_array = np.ones((_IO_BUFFER_SIZE + 100), dtype=np.uint8)
+ filename = tmpdir.join('test.pkl').strpath
+ numpy_pickle.dump(big_array, filename, compress=True)
+ arr_reloaded = numpy_pickle.load(filename)
+
+ np.testing.assert_array_equal(big_array, arr_reloaded)
+
+
+@with_numpy
+def test_memmap_persistence(tmpdir):
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample(10)
+ filename = tmpdir.join('test1.pkl').strpath
+ numpy_pickle.dump(a, filename)
+ b = numpy_pickle.load(filename, mmap_mode='r')
+
+ assert isinstance(b, np.memmap)
+
+ # Test with an object containing multiple numpy arrays
+ filename = tmpdir.join('test2.pkl').strpath
+ obj = ComplexTestObject()
+ numpy_pickle.dump(obj, filename)
+ obj_loaded = numpy_pickle.load(filename, mmap_mode='r')
+ assert isinstance(obj_loaded, type(obj))
+ assert isinstance(obj_loaded.array_float, np.memmap)
+ assert not obj_loaded.array_float.flags.writeable
+ assert isinstance(obj_loaded.array_int, np.memmap)
+ assert not obj_loaded.array_int.flags.writeable
+ # Memory map not allowed for numpy object arrays
+ assert not isinstance(obj_loaded.array_obj, np.memmap)
+ np.testing.assert_array_equal(obj_loaded.array_float,
+ obj.array_float)
+ np.testing.assert_array_equal(obj_loaded.array_int,
+ obj.array_int)
+ np.testing.assert_array_equal(obj_loaded.array_obj,
+ obj.array_obj)
+
+ # Test we can write in memmapped arrays
+ obj_loaded = numpy_pickle.load(filename, mmap_mode='r+')
+ assert obj_loaded.array_float.flags.writeable
+ obj_loaded.array_float[0:10] = 10.0
+ assert obj_loaded.array_int.flags.writeable
+ obj_loaded.array_int[0:10] = 10
+
+ obj_reloaded = numpy_pickle.load(filename, mmap_mode='r')
+ np.testing.assert_array_equal(obj_reloaded.array_float,
+ obj_loaded.array_float)
+ np.testing.assert_array_equal(obj_reloaded.array_int,
+ obj_loaded.array_int)
+
+ # Test w+ mode is caught and the mode has switched to r+
+ numpy_pickle.load(filename, mmap_mode='w+')
+ assert obj_loaded.array_int.flags.writeable
+ assert obj_loaded.array_int.mode == 'r+'
+ assert obj_loaded.array_float.flags.writeable
+ assert obj_loaded.array_float.mode == 'r+'
+
+
+@with_numpy
+def test_memmap_persistence_mixed_dtypes(tmpdir):
+ # loading datastructures that have sub-arrays with dtype=object
+ # should not prevent memmapping on fixed size dtype sub-arrays.
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample(10)
+ b = np.array([1, 'b'], dtype=object)
+ construct = (a, b)
+ filename = tmpdir.join('test.pkl').strpath
+ numpy_pickle.dump(construct, filename)
+ a_clone, b_clone = numpy_pickle.load(filename, mmap_mode='r')
+
+ # the floating point array has been memory mapped
+ assert isinstance(a_clone, np.memmap)
+
+ # the object-dtype array has been loaded in memory
+ assert not isinstance(b_clone, np.memmap)
+
+
+@with_numpy
+def test_masked_array_persistence(tmpdir):
+ # The special-case picker fails, because saving masked_array
+ # not implemented, but it just delegates to the standard pickler.
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample(10)
+ a = np.ma.masked_greater(a, 0.5)
+ filename = tmpdir.join('test.pkl').strpath
+ numpy_pickle.dump(a, filename)
+ b = numpy_pickle.load(filename, mmap_mode='r')
+ assert isinstance(b, np.ma.masked_array)
+
+
+@with_numpy
+def test_compress_mmap_mode_warning(tmpdir):
+ # Test the warning in case of compress + mmap_mode
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample(10)
+ this_filename = tmpdir.join('test.pkl').strpath
+ numpy_pickle.dump(a, this_filename, compress=1)
+ with warns(UserWarning) as warninfo:
+ numpy_pickle.load(this_filename, mmap_mode='r+')
+ warninfo = [w.message for w in warninfo]
+ assert len(warninfo) == 1
+ assert (
+ str(warninfo[0]) ==
+ 'mmap_mode "r+" is not compatible with compressed '
+ f'file {this_filename}. "r+" flag will be ignored.'
+ )
+
+
+@with_numpy
+@parametrize('cache_size', [None, 0, 10])
+def test_cache_size_warning(tmpdir, cache_size):
+ # Check deprecation warning raised when cache size is not None
+ filename = tmpdir.join('test.pkl').strpath
+ rnd = np.random.RandomState(0)
+ a = rnd.random_sample((10, 2))
+
+ warnings.simplefilter("always")
+ with warnings.catch_warnings(record=True) as warninfo:
+ numpy_pickle.dump(a, filename, cache_size=cache_size)
+ expected_nb_warnings = 1 if cache_size is not None else 0
+ assert len(warninfo) == expected_nb_warnings
+ for w in warninfo:
+ assert w.category == DeprecationWarning
+ assert (str(w.message) ==
+ "Please do not set 'cache_size' in joblib.dump, this "
+ "parameter has no effect and will be removed. You "
+ "used 'cache_size={0}'".format(cache_size))
+
+
+@with_numpy
+@with_memory_profiler
+@parametrize('compress', [True, False])
+def test_memory_usage(tmpdir, compress):
+ # Verify memory stays within expected bounds.
+ filename = tmpdir.join('test.pkl').strpath
+ small_array = np.ones((10, 10))
+ big_array = np.ones(shape=100 * int(1e6), dtype=np.uint8)
+
+ for obj in (small_array, big_array):
+ size = obj.nbytes / 1e6
+ obj_filename = filename + str(np.random.randint(0, 1000))
+ mem_used = memory_used(numpy_pickle.dump,
+ obj, obj_filename, compress=compress)
+
+ # The memory used to dump the object shouldn't exceed the buffer
+ # size used to write array chunks (16MB).
+ write_buf_size = _IO_BUFFER_SIZE + 16 * 1024 ** 2 / 1e6
+ assert mem_used <= write_buf_size
+
+ mem_used = memory_used(numpy_pickle.load, obj_filename)
+ # memory used should be less than array size + buffer size used to
+ # read the array chunk by chunk.
+ read_buf_size = 32 + _IO_BUFFER_SIZE # MiB
+ assert mem_used < size + read_buf_size
+
+
+@with_numpy
+def test_compressed_pickle_dump_and_load(tmpdir):
+ expected_list = [np.arange(5, dtype=np.dtype('i8')),
+ np.arange(5, dtype=np.dtype('f8')),
+ np.array([1, 'abc', {'a': 1, 'b': 2}], dtype='O'),
+ np.arange(256, dtype=np.uint8).tobytes(),
+ u"C'est l'\xe9t\xe9 !"]
+
+ fname = tmpdir.join('temp.pkl.gz').strpath
+
+ dumped_filenames = numpy_pickle.dump(expected_list, fname, compress=1)
+ assert len(dumped_filenames) == 1
+ result_list = numpy_pickle.load(fname)
+ for result, expected in zip(result_list, expected_list):
+ if isinstance(expected, np.ndarray):
+ expected = _ensure_native_byte_order(expected)
+ assert result.dtype == expected.dtype
+ np.testing.assert_equal(result, expected)
+ else:
+ assert result == expected
+
+
+def _check_pickle(filename, expected_list, mmap_mode=None):
+ """Helper function to test joblib pickle content.
+
+ Note: currently only pickles containing an iterable are supported
+ by this function.
+ """
+ version_match = re.match(r'.+py(\d)(\d).+', filename)
+ py_version_used_for_writing = int(version_match.group(1))
+
+ py_version_to_default_pickle_protocol = {2: 2, 3: 3}
+ pickle_reading_protocol = py_version_to_default_pickle_protocol.get(3, 4)
+ pickle_writing_protocol = py_version_to_default_pickle_protocol.get(
+ py_version_used_for_writing, 4)
+ if pickle_reading_protocol >= pickle_writing_protocol:
+ try:
+ with warnings.catch_warnings(record=True) as warninfo:
+ warnings.simplefilter('always')
+ warnings.filterwarnings(
+ 'ignore', module='numpy',
+ message='The compiler package is deprecated')
+ result_list = numpy_pickle.load(filename, mmap_mode=mmap_mode)
+ filename_base = os.path.basename(filename)
+ expected_nb_deprecation_warnings = 1 if (
+ "_0.9" in filename_base or "_0.8.4" in filename_base) else 0
+
+ expected_nb_user_warnings = 3 if (
+ re.search("_0.1.+.pkl$", filename_base) and
+ mmap_mode is not None) else 0
+ expected_nb_warnings = \
+ expected_nb_deprecation_warnings + expected_nb_user_warnings
+ assert len(warninfo) == expected_nb_warnings
+
+ deprecation_warnings = [
+ w for w in warninfo if issubclass(
+ w.category, DeprecationWarning)]
+ user_warnings = [
+ w for w in warninfo if issubclass(
+ w.category, UserWarning)]
+ for w in deprecation_warnings:
+ assert (str(w.message) ==
+ "The file '{0}' has been generated with a joblib "
+ "version less than 0.10. Please regenerate this "
+ "pickle file.".format(filename))
+
+ for w in user_warnings:
+ escaped_filename = re.escape(filename)
+ assert re.search(
+ f"memmapped.+{escaped_filename}.+segmentation fault",
+ str(w.message))
+
+ for result, expected in zip(result_list, expected_list):
+ if isinstance(expected, np.ndarray):
+ expected = _ensure_native_byte_order(expected)
+ assert result.dtype == expected.dtype
+ np.testing.assert_equal(result, expected)
+ else:
+ assert result == expected
+ except Exception as exc:
+ # When trying to read with python 3 a pickle generated
+ # with python 2 we expect a user-friendly error
+ if py_version_used_for_writing == 2:
+ assert isinstance(exc, ValueError)
+ message = ('You may be trying to read with '
+ 'python 3 a joblib pickle generated with python 2.')
+ assert message in str(exc)
+ elif filename.endswith('.lz4') and with_lz4.args[0]:
+ assert isinstance(exc, ValueError)
+ assert LZ4_NOT_INSTALLED_ERROR in str(exc)
+ else:
+ raise
+ else:
+ # Pickle protocol used for writing is too high. We expect a
+ # "unsupported pickle protocol" error message
+ try:
+ numpy_pickle.load(filename)
+ raise AssertionError('Numpy pickle loading should '
+ 'have raised a ValueError exception')
+ except ValueError as e:
+ message = 'unsupported pickle protocol: {0}'.format(
+ pickle_writing_protocol)
+ assert message in str(e.args)
+
+
+@with_numpy
+def test_joblib_pickle_across_python_versions():
+ # We need to be specific about dtypes in particular endianness
+ # because the pickles can be generated on one architecture and
+ # the tests run on another one. See
+ # https://github.com/joblib/joblib/issues/279.
+ expected_list = [np.arange(5, dtype=np.dtype('i8'), ('', '>f8')]),
+ np.arange(3, dtype=np.dtype('>i8')),
+ np.arange(3, dtype=np.dtype('>f8'))]
+
+ # Verify the byteorder mismatch is correctly detected.
+ for array in be_arrays:
+ if sys.byteorder == 'big':
+ assert not _is_numpy_array_byte_order_mismatch(array)
+ else:
+ assert _is_numpy_array_byte_order_mismatch(array)
+ converted = _ensure_native_byte_order(array)
+ if converted.dtype.fields:
+ for f in converted.dtype.fields.values():
+ f[0].byteorder == '='
+ else:
+ assert converted.dtype.byteorder == "="
+
+ # List of numpy arrays with little endian byteorder.
+ le_arrays = [np.array([(1, 2.0), (3, 4.0)],
+ dtype=[('', ' size
+ np.testing.assert_array_equal(obj, memmaps)
+
+
+def test_register_compressor(tmpdir):
+ # Check that registering compressor file works.
+ compressor_name = 'test-name'
+ compressor_prefix = 'test-prefix'
+
+ class BinaryCompressorTestFile(io.BufferedIOBase):
+ pass
+
+ class BinaryCompressorTestWrapper(CompressorWrapper):
+
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=BinaryCompressorTestFile,
+ prefix=compressor_prefix)
+
+ register_compressor(compressor_name, BinaryCompressorTestWrapper())
+
+ assert (_COMPRESSORS[compressor_name].fileobj_factory ==
+ BinaryCompressorTestFile)
+ assert _COMPRESSORS[compressor_name].prefix == compressor_prefix
+
+ # Remove this dummy compressor file from extra compressors because other
+ # tests might fail because of this
+ _COMPRESSORS.pop(compressor_name)
+
+
+@parametrize('invalid_name', [1, (), {}])
+def test_register_compressor_invalid_name(invalid_name):
+ # Test that registering an invalid compressor name is not allowed.
+ with raises(ValueError) as excinfo:
+ register_compressor(invalid_name, None)
+ excinfo.match("Compressor name should be a string")
+
+
+def test_register_compressor_invalid_fileobj():
+ # Test that registering an invalid file object is not allowed.
+
+ class InvalidFileObject():
+ pass
+
+ class InvalidFileObjectWrapper(CompressorWrapper):
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=InvalidFileObject,
+ prefix=b'prefix')
+
+ with raises(ValueError) as excinfo:
+ register_compressor('invalid', InvalidFileObjectWrapper())
+
+ excinfo.match("Compressor 'fileobj_factory' attribute should implement "
+ "the file object interface")
+
+
+class AnotherZlibCompressorWrapper(CompressorWrapper):
+
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=BinaryZlibFile, prefix=b'prefix')
+
+
+class StandardLibGzipCompressorWrapper(CompressorWrapper):
+
+ def __init__(self):
+ CompressorWrapper.__init__(self, obj=gzip.GzipFile, prefix=b'prefix')
+
+
+def test_register_compressor_already_registered():
+ # Test registration of existing compressor files.
+ compressor_name = 'test-name'
+
+ # register a test compressor
+ register_compressor(compressor_name, AnotherZlibCompressorWrapper())
+
+ with raises(ValueError) as excinfo:
+ register_compressor(compressor_name,
+ StandardLibGzipCompressorWrapper())
+ excinfo.match("Compressor '{}' already registered."
+ .format(compressor_name))
+
+ register_compressor(compressor_name, StandardLibGzipCompressorWrapper(),
+ force=True)
+
+ assert compressor_name in _COMPRESSORS
+ assert _COMPRESSORS[compressor_name].fileobj_factory == gzip.GzipFile
+
+ # Remove this dummy compressor file from extra compressors because other
+ # tests might fail because of this
+ _COMPRESSORS.pop(compressor_name)
+
+
+@with_lz4
+def test_lz4_compression(tmpdir):
+ # Check that lz4 can be used when dependency is available.
+ import lz4.frame
+ compressor = 'lz4'
+ assert compressor in _COMPRESSORS
+ assert _COMPRESSORS[compressor].fileobj_factory == lz4.frame.LZ4FrameFile
+
+ fname = tmpdir.join('test.pkl').strpath
+ data = 'test data'
+ numpy_pickle.dump(data, fname, compress=compressor)
+
+ with open(fname, 'rb') as f:
+ assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX
+ assert numpy_pickle.load(fname) == data
+
+ # Test that LZ4 is applied based on file extension
+ numpy_pickle.dump(data, fname + '.lz4')
+ with open(fname, 'rb') as f:
+ assert f.read(len(_LZ4_PREFIX)) == _LZ4_PREFIX
+ assert numpy_pickle.load(fname) == data
+
+
+@without_lz4
+def test_lz4_compression_without_lz4(tmpdir):
+ # Check that lz4 cannot be used when dependency is not available.
+ fname = tmpdir.join('test.nolz4').strpath
+ data = 'test data'
+ msg = LZ4_NOT_INSTALLED_ERROR
+ with raises(ValueError) as excinfo:
+ numpy_pickle.dump(data, fname, compress='lz4')
+ excinfo.match(msg)
+
+ with raises(ValueError) as excinfo:
+ numpy_pickle.dump(data, fname + '.lz4')
+ excinfo.match(msg)
+
+
+protocols = [pickle.DEFAULT_PROTOCOL]
+if pickle.HIGHEST_PROTOCOL != pickle.DEFAULT_PROTOCOL:
+ protocols.append(pickle.HIGHEST_PROTOCOL)
+
+
+@with_numpy
+@parametrize('protocol', protocols)
+def test_memmap_alignment_padding(tmpdir, protocol):
+ # Test that memmaped arrays returned by numpy.load are correctly aligned
+ fname = tmpdir.join('test.mmap').strpath
+
+ a = np.random.randn(2)
+ numpy_pickle.dump(a, fname, protocol=protocol)
+ memmap = numpy_pickle.load(fname, mmap_mode='r')
+ assert isinstance(memmap, np.memmap)
+ np.testing.assert_array_equal(a, memmap)
+ assert (
+ memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)
+ assert memmap.flags.aligned
+
+ array_list = [
+ np.random.randn(2), np.random.randn(2),
+ np.random.randn(2), np.random.randn(2)
+ ]
+
+ # On Windows OSError 22 if reusing the same path for memmap ...
+ fname = tmpdir.join('test1.mmap').strpath
+ numpy_pickle.dump(array_list, fname, protocol=protocol)
+ l_reloaded = numpy_pickle.load(fname, mmap_mode='r')
+
+ for idx, memmap in enumerate(l_reloaded):
+ assert isinstance(memmap, np.memmap)
+ np.testing.assert_array_equal(array_list[idx], memmap)
+ assert (
+ memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)
+ assert memmap.flags.aligned
+
+ array_dict = {
+ 'a0': np.arange(2, dtype=np.uint8),
+ 'a1': np.arange(3, dtype=np.uint8),
+ 'a2': np.arange(5, dtype=np.uint8),
+ 'a3': np.arange(7, dtype=np.uint8),
+ 'a4': np.arange(11, dtype=np.uint8),
+ 'a5': np.arange(13, dtype=np.uint8),
+ 'a6': np.arange(17, dtype=np.uint8),
+ 'a7': np.arange(19, dtype=np.uint8),
+ 'a8': np.arange(23, dtype=np.uint8),
+ }
+
+ # On Windows OSError 22 if reusing the same path for memmap ...
+ fname = tmpdir.join('test2.mmap').strpath
+ numpy_pickle.dump(array_dict, fname, protocol=protocol)
+ d_reloaded = numpy_pickle.load(fname, mmap_mode='r')
+
+ for key, memmap in d_reloaded.items():
+ assert isinstance(memmap, np.memmap)
+ np.testing.assert_array_equal(array_dict[key], memmap)
+ assert (
+ memmap.ctypes.data % numpy_pickle.NUMPY_ARRAY_ALIGNMENT_BYTES == 0)
+ assert memmap.flags.aligned
diff --git a/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_compat.py b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_compat.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e8319212b606dbebf27bfed32c109c00294929e
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_compat.py
@@ -0,0 +1,18 @@
+"""Test the old numpy pickler, compatibility version."""
+
+import random
+
+# numpy_pickle is not a drop-in replacement of pickle, as it takes
+# filenames instead of open files as arguments.
+from joblib import numpy_pickle_compat
+
+
+def test_z_file(tmpdir):
+ # Test saving and loading data with Zfiles.
+ filename = tmpdir.join('test.pkl').strpath
+ data = numpy_pickle_compat.asbytes('Foo, \n Bar, baz, \n\nfoobar')
+ with open(filename, 'wb') as f:
+ numpy_pickle_compat.write_zfile(f, data)
+ with open(filename, 'rb') as f:
+ data_read = numpy_pickle_compat.read_zfile(f)
+ assert data == data_read
diff --git a/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_utils.py b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..39c2cad5259ad58f47a6607dafd8323f5fb54f35
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_numpy_pickle_utils.py
@@ -0,0 +1,10 @@
+from joblib import numpy_pickle_utils
+from joblib.compressor import BinaryZlibFile
+from joblib.testing import parametrize
+
+
+@parametrize('filename', ['test', u'test']) # testing str and unicode names
+def test_binary_zlib_file(tmpdir, filename):
+ """Testing creation of files depending on the type of the filenames."""
+ binary_file = BinaryZlibFile(tmpdir.join(filename).strpath, mode='wb')
+ binary_file.close()
diff --git a/runtime/Lib/site-packages/joblib/test/test_parallel.py b/runtime/Lib/site-packages/joblib/test/test_parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..906d4362907b87214f3402df95d4be378240dc80
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_parallel.py
@@ -0,0 +1,1737 @@
+"""
+Test the parallel module.
+"""
+
+# Author: Gael Varoquaux
+# Copyright (c) 2010-2011 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import os
+import sys
+import time
+import mmap
+import warnings
+import threading
+from traceback import format_exception
+from math import sqrt
+from time import sleep
+from pickle import PicklingError
+from multiprocessing import TimeoutError
+import pickle
+import warnings
+import pytest
+
+import joblib
+from joblib import parallel
+from joblib import dump, load
+
+from joblib._multiprocessing_helpers import mp
+
+from joblib.test.common import np, with_numpy
+from joblib.test.common import with_multiprocessing
+from joblib.testing import (parametrize, raises, check_subprocess_call,
+ skipif, warns)
+
+if mp is not None:
+ # Loky is not available if multiprocessing is not
+ from joblib.externals.loky import get_reusable_executor
+
+from queue import Queue
+
+try:
+ import posix
+except ImportError:
+ posix = None
+
+try:
+ from ._openmp_test_helper.parallel_sum import parallel_sum
+except ImportError:
+ parallel_sum = None
+
+try:
+ import distributed
+except ImportError:
+ distributed = None
+
+from joblib._parallel_backends import SequentialBackend
+from joblib._parallel_backends import ThreadingBackend
+from joblib._parallel_backends import MultiprocessingBackend
+from joblib._parallel_backends import ParallelBackendBase
+from joblib._parallel_backends import LokyBackend
+from joblib._parallel_backends import SafeFunction
+
+from joblib.parallel import Parallel, delayed
+from joblib.parallel import register_parallel_backend, parallel_backend
+from joblib.parallel import effective_n_jobs, cpu_count
+
+from joblib.parallel import mp, BACKENDS, DEFAULT_BACKEND, EXTERNAL_BACKENDS
+from joblib.my_exceptions import JoblibException
+from joblib.my_exceptions import WorkerInterrupt
+
+
+ALL_VALID_BACKENDS = [None] + sorted(BACKENDS.keys())
+# Add instances of backend classes deriving from ParallelBackendBase
+ALL_VALID_BACKENDS += [BACKENDS[backend_str]() for backend_str in BACKENDS]
+if mp is None:
+ PROCESS_BACKENDS = []
+else:
+ PROCESS_BACKENDS = ['multiprocessing', 'loky']
+PARALLEL_BACKENDS = PROCESS_BACKENDS + ['threading']
+
+if hasattr(mp, 'get_context'):
+ # Custom multiprocessing context in Python 3.4+
+ ALL_VALID_BACKENDS.append(mp.get_context('spawn'))
+
+DefaultBackend = BACKENDS[DEFAULT_BACKEND]
+
+
+def get_workers(backend):
+ return getattr(backend, '_pool', getattr(backend, '_workers', None))
+
+
+def division(x, y):
+ return x / y
+
+
+def square(x):
+ return x ** 2
+
+
+class MyExceptionWithFinickyInit(Exception):
+ """An exception class with non trivial __init__
+ """
+ def __init__(self, a, b, c, d):
+ pass
+
+
+def exception_raiser(x, custom_exception=False):
+ if x == 7:
+ raise (MyExceptionWithFinickyInit('a', 'b', 'c', 'd')
+ if custom_exception else ValueError)
+ return x
+
+
+def interrupt_raiser(x):
+ time.sleep(.05)
+ raise KeyboardInterrupt
+
+
+def f(x, y=0, z=0):
+ """ A module-level function so that it can be spawn with
+ multiprocessing.
+ """
+ return x ** 2 + y + z
+
+
+def _active_backend_type():
+ return type(parallel.get_active_backend()[0])
+
+
+def parallel_func(inner_n_jobs, backend):
+ return Parallel(n_jobs=inner_n_jobs, backend=backend)(
+ delayed(square)(i) for i in range(3))
+
+
+###############################################################################
+def test_cpu_count():
+ assert cpu_count() > 0
+
+
+def test_effective_n_jobs():
+ assert effective_n_jobs() > 0
+
+
+@pytest.mark.parametrize(
+ "backend_n_jobs, expected_n_jobs",
+ [(3, 3), (-1, effective_n_jobs(n_jobs=-1)), (None, 1)],
+ ids=["positive-int", "negative-int", "None"]
+)
+@with_multiprocessing
+def test_effective_n_jobs_None(backend_n_jobs, expected_n_jobs):
+ # check the number of effective jobs when `n_jobs=None`
+ # non-regression test for https://github.com/joblib/joblib/issues/984
+ with parallel_backend("threading", n_jobs=backend_n_jobs):
+ # when using a backend, the default of number jobs will be the one set
+ # in the backend
+ assert effective_n_jobs(n_jobs=None) == expected_n_jobs
+ # without any backend, None will default to a single job
+ assert effective_n_jobs(n_jobs=None) == 1
+
+
+###############################################################################
+# Test parallel
+
+@parametrize('backend', ALL_VALID_BACKENDS)
+@parametrize('n_jobs', [1, 2, -1, -2])
+@parametrize('verbose', [2, 11, 100])
+def test_simple_parallel(backend, n_jobs, verbose):
+ assert ([square(x) for x in range(5)] ==
+ Parallel(n_jobs=n_jobs, backend=backend,
+ verbose=verbose)(
+ delayed(square)(x) for x in range(5)))
+
+
+@parametrize('backend', ALL_VALID_BACKENDS)
+def test_main_thread_renamed_no_warning(backend, monkeypatch):
+ # Check that no default backend relies on the name of the main thread:
+ # https://github.com/joblib/joblib/issues/180#issuecomment-253266247
+ # Some programs use a different name for the main thread. This is the case
+ # for uWSGI apps for instance.
+ monkeypatch.setattr(target=threading.current_thread(), name='name',
+ value='some_new_name_for_the_main_thread')
+
+ with warnings.catch_warnings(record=True) as warninfo:
+ results = Parallel(n_jobs=2, backend=backend)(
+ delayed(square)(x) for x in range(3))
+ assert results == [0, 1, 4]
+
+ # Due to the default parameters of LokyBackend, there is a chance that
+ # warninfo catches Warnings from worker timeouts. We remove it if it exists
+ warninfo = [w for w in warninfo if "worker timeout" not in str(w.message)]
+
+ # The multiprocessing backend will raise a warning when detecting that is
+ # started from the non-main thread. Let's check that there is no false
+ # positive because of the name change.
+ assert len(warninfo) == 0
+
+
+def _assert_warning_nested(backend, inner_n_jobs, expected):
+ with warnings.catch_warnings(record=True) as warninfo:
+ warnings.simplefilter("always")
+ parallel_func(backend=backend, inner_n_jobs=inner_n_jobs)
+
+ warninfo = [w.message for w in warninfo]
+ if expected:
+ # with threading, we might see more that one warninfo
+ if warninfo:
+ return (
+ len(warninfo) == 1 and
+ 'backed parallel loops cannot' in warninfo[0].args[0]
+ )
+ return False
+ else:
+ assert not warninfo
+ return True
+
+
+@with_multiprocessing
+@parametrize('parent_backend,child_backend,expected', [
+ ('loky', 'multiprocessing', True),
+ ('loky', 'loky', False),
+ ('multiprocessing', 'multiprocessing', True),
+ ('multiprocessing', 'loky', True),
+ ('threading', 'multiprocessing', True),
+ ('threading', 'loky', True),
+])
+def test_nested_parallel_warnings(parent_backend, child_backend, expected):
+
+ # no warnings if inner_n_jobs=1
+ Parallel(n_jobs=2, backend=parent_backend)(
+ delayed(_assert_warning_nested)(
+ backend=child_backend, inner_n_jobs=1,
+ expected=False)
+ for _ in range(5))
+
+ # warnings if inner_n_jobs != 1 and expected
+ res = Parallel(n_jobs=2, backend=parent_backend)(
+ delayed(_assert_warning_nested)(
+ backend=child_backend, inner_n_jobs=2,
+ expected=expected)
+ for _ in range(5))
+
+ # warning handling is not thread safe. One thread might see multiple
+ # warning or no warning at all.
+ if parent_backend == "threading":
+ assert any(res)
+ else:
+ assert all(res)
+
+
+@with_multiprocessing
+@parametrize('backend', ['loky', 'multiprocessing', 'threading'])
+def test_background_thread_parallelism(backend):
+ is_run_parallel = [False]
+
+ def background_thread(is_run_parallel):
+ with warnings.catch_warnings(record=True) as warninfo:
+ Parallel(n_jobs=2)(
+ delayed(sleep)(.1) for _ in range(4))
+ print(len(warninfo))
+ is_run_parallel[0] = len(warninfo) == 0
+
+ t = threading.Thread(target=background_thread, args=(is_run_parallel,))
+ t.start()
+ t.join()
+ assert is_run_parallel[0]
+
+
+def nested_loop(backend):
+ Parallel(n_jobs=2, backend=backend)(
+ delayed(square)(.01) for _ in range(2))
+
+
+@parametrize('child_backend', BACKENDS)
+@parametrize('parent_backend', BACKENDS)
+def test_nested_loop(parent_backend, child_backend):
+ Parallel(n_jobs=2, backend=parent_backend)(
+ delayed(nested_loop)(child_backend) for _ in range(2))
+
+
+def raise_exception(backend):
+ raise ValueError
+
+
+@with_multiprocessing
+def test_nested_loop_with_exception_with_loky():
+ with raises(ValueError):
+ with Parallel(n_jobs=2, backend="loky") as parallel:
+ parallel([delayed(nested_loop)("loky"),
+ delayed(raise_exception)("loky")])
+
+
+def test_mutate_input_with_threads():
+ """Input is mutable when using the threading backend"""
+ q = Queue(maxsize=5)
+ Parallel(n_jobs=2, backend="threading")(
+ delayed(q.put)(1) for _ in range(5))
+ assert q.full()
+
+
+@parametrize('n_jobs', [1, 2, 3])
+def test_parallel_kwargs(n_jobs):
+ """Check the keyword argument processing of pmap."""
+ lst = range(10)
+ assert ([f(x, y=1) for x in lst] ==
+ Parallel(n_jobs=n_jobs)(delayed(f)(x, y=1) for x in lst))
+
+
+@parametrize('backend', PARALLEL_BACKENDS)
+def test_parallel_as_context_manager(backend):
+ lst = range(10)
+ expected = [f(x, y=1) for x in lst]
+
+ with Parallel(n_jobs=4, backend=backend) as p:
+ # Internally a pool instance has been eagerly created and is managed
+ # via the context manager protocol
+ managed_backend = p._backend
+
+ # We make call with the managed parallel object several times inside
+ # the managed block:
+ assert expected == p(delayed(f)(x, y=1) for x in lst)
+ assert expected == p(delayed(f)(x, y=1) for x in lst)
+
+ # Those calls have all used the same pool instance:
+ if mp is not None:
+ assert get_workers(managed_backend) is get_workers(p._backend)
+
+ # As soon as we exit the context manager block, the pool is terminated and
+ # no longer referenced from the parallel object:
+ if mp is not None:
+ assert get_workers(p._backend) is None
+
+ # It's still possible to use the parallel instance in non-managed mode:
+ assert expected == p(delayed(f)(x, y=1) for x in lst)
+ if mp is not None:
+ assert get_workers(p._backend) is None
+
+
+@with_multiprocessing
+def test_parallel_pickling():
+ """ Check that pmap captures the errors when it is passed an object
+ that cannot be pickled.
+ """
+ class UnpicklableObject(object):
+ def __reduce__(self):
+ raise RuntimeError('123')
+
+ with raises(PicklingError, match=r"the task to send"):
+ Parallel(n_jobs=2)(delayed(id)(UnpicklableObject()) for _ in range(10))
+
+
+@parametrize('backend', PARALLEL_BACKENDS)
+def test_parallel_timeout_success(backend):
+ # Check that timeout isn't thrown when function is fast enough
+ assert len(Parallel(n_jobs=2, backend=backend, timeout=10)(
+ delayed(sleep)(0.001) for x in range(10))) == 10
+
+
+@with_multiprocessing
+@parametrize('backend', PARALLEL_BACKENDS)
+def test_parallel_timeout_fail(backend):
+ # Check that timeout properly fails when function is too slow
+ with raises(TimeoutError):
+ Parallel(n_jobs=2, backend=backend, timeout=0.01)(
+ delayed(sleep)(10) for x in range(10))
+
+
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_error_capture(backend):
+ # Check that error are captured, and that correct exceptions
+ # are raised.
+ if mp is not None:
+ with raises(ZeroDivisionError):
+ Parallel(n_jobs=2, backend=backend)(
+ [delayed(division)(x, y)
+ for x, y in zip((0, 1), (1, 0))])
+ with raises(WorkerInterrupt):
+ Parallel(n_jobs=2, backend=backend)(
+ [delayed(interrupt_raiser)(x) for x in (1, 0)])
+
+ # Try again with the context manager API
+ with Parallel(n_jobs=2, backend=backend) as parallel:
+ assert get_workers(parallel._backend) is not None
+ original_workers = get_workers(parallel._backend)
+
+ with raises(ZeroDivisionError):
+ parallel([delayed(division)(x, y)
+ for x, y in zip((0, 1), (1, 0))])
+
+ # The managed pool should still be available and be in a working
+ # state despite the previously raised (and caught) exception
+ assert get_workers(parallel._backend) is not None
+
+ # The pool should have been interrupted and restarted:
+ assert get_workers(parallel._backend) is not original_workers
+
+ assert ([f(x, y=1) for x in range(10)] ==
+ parallel(delayed(f)(x, y=1) for x in range(10)))
+
+ original_workers = get_workers(parallel._backend)
+ with raises(WorkerInterrupt):
+ parallel([delayed(interrupt_raiser)(x) for x in (1, 0)])
+
+ # The pool should still be available despite the exception
+ assert get_workers(parallel._backend) is not None
+
+ # The pool should have been interrupted and restarted:
+ assert get_workers(parallel._backend) is not original_workers
+
+ assert ([f(x, y=1) for x in range(10)] ==
+ parallel(delayed(f)(x, y=1) for x in range(10)))
+
+ # Check that the inner pool has been terminated when exiting the
+ # context manager
+ assert get_workers(parallel._backend) is None
+ else:
+ with raises(KeyboardInterrupt):
+ Parallel(n_jobs=2)(
+ [delayed(interrupt_raiser)(x) for x in (1, 0)])
+
+ # wrapped exceptions should inherit from the class of the original
+ # exception to make it easy to catch them
+ with raises(ZeroDivisionError):
+ Parallel(n_jobs=2)(
+ [delayed(division)(x, y) for x, y in zip((0, 1), (1, 0))])
+
+ with raises(MyExceptionWithFinickyInit):
+ Parallel(n_jobs=2, verbose=0)(
+ (delayed(exception_raiser)(i, custom_exception=True)
+ for i in range(30)))
+
+ try:
+ # JoblibException wrapping is disabled in sequential mode:
+ Parallel(n_jobs=1)(
+ delayed(division)(x, y) for x, y in zip((0, 1), (1, 0)))
+ except Exception as ex:
+ assert not isinstance(ex, JoblibException)
+ else:
+ raise ValueError("The excepted error has not been raised.")
+
+
+def consumer(queue, item):
+ queue.append('Consumed %s' % item)
+
+
+@parametrize('backend', BACKENDS)
+@parametrize('batch_size, expected_queue',
+ [(1, ['Produced 0', 'Consumed 0',
+ 'Produced 1', 'Consumed 1',
+ 'Produced 2', 'Consumed 2',
+ 'Produced 3', 'Consumed 3',
+ 'Produced 4', 'Consumed 4',
+ 'Produced 5', 'Consumed 5']),
+ (4, [ # First Batch
+ 'Produced 0', 'Produced 1', 'Produced 2', 'Produced 3',
+ 'Consumed 0', 'Consumed 1', 'Consumed 2', 'Consumed 3',
+ # Second batch
+ 'Produced 4', 'Produced 5', 'Consumed 4', 'Consumed 5'])])
+def test_dispatch_one_job(backend, batch_size, expected_queue):
+ """ Test that with only one job, Parallel does act as a iterator.
+ """
+ queue = list()
+
+ def producer():
+ for i in range(6):
+ queue.append('Produced %i' % i)
+ yield i
+
+ Parallel(n_jobs=1, batch_size=batch_size, backend=backend)(
+ delayed(consumer)(queue, x) for x in producer())
+ assert queue == expected_queue
+ assert len(queue) == 12
+
+
+@with_multiprocessing
+@parametrize('backend', PARALLEL_BACKENDS)
+def test_dispatch_multiprocessing(backend):
+ """ Check that using pre_dispatch Parallel does indeed dispatch items
+ lazily.
+ """
+ manager = mp.Manager()
+ queue = manager.list()
+
+ def producer():
+ for i in range(6):
+ queue.append('Produced %i' % i)
+ yield i
+
+ Parallel(n_jobs=2, batch_size=1, pre_dispatch=3, backend=backend)(
+ delayed(consumer)(queue, 'any') for _ in producer())
+
+ queue_contents = list(queue)
+ assert queue_contents[0] == 'Produced 0'
+
+ # Only 3 tasks are pre-dispatched out of 6. The 4th task is dispatched only
+ # after any of the first 3 jobs have completed.
+ first_consumption_index = queue_contents[:4].index('Consumed any')
+ assert first_consumption_index > -1
+
+ produced_3_index = queue_contents.index('Produced 3') # 4th task produced
+ assert produced_3_index > first_consumption_index
+
+ assert len(queue) == 12
+
+
+def test_batching_auto_threading():
+ # batching='auto' with the threading backend leaves the effective batch
+ # size to 1 (no batching) as it has been found to never be beneficial with
+ # this low-overhead backend.
+
+ with Parallel(n_jobs=2, batch_size='auto', backend='threading') as p:
+ p(delayed(id)(i) for i in range(5000)) # many very fast tasks
+ assert p._backend.compute_batch_size() == 1
+
+
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_batching_auto_subprocesses(backend):
+ with Parallel(n_jobs=2, batch_size='auto', backend=backend) as p:
+ p(delayed(id)(i) for i in range(5000)) # many very fast tasks
+
+ # It should be strictly larger than 1 but as we don't want heisen
+ # failures on clogged CI worker environment be safe and only check that
+ # it's a strictly positive number.
+ assert p._backend.compute_batch_size() > 0
+
+
+def test_exception_dispatch():
+ """Make sure that exception raised during dispatch are indeed captured"""
+ with raises(ValueError):
+ Parallel(n_jobs=2, pre_dispatch=16, verbose=0)(
+ delayed(exception_raiser)(i) for i in range(30))
+
+
+def nested_function_inner(i):
+ Parallel(n_jobs=2)(
+ delayed(exception_raiser)(j) for j in range(30))
+
+
+def nested_function_outer(i):
+ Parallel(n_jobs=2)(
+ delayed(nested_function_inner)(j) for j in range(30))
+
+
+@with_multiprocessing
+@parametrize('backend', PARALLEL_BACKENDS)
+@pytest.mark.xfail(reason="https://github.com/joblib/loky/pull/255")
+def test_nested_exception_dispatch(backend):
+ """Ensure errors for nested joblib cases gets propagated
+
+ We rely on the Python 3 built-in __cause__ system that already
+ report this kind of information to the user.
+ """
+ with raises(ValueError) as excinfo:
+ Parallel(n_jobs=2, backend=backend)(
+ delayed(nested_function_outer)(i) for i in range(30))
+
+ # Check that important information such as function names are visible
+ # in the final error message reported to the user
+ report_lines = format_exception(excinfo.type, excinfo.value, excinfo.tb)
+ report = "".join(report_lines)
+ assert 'nested_function_outer' in report
+ assert 'nested_function_inner' in report
+ assert 'exception_raiser' in report
+
+ assert type(excinfo.value) is ValueError
+
+
+class FakeParallelBackend(SequentialBackend):
+ """Pretends to run concurrently while running sequentially."""
+
+ def configure(self, n_jobs=1, parallel=None, **backend_args):
+ self.n_jobs = self.effective_n_jobs(n_jobs)
+ self.parallel = parallel
+ return n_jobs
+
+ def effective_n_jobs(self, n_jobs=1):
+ if n_jobs < 0:
+ n_jobs = max(mp.cpu_count() + 1 + n_jobs, 1)
+ return n_jobs
+
+
+def test_invalid_backend():
+ with raises(ValueError) as excinfo:
+ Parallel(backend='unit-testing')
+ assert "Invalid backend:" in str(excinfo.value)
+
+ with raises(ValueError) as excinfo:
+ with parallel_backend('unit-testing'):
+ pass
+ assert "Invalid backend:" in str(excinfo.value)
+
+
+@parametrize('backend', ALL_VALID_BACKENDS)
+def test_invalid_njobs(backend):
+ with raises(ValueError) as excinfo:
+ Parallel(n_jobs=0, backend=backend)._initialize_backend()
+ assert "n_jobs == 0 in Parallel has no meaning" in str(excinfo.value)
+
+
+def test_register_parallel_backend():
+ try:
+ register_parallel_backend("test_backend", FakeParallelBackend)
+ assert "test_backend" in BACKENDS
+ assert BACKENDS["test_backend"] == FakeParallelBackend
+ finally:
+ del BACKENDS["test_backend"]
+
+
+def test_overwrite_default_backend():
+ assert _active_backend_type() == DefaultBackend
+ try:
+ register_parallel_backend("threading", BACKENDS["threading"],
+ make_default=True)
+ assert _active_backend_type() == ThreadingBackend
+ finally:
+ # Restore the global default manually
+ parallel.DEFAULT_BACKEND = DEFAULT_BACKEND
+ assert _active_backend_type() == DefaultBackend
+
+
+@skipif(mp is not None, reason="Only without multiprocessing")
+def test_backend_no_multiprocessing():
+ with warns(UserWarning,
+ match="joblib backend '.*' is not available on.*"):
+ Parallel(backend='loky')(delayed(square)(i) for i in range(3))
+
+ # The below should now work without problems
+ with parallel_backend('loky'):
+ Parallel()(delayed(square)(i) for i in range(3))
+
+
+def check_backend_context_manager(backend_name):
+ with parallel_backend(backend_name, n_jobs=3):
+ active_backend, active_n_jobs = parallel.get_active_backend()
+ assert active_n_jobs == 3
+ assert effective_n_jobs(3) == 3
+ p = Parallel()
+ assert p.n_jobs == 3
+ if backend_name == 'multiprocessing':
+ assert type(active_backend) == MultiprocessingBackend
+ assert type(p._backend) == MultiprocessingBackend
+ elif backend_name == 'loky':
+ assert type(active_backend) == LokyBackend
+ assert type(p._backend) == LokyBackend
+ elif backend_name == 'threading':
+ assert type(active_backend) == ThreadingBackend
+ assert type(p._backend) == ThreadingBackend
+ elif backend_name.startswith('test_'):
+ assert type(active_backend) == FakeParallelBackend
+ assert type(p._backend) == FakeParallelBackend
+
+
+all_backends_for_context_manager = PARALLEL_BACKENDS[:]
+all_backends_for_context_manager.extend(
+ ['test_backend_%d' % i for i in range(3)]
+)
+
+
+@with_multiprocessing
+@parametrize('backend', all_backends_for_context_manager)
+def test_backend_context_manager(monkeypatch, backend):
+ if backend not in BACKENDS:
+ monkeypatch.setitem(BACKENDS, backend, FakeParallelBackend)
+
+ assert _active_backend_type() == DefaultBackend
+ # check that this possible to switch parallel backends sequentially
+ check_backend_context_manager(backend)
+
+ # The default backend is restored
+ assert _active_backend_type() == DefaultBackend
+
+ # Check that context manager switching is thread safe:
+ Parallel(n_jobs=2, backend='threading')(
+ delayed(check_backend_context_manager)(b)
+ for b in all_backends_for_context_manager if not b)
+
+ # The default backend is again restored
+ assert _active_backend_type() == DefaultBackend
+
+
+class ParameterizedParallelBackend(SequentialBackend):
+ """Pretends to run conncurrently while running sequentially."""
+
+ def __init__(self, param=None):
+ if param is None:
+ raise ValueError('param should not be None')
+ self.param = param
+
+
+def test_parameterized_backend_context_manager(monkeypatch):
+ monkeypatch.setitem(BACKENDS, 'param_backend',
+ ParameterizedParallelBackend)
+ assert _active_backend_type() == DefaultBackend
+
+ with parallel_backend('param_backend', param=42, n_jobs=3):
+ active_backend, active_n_jobs = parallel.get_active_backend()
+ assert type(active_backend) == ParameterizedParallelBackend
+ assert active_backend.param == 42
+ assert active_n_jobs == 3
+ p = Parallel()
+ assert p.n_jobs == 3
+ assert p._backend is active_backend
+ results = p(delayed(sqrt)(i) for i in range(5))
+ assert results == [sqrt(i) for i in range(5)]
+
+ # The default backend is again restored
+ assert _active_backend_type() == DefaultBackend
+
+
+def test_directly_parameterized_backend_context_manager():
+ assert _active_backend_type() == DefaultBackend
+
+ # Check that it's possible to pass a backend instance directly,
+ # without registration
+ with parallel_backend(ParameterizedParallelBackend(param=43), n_jobs=5):
+ active_backend, active_n_jobs = parallel.get_active_backend()
+ assert type(active_backend) == ParameterizedParallelBackend
+ assert active_backend.param == 43
+ assert active_n_jobs == 5
+ p = Parallel()
+ assert p.n_jobs == 5
+ assert p._backend is active_backend
+ results = p(delayed(sqrt)(i) for i in range(5))
+ assert results == [sqrt(i) for i in range(5)]
+
+ # The default backend is again restored
+ assert _active_backend_type() == DefaultBackend
+
+
+def sleep_and_return_pid():
+ sleep(.1)
+ return os.getpid()
+
+
+def get_nested_pids():
+ assert _active_backend_type() == ThreadingBackend
+ # Assert that the nested backend does not change the default number of
+ # jobs used in Parallel
+ assert Parallel()._effective_n_jobs() == 1
+
+ # Assert that the tasks are running only on one process
+ return Parallel(n_jobs=2)(delayed(sleep_and_return_pid)()
+ for _ in range(2))
+
+
+class MyBackend(joblib._parallel_backends.LokyBackend):
+ """Backend to test backward compatibility with older backends"""
+ def get_nested_backend(self, ):
+ # Older backends only return a backend, without n_jobs indications.
+ return super(MyBackend, self).get_nested_backend()[0]
+
+
+register_parallel_backend('back_compat_backend', MyBackend)
+
+
+@with_multiprocessing
+@parametrize('backend', ['threading', 'loky', 'multiprocessing',
+ 'back_compat_backend'])
+def test_nested_backend_context_manager(backend):
+ # Check that by default, nested parallel calls will always use the
+ # ThreadingBackend
+
+ with parallel_backend(backend):
+ pid_groups = Parallel(n_jobs=2)(
+ delayed(get_nested_pids)()
+ for _ in range(10)
+ )
+ for pid_group in pid_groups:
+ assert len(set(pid_group)) == 1
+
+
+@with_multiprocessing
+@parametrize('n_jobs', [2, -1, None])
+@parametrize('backend', PARALLEL_BACKENDS)
+def test_nested_backend_in_sequential(backend, n_jobs):
+ # Check that by default, nested parallel calls will always use the
+ # ThreadingBackend
+
+ def check_nested_backend(expected_backend_type, expected_n_job):
+ # Assert that the sequential backend at top level, does not change the
+ # backend for nested calls.
+ assert _active_backend_type() == BACKENDS[expected_backend_type]
+
+ # Assert that the nested backend in SequentialBackend does not change
+ # the default number of jobs used in Parallel
+ expected_n_job = effective_n_jobs(expected_n_job)
+ assert Parallel()._effective_n_jobs() == expected_n_job
+
+ Parallel(n_jobs=1)(
+ delayed(check_nested_backend)('loky', 1)
+ for _ in range(10)
+ )
+
+ with parallel_backend(backend, n_jobs=n_jobs):
+ Parallel(n_jobs=1)(
+ delayed(check_nested_backend)(backend, n_jobs)
+ for _ in range(10)
+ )
+
+
+def check_nesting_level(inner_backend, expected_level):
+ with parallel_backend(inner_backend) as (backend, n_jobs):
+ assert backend.nesting_level == expected_level
+
+
+@with_multiprocessing
+@parametrize('outer_backend', PARALLEL_BACKENDS)
+@parametrize('inner_backend', PARALLEL_BACKENDS)
+def test_backend_nesting_level(outer_backend, inner_backend):
+ # Check that the nesting level for the backend is correctly set
+ check_nesting_level(outer_backend, 0)
+
+ Parallel(n_jobs=2, backend=outer_backend)(
+ delayed(check_nesting_level)(inner_backend, 1)
+ for _ in range(10)
+ )
+
+ with parallel_backend(inner_backend, n_jobs=2):
+ Parallel()(delayed(check_nesting_level)(inner_backend, 1)
+ for _ in range(10))
+
+
+@with_multiprocessing
+def test_retrieval_context():
+ import contextlib
+
+ class MyBackend(ThreadingBackend):
+ i = 0
+
+ @contextlib.contextmanager
+ def retrieval_context(self):
+ self.i += 1
+ yield
+
+ register_parallel_backend("retrieval", MyBackend)
+
+ def nested_call(n):
+ return Parallel(n_jobs=2)(delayed(id)(i) for i in range(n))
+
+ with parallel_backend("retrieval") as (ba, _):
+ Parallel(n_jobs=2)(
+ delayed(nested_call)(i)
+ for i in range(5)
+ )
+ assert ba.i == 1
+
+
+###############################################################################
+# Test helpers
+def test_joblib_exception():
+ # Smoke-test the custom exception
+ e = JoblibException('foobar')
+ # Test the repr
+ repr(e)
+ # Test the pickle
+ pickle.dumps(e)
+
+
+def test_safe_function():
+ safe_division = SafeFunction(division)
+ with raises(ZeroDivisionError):
+ safe_division(1, 0)
+
+ safe_interrupt = SafeFunction(interrupt_raiser)
+ with raises(WorkerInterrupt):
+ safe_interrupt('x')
+
+
+@parametrize('batch_size', [0, -1, 1.42])
+def test_invalid_batch_size(batch_size):
+ with raises(ValueError):
+ Parallel(batch_size=batch_size)
+
+
+@parametrize('n_tasks, n_jobs, pre_dispatch, batch_size',
+ [(2, 2, 'all', 'auto'),
+ (2, 2, 'n_jobs', 'auto'),
+ (10, 2, 'n_jobs', 'auto'),
+ (517, 2, 'n_jobs', 'auto'),
+ (10, 2, 'n_jobs', 'auto'),
+ (10, 4, 'n_jobs', 'auto'),
+ (200, 12, 'n_jobs', 'auto'),
+ (25, 12, '2 * n_jobs', 1),
+ (250, 12, 'all', 1),
+ (250, 12, '2 * n_jobs', 7),
+ (200, 12, '2 * n_jobs', 'auto')])
+def test_dispatch_race_condition(n_tasks, n_jobs, pre_dispatch, batch_size):
+ # Check that using (async-)dispatch does not yield a race condition on the
+ # iterable generator that is not thread-safe natively.
+ # This is a non-regression test for the "Pool seems closed" class of error
+ params = {'n_jobs': n_jobs, 'pre_dispatch': pre_dispatch,
+ 'batch_size': batch_size}
+ expected = [square(i) for i in range(n_tasks)]
+ results = Parallel(**params)(delayed(square)(i) for i in range(n_tasks))
+ assert results == expected
+
+
+@with_multiprocessing
+def test_default_mp_context():
+ mp_start_method = mp.get_start_method()
+ p = Parallel(n_jobs=2, backend='multiprocessing')
+ context = p._backend_args.get('context')
+ start_method = context.get_start_method()
+ assert start_method == mp_start_method
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_no_blas_crash_or_freeze_with_subprocesses(backend):
+ if backend == 'multiprocessing':
+ # Use the spawn backend that is both robust and available on all
+ # platforms
+ backend = mp.get_context('spawn')
+
+ # Check that on recent Python version, the 'spawn' start method can make
+ # it possible to use multiprocessing in conjunction of any BLAS
+ # implementation that happens to be used by numpy with causing a freeze or
+ # a crash
+ rng = np.random.RandomState(42)
+
+ # call BLAS DGEMM to force the initialization of the internal thread-pool
+ # in the main process
+ a = rng.randn(1000, 1000)
+ np.dot(a, a.T)
+
+ # check that the internal BLAS thread-pool is not in an inconsistent state
+ # in the worker processes managed by multiprocessing
+ Parallel(n_jobs=2, backend=backend)(
+ delayed(np.dot)(a, a.T) for i in range(2))
+
+
+UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_NO_MAIN = """\
+from joblib import Parallel, delayed
+
+def square(x):
+ return x ** 2
+
+backend = "{}"
+if backend == "spawn":
+ from multiprocessing import get_context
+ backend = get_context(backend)
+
+print(Parallel(n_jobs=2, backend=backend)(
+ delayed(square)(i) for i in range(5)))
+"""
+
+
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_parallel_with_interactively_defined_functions(backend):
+ # When using the "-c" flag, interactive functions defined in __main__
+ # should work with any backend.
+ if backend == "multiprocessing" and mp.get_start_method() != "fork":
+ pytest.skip("Require fork start method to use interactively defined "
+ "functions with multiprocessing.")
+ code = UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_NO_MAIN.format(backend)
+ check_subprocess_call(
+ [sys.executable, '-c', code], timeout=10,
+ stdout_regex=r'\[0, 1, 4, 9, 16\]')
+
+
+UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_MAIN = """\
+import sys
+# Make sure that joblib is importable in the subprocess launching this
+# script. This is needed in case we run the tests from the joblib root
+# folder without having installed joblib
+sys.path.insert(0, {joblib_root_folder!r})
+
+from joblib import Parallel, delayed
+
+def run(f, x):
+ return f(x)
+
+{define_func}
+
+if __name__ == "__main__":
+ backend = "{backend}"
+ if backend == "spawn":
+ from multiprocessing import get_context
+ backend = get_context(backend)
+
+ callable_position = "{callable_position}"
+ if callable_position == "delayed":
+ print(Parallel(n_jobs=2, backend=backend)(
+ delayed(square)(i) for i in range(5)))
+ elif callable_position == "args":
+ print(Parallel(n_jobs=2, backend=backend)(
+ delayed(run)(square, i) for i in range(5)))
+ else:
+ print(Parallel(n_jobs=2, backend=backend)(
+ delayed(run)(f=square, x=i) for i in range(5)))
+"""
+
+SQUARE_MAIN = """\
+def square(x):
+ return x ** 2
+"""
+SQUARE_LOCAL = """\
+def gen_square():
+ def square(x):
+ return x ** 2
+ return square
+square = gen_square()
+"""
+SQUARE_LAMBDA = """\
+square = lambda x: x ** 2
+"""
+
+
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS + ([] if mp is None else ['spawn']))
+@parametrize('define_func', [SQUARE_MAIN, SQUARE_LOCAL, SQUARE_LAMBDA])
+@parametrize('callable_position', ['delayed', 'args', 'kwargs'])
+def test_parallel_with_unpicklable_functions_in_args(
+ backend, define_func, callable_position, tmpdir):
+ if backend in ['multiprocessing', 'spawn'] and (
+ define_func != SQUARE_MAIN or sys.platform == "win32"):
+ pytest.skip("Not picklable with pickle")
+ code = UNPICKLABLE_CALLABLE_SCRIPT_TEMPLATE_MAIN.format(
+ define_func=define_func, backend=backend,
+ callable_position=callable_position,
+ joblib_root_folder=os.path.dirname(os.path.dirname(joblib.__file__)))
+ code_file = tmpdir.join("unpicklable_func_script.py")
+ code_file.write(code)
+ check_subprocess_call(
+ [sys.executable, code_file.strpath], timeout=10,
+ stdout_regex=r'\[0, 1, 4, 9, 16\]')
+
+
+INTERACTIVE_DEFINED_FUNCTION_AND_CLASS_SCRIPT_CONTENT = """\
+import sys
+import faulthandler
+# Make sure that joblib is importable in the subprocess launching this
+# script. This is needed in case we run the tests from the joblib root
+# folder without having installed joblib
+sys.path.insert(0, {joblib_root_folder!r})
+
+from joblib import Parallel, delayed
+from functools import partial
+
+class MyClass:
+ '''Class defined in the __main__ namespace'''
+ def __init__(self, value):
+ self.value = value
+
+
+def square(x, ignored=None, ignored2=None):
+ '''Function defined in the __main__ namespace'''
+ return x.value ** 2
+
+
+square2 = partial(square, ignored2='something')
+
+# Here, we do not need the `if __name__ == "__main__":` safeguard when
+# using the default `loky` backend (even on Windows).
+
+# To make debugging easier
+faulthandler.dump_traceback_later(30, exit=True)
+
+# The following baroque function call is meant to check that joblib
+# introspection rightfully uses cloudpickle instead of the (faster) pickle
+# module of the standard library when necessary. In particular cloudpickle is
+# necessary for functions and instances of classes interactively defined in the
+# __main__ module.
+
+print(Parallel(n_jobs=2)(
+ delayed(square2)(MyClass(i), ignored=[dict(a=MyClass(1))])
+ for i in range(5)
+))
+""".format(joblib_root_folder=os.path.dirname(
+ os.path.dirname(joblib.__file__)))
+
+
+@with_multiprocessing
+def test_parallel_with_interactively_defined_functions_default_backend(tmpdir):
+ # The default backend (loky) accepts interactive functions defined in
+ # __main__ and does not require if __name__ == '__main__' even when
+ # the __main__ module is defined by the result of the execution of a
+ # filesystem script.
+ script = tmpdir.join('joblib_interactively_defined_function.py')
+ script.write(INTERACTIVE_DEFINED_FUNCTION_AND_CLASS_SCRIPT_CONTENT)
+ check_subprocess_call(
+ [sys.executable, script.strpath],
+ stdout_regex=r'\[0, 1, 4, 9, 16\]',
+ timeout=None, # rely on faulthandler to kill the process
+ )
+
+
+INTERACTIVELY_DEFINED_SUBCLASS_WITH_METHOD_SCRIPT_CONTENT = """\
+import sys
+# Make sure that joblib is importable in the subprocess launching this
+# script. This is needed in case we run the tests from the joblib root
+# folder without having installed joblib
+sys.path.insert(0, {joblib_root_folder!r})
+
+from joblib import Parallel, delayed, hash
+import multiprocessing as mp
+mp.util.log_to_stderr(5)
+
+class MyList(list):
+ '''MyList is interactively defined by MyList.append is a built-in'''
+ def __hash__(self):
+ # XXX: workaround limitation in cloudpickle
+ return hash(self).__hash__()
+
+l = MyList()
+
+print(Parallel(n_jobs=2)(
+ delayed(l.append)(i) for i in range(3)
+))
+""".format(joblib_root_folder=os.path.dirname(
+ os.path.dirname(joblib.__file__)))
+
+
+@with_multiprocessing
+def test_parallel_with_interactively_defined_bound_method(tmpdir):
+ script = tmpdir.join('joblib_interactive_bound_method_script.py')
+ script.write(INTERACTIVELY_DEFINED_SUBCLASS_WITH_METHOD_SCRIPT_CONTENT)
+ check_subprocess_call([sys.executable, script.strpath],
+ stdout_regex=r'\[None, None, None\]',
+ stderr_regex=r'LokyProcess',
+ timeout=15)
+
+
+def test_parallel_with_exhausted_iterator():
+ exhausted_iterator = iter([])
+ assert Parallel(n_jobs=2)(exhausted_iterator) == []
+
+
+def check_memmap(a):
+ if not isinstance(a, np.memmap):
+ raise TypeError('Expected np.memmap instance, got %r',
+ type(a))
+ return a.copy() # return a regular array instead of a memmap
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_auto_memmap_on_arrays_from_generator(backend):
+ # Non-regression test for a problem with a bad interaction between the
+ # GC collecting arrays recently created during iteration inside the
+ # parallel dispatch loop and the auto-memmap feature of Parallel.
+ # See: https://github.com/joblib/joblib/pull/294
+ def generate_arrays(n):
+ for i in range(n):
+ yield np.ones(10, dtype=np.float32) * i
+ # Use max_nbytes=1 to force the use of memory-mapping even for small
+ # arrays
+ results = Parallel(n_jobs=2, max_nbytes=1, backend=backend)(
+ delayed(check_memmap)(a) for a in generate_arrays(100))
+ for result, expected in zip(results, generate_arrays(len(results))):
+ np.testing.assert_array_equal(expected, result)
+
+ # Second call to force loky to adapt the executor by growing the number
+ # of worker processes. This is a non-regression test for:
+ # https://github.com/joblib/joblib/issues/629.
+ results = Parallel(n_jobs=4, max_nbytes=1, backend=backend)(
+ delayed(check_memmap)(a) for a in generate_arrays(100))
+ for result, expected in zip(results, generate_arrays(len(results))):
+ np.testing.assert_array_equal(expected, result)
+
+
+def identity(arg):
+ return arg
+
+
+@with_numpy
+@with_multiprocessing
+def test_memmap_with_big_offset(tmpdir):
+ fname = tmpdir.join('test.mmap').strpath
+ size = mmap.ALLOCATIONGRANULARITY
+ obj = [np.zeros(size, dtype='uint8'), np.ones(size, dtype='uint8')]
+ dump(obj, fname)
+ memmap = load(fname, mmap_mode='r')
+ result, = Parallel(n_jobs=2)(delayed(identity)(memmap) for _ in [0])
+ assert isinstance(memmap[1], np.memmap)
+ assert memmap[1].offset > size
+ np.testing.assert_array_equal(obj, result)
+
+
+def test_warning_about_timeout_not_supported_by_backend():
+ with warnings.catch_warnings(record=True) as warninfo:
+ Parallel(timeout=1)(delayed(square)(i) for i in range(50))
+ assert len(warninfo) == 1
+ w = warninfo[0]
+ assert isinstance(w.message, UserWarning)
+ assert str(w.message) == (
+ "The backend class 'SequentialBackend' does not support timeout. "
+ "You have set 'timeout=1' in Parallel but the 'timeout' parameter "
+ "will not be used.")
+
+
+@parametrize('backend', ALL_VALID_BACKENDS)
+@parametrize('n_jobs', [1, 2, -2, -1])
+def test_abort_backend(n_jobs, backend):
+ delays = ["a"] + [10] * 100
+ with raises(TypeError):
+ t_start = time.time()
+ Parallel(n_jobs=n_jobs, backend=backend)(
+ delayed(time.sleep)(i) for i in delays)
+ dt = time.time() - t_start
+ assert dt < 20
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_memmapping_leaks(backend, tmpdir):
+ # Non-regression test for memmapping backends. Ensure that the data
+ # does not stay too long in memory
+ tmpdir = tmpdir.strpath
+
+ # Use max_nbytes=1 to force the use of memory-mapping even for small
+ # arrays
+ with Parallel(n_jobs=2, max_nbytes=1, backend=backend,
+ temp_folder=tmpdir) as p:
+ p(delayed(check_memmap)(a) for a in [np.random.random(10)] * 2)
+
+ # The memmap folder should not be clean in the context scope
+ assert len(os.listdir(tmpdir)) > 0
+
+ # Make sure that the shared memory is cleaned at the end when we exit
+ # the context
+ for _ in range(100):
+ if not os.listdir(tmpdir):
+ break
+ sleep(.1)
+ else:
+ raise AssertionError('temporary directory of Parallel was not removed')
+
+ # Make sure that the shared memory is cleaned at the end of a call
+ p = Parallel(n_jobs=2, max_nbytes=1, backend=backend)
+ p(delayed(check_memmap)(a) for a in [np.random.random(10)] * 2)
+
+ for _ in range(100):
+ if not os.listdir(tmpdir):
+ break
+ sleep(.1)
+ else:
+ raise AssertionError('temporary directory of Parallel was not removed')
+
+
+@parametrize('backend',
+ ([None, 'threading'] if mp is None
+ else [None, 'loky', 'threading'])
+ )
+def test_lambda_expression(backend):
+ # cloudpickle is used to pickle delayed callables
+ results = Parallel(n_jobs=2, backend=backend)(
+ delayed(lambda x: x ** 2)(i) for i in range(10))
+ assert results == [i ** 2 for i in range(10)]
+
+
+@with_multiprocessing
+@parametrize('backend', PROCESS_BACKENDS)
+def test_backend_batch_statistics_reset(backend):
+ """Test that a parallel backend correctly resets its batch statistics."""
+ n_jobs = 2
+ n_inputs = 500
+ task_time = 2. / n_inputs
+
+ p = Parallel(verbose=10, n_jobs=n_jobs, backend=backend)
+ p(delayed(time.sleep)(task_time) for i in range(n_inputs))
+ assert (p._backend._effective_batch_size ==
+ p._backend._DEFAULT_EFFECTIVE_BATCH_SIZE)
+ assert (p._backend._smoothed_batch_duration ==
+ p._backend._DEFAULT_SMOOTHED_BATCH_DURATION)
+
+ p(delayed(time.sleep)(task_time) for i in range(n_inputs))
+ assert (p._backend._effective_batch_size ==
+ p._backend._DEFAULT_EFFECTIVE_BATCH_SIZE)
+ assert (p._backend._smoothed_batch_duration ==
+ p._backend._DEFAULT_SMOOTHED_BATCH_DURATION)
+
+
+@with_multiprocessing
+def test_backend_hinting_and_constraints():
+ for n_jobs in [1, 2, -1]:
+ assert type(Parallel(n_jobs=n_jobs)._backend) == LokyBackend
+
+ p = Parallel(n_jobs=n_jobs, prefer='threads')
+ assert type(p._backend) == ThreadingBackend
+
+ p = Parallel(n_jobs=n_jobs, prefer='processes')
+ assert type(p._backend) == LokyBackend
+
+ p = Parallel(n_jobs=n_jobs, require='sharedmem')
+ assert type(p._backend) == ThreadingBackend
+
+ # Explicit backend selection can override backend hinting although it
+ # is useless to pass a hint when selecting a backend.
+ p = Parallel(n_jobs=2, backend='loky', prefer='threads')
+ assert type(p._backend) == LokyBackend
+
+ with parallel_backend('loky', n_jobs=2):
+ # Explicit backend selection by the user with the context manager
+ # should be respected when combined with backend hints only.
+ p = Parallel(prefer='threads')
+ assert type(p._backend) == LokyBackend
+ assert p.n_jobs == 2
+
+ with parallel_backend('loky', n_jobs=2):
+ # Locally hard-coded n_jobs value is respected.
+ p = Parallel(n_jobs=3, prefer='threads')
+ assert type(p._backend) == LokyBackend
+ assert p.n_jobs == 3
+
+ with parallel_backend('loky', n_jobs=2):
+ # Explicit backend selection by the user with the context manager
+ # should be ignored when the Parallel call has hard constraints.
+ # In this case, the default backend that supports shared mem is
+ # used an the default number of processes is used.
+ p = Parallel(require='sharedmem')
+ assert type(p._backend) == ThreadingBackend
+ assert p.n_jobs == 1
+
+ with parallel_backend('loky', n_jobs=2):
+ p = Parallel(n_jobs=3, require='sharedmem')
+ assert type(p._backend) == ThreadingBackend
+ assert p.n_jobs == 3
+
+
+def test_backend_hinting_and_constraints_with_custom_backends(capsys):
+ # Custom backends can declare that they use threads and have shared memory
+ # semantics:
+ class MyCustomThreadingBackend(ParallelBackendBase):
+ supports_sharedmem = True
+ use_threads = True
+
+ def apply_async(self):
+ pass
+
+ def effective_n_jobs(self, n_jobs):
+ return n_jobs
+
+ with parallel_backend(MyCustomThreadingBackend()):
+ p = Parallel(n_jobs=2, prefer='processes') # ignored
+ assert type(p._backend) == MyCustomThreadingBackend
+
+ p = Parallel(n_jobs=2, require='sharedmem')
+ assert type(p._backend) == MyCustomThreadingBackend
+
+ class MyCustomProcessingBackend(ParallelBackendBase):
+ supports_sharedmem = False
+ use_threads = False
+
+ def apply_async(self):
+ pass
+
+ def effective_n_jobs(self, n_jobs):
+ return n_jobs
+
+ with parallel_backend(MyCustomProcessingBackend()):
+ p = Parallel(n_jobs=2, prefer='processes')
+ assert type(p._backend) == MyCustomProcessingBackend
+
+ out, err = capsys.readouterr()
+ assert out == ""
+ assert err == ""
+
+ p = Parallel(n_jobs=2, require='sharedmem', verbose=10)
+ assert type(p._backend) == ThreadingBackend
+
+ out, err = capsys.readouterr()
+ expected = ("Using ThreadingBackend as joblib.Parallel backend "
+ "instead of MyCustomProcessingBackend as the latter "
+ "does not provide shared memory semantics.")
+ assert out.strip() == expected
+ assert err == ""
+
+ with raises(ValueError):
+ Parallel(backend=MyCustomProcessingBackend(), require='sharedmem')
+
+
+def test_invalid_backend_hinting_and_constraints():
+ with raises(ValueError):
+ Parallel(prefer='invalid')
+
+ with raises(ValueError):
+ Parallel(require='invalid')
+
+ with raises(ValueError):
+ # It is inconsistent to prefer process-based parallelism while
+ # requiring shared memory semantics.
+ Parallel(prefer='processes', require='sharedmem')
+
+ if mp is not None:
+ # It is inconsistent to ask explicitly for a process-based
+ # parallelism while requiring shared memory semantics.
+ with raises(ValueError):
+ Parallel(backend='loky', require='sharedmem')
+ with raises(ValueError):
+ Parallel(backend='multiprocessing', require='sharedmem')
+
+
+def test_global_parallel_backend():
+ default = Parallel()._backend
+
+ pb = parallel_backend('threading')
+ assert isinstance(Parallel()._backend, ThreadingBackend)
+
+ pb.unregister()
+ assert type(Parallel()._backend) is type(default)
+
+
+def test_external_backends():
+ def register_foo():
+ BACKENDS['foo'] = ThreadingBackend
+
+ EXTERNAL_BACKENDS['foo'] = register_foo
+
+ with parallel_backend('foo'):
+ assert isinstance(Parallel()._backend, ThreadingBackend)
+
+
+def _recursive_backend_info(limit=3, **kwargs):
+ """Perform nested parallel calls and introspect the backend on the way"""
+
+ with Parallel(n_jobs=2) as p:
+ this_level = [(type(p._backend).__name__, p._backend.nesting_level)]
+ if limit == 0:
+ return this_level
+ results = p(delayed(_recursive_backend_info)(limit=limit - 1, **kwargs)
+ for i in range(1))
+ return this_level + results[0]
+
+
+@with_multiprocessing
+@parametrize('backend', ['loky', 'threading'])
+def test_nested_parallelism_limit(backend):
+ with parallel_backend(backend, n_jobs=2):
+ backend_types_and_levels = _recursive_backend_info()
+
+ if cpu_count() == 1:
+ second_level_backend_type = 'SequentialBackend'
+ max_level = 1
+ else:
+ second_level_backend_type = 'ThreadingBackend'
+ max_level = 2
+
+ top_level_backend_type = backend.title() + 'Backend'
+ expected_types_and_levels = [
+ (top_level_backend_type, 0),
+ (second_level_backend_type, 1),
+ ('SequentialBackend', max_level),
+ ('SequentialBackend', max_level)
+ ]
+ assert backend_types_and_levels == expected_types_and_levels
+
+
+@with_numpy
+@skipif(distributed is None, reason='This test requires dask')
+def test_nested_parallelism_with_dask():
+ client = distributed.Client(n_workers=2, threads_per_worker=2) # noqa
+
+ # 10 MB of data as argument to trigger implicit scattering
+ data = np.ones(int(1e7), dtype=np.uint8)
+ for i in range(2):
+ with parallel_backend('dask'):
+ backend_types_and_levels = _recursive_backend_info(data=data)
+ assert len(backend_types_and_levels) == 4
+ assert all(name == 'DaskDistributedBackend'
+ for name, _ in backend_types_and_levels)
+
+ # No argument
+ with parallel_backend('dask'):
+ backend_types_and_levels = _recursive_backend_info()
+ assert len(backend_types_and_levels) == 4
+ assert all(name == 'DaskDistributedBackend'
+ for name, _ in backend_types_and_levels)
+
+
+def _recursive_parallel(nesting_limit=None):
+ """A horrible function that does recursive parallel calls"""
+ return Parallel()(delayed(_recursive_parallel)() for i in range(2))
+
+
+@parametrize('backend',
+ (['threading'] if mp is None else ['loky', 'threading']))
+def test_thread_bomb_mitigation(backend):
+ # Test that recursive parallelism raises a recursion rather than
+ # saturating the operating system resources by creating a unbounded number
+ # of threads.
+ with parallel_backend(backend, n_jobs=2):
+ with raises(BaseException) as excinfo:
+ _recursive_parallel()
+ exc = excinfo.value
+ if backend == "loky":
+ # Local import because loky may not be importable for lack of
+ # multiprocessing
+ from joblib.externals.loky.process_executor import TerminatedWorkerError # noqa
+ if isinstance(exc, TerminatedWorkerError):
+ # The recursion exception can itself cause an error when
+ # pickling it to be send back to the parent process. In this
+ # case the worker crashes but the original traceback is still
+ # printed on stderr. This could be improved but does not seem
+ # simple to do and this is is not critical for users (as long
+ # as there is no process or thread bomb happening).
+ pytest.xfail("Loky worker crash when serializing RecursionError")
+ else:
+ assert isinstance(exc, RecursionError)
+
+
+def _run_parallel_sum():
+ env_vars = {}
+ for var in ['OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
+ 'VECLIB_MAXIMUM_THREADS', 'NUMEXPR_NUM_THREADS',
+ 'NUMBA_NUM_THREADS', 'ENABLE_IPC']:
+ env_vars[var] = os.environ.get(var)
+ return env_vars, parallel_sum(100)
+
+
+@parametrize("backend", ([None, 'loky'] if mp is not None else [None]))
+@skipif(parallel_sum is None, reason="Need OpenMP helper compiled")
+def test_parallel_thread_limit(backend):
+ results = Parallel(n_jobs=2, backend=backend)(
+ delayed(_run_parallel_sum)() for _ in range(2)
+ )
+ expected_num_threads = max(cpu_count() // 2, 1)
+ for worker_env_vars, omp_num_threads in results:
+ assert omp_num_threads == expected_num_threads
+ for name, value in worker_env_vars.items():
+ if name.endswith("_THREADS"):
+ assert value == str(expected_num_threads)
+ else:
+ assert name == "ENABLE_IPC"
+ assert value == "1"
+
+
+@skipif(distributed is not None,
+ reason='This test requires dask NOT installed')
+def test_dask_backend_when_dask_not_installed():
+ with raises(ValueError, match='Please install dask'):
+ parallel_backend('dask')
+
+
+def test_zero_worker_backend():
+ # joblib.Parallel should reject with an explicit error message parallel
+ # backends that have no worker.
+ class ZeroWorkerBackend(ThreadingBackend):
+ def configure(self, *args, **kwargs):
+ return 0
+
+ def apply_async(self, func, callback=None): # pragma: no cover
+ raise TimeoutError("No worker available")
+
+ def effective_n_jobs(self, n_jobs): # pragma: no cover
+ return 0
+
+ expected_msg = "ZeroWorkerBackend has no active worker"
+ with parallel_backend(ZeroWorkerBackend()):
+ with pytest.raises(RuntimeError, match=expected_msg):
+ Parallel(n_jobs=2)(delayed(id)(i) for i in range(2))
+
+
+def test_globals_update_at_each_parallel_call():
+ # This is a non-regression test related to joblib issues #836 and #833.
+ # Cloudpickle versions between 0.5.4 and 0.7 introduced a bug where global
+ # variables changes in a parent process between two calls to
+ # joblib.Parallel would not be propagated into the workers.
+ global MY_GLOBAL_VARIABLE
+ MY_GLOBAL_VARIABLE = "original value"
+
+ def check_globals():
+ global MY_GLOBAL_VARIABLE
+ return MY_GLOBAL_VARIABLE
+
+ assert check_globals() == "original value"
+
+ workers_global_variable = Parallel(n_jobs=2)(
+ delayed(check_globals)() for i in range(2))
+ assert set(workers_global_variable) == {"original value"}
+
+ # Change the value of MY_GLOBAL_VARIABLE, and make sure this change gets
+ # propagated into the workers environment
+ MY_GLOBAL_VARIABLE = "changed value"
+ assert check_globals() == "changed value"
+
+ workers_global_variable = Parallel(n_jobs=2)(
+ delayed(check_globals)() for i in range(2))
+ assert set(workers_global_variable) == {"changed value"}
+
+
+##############################################################################
+# Test environment variable in child env, in particular for limiting
+# the maximal number of threads in C-library threadpools.
+#
+
+def _check_numpy_threadpool_limits():
+ import numpy as np
+ # Let's call BLAS on a Matrix Matrix multiplication with dimensions large
+ # enough to ensure that the threadpool managed by the underlying BLAS
+ # implementation is actually used so as to force its initialization.
+ a = np.random.randn(100, 100)
+ np.dot(a, a)
+ from threadpoolctl import threadpool_info
+ return threadpool_info()
+
+
+def _parent_max_num_threads_for(child_module, parent_info):
+ for parent_module in parent_info:
+ if parent_module['filepath'] == child_module['filepath']:
+ return parent_module['num_threads']
+ raise ValueError("An unexpected module was loaded in child:\n{}"
+ .format(child_module))
+
+
+def check_child_num_threads(workers_info, parent_info, num_threads):
+ # Check that the number of threads reported in workers_info is consistent
+ # with the expectation. We need to be careful to handle the cases where
+ # the requested number of threads is below max_num_thread for the library.
+ for child_threadpool_info in workers_info:
+ for child_module in child_threadpool_info:
+ parent_max_num_threads = _parent_max_num_threads_for(
+ child_module, parent_info)
+ expected = {min(num_threads, parent_max_num_threads), num_threads}
+ assert child_module['num_threads'] in expected
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('n_jobs', [2, 4, -2, -1])
+def test_threadpool_limitation_in_child(n_jobs):
+ # Check that the protection against oversubscription in workers is working
+ # using threadpoolctl functionalities.
+
+ # Skip this test if numpy is not linked to a BLAS library
+ parent_info = _check_numpy_threadpool_limits()
+ if len(parent_info) == 0:
+ pytest.skip(msg="Need a version of numpy linked to BLAS")
+
+ workers_threadpool_infos = Parallel(n_jobs=n_jobs)(
+ delayed(_check_numpy_threadpool_limits)() for i in range(2))
+
+ n_jobs = effective_n_jobs(n_jobs)
+ expected_child_num_threads = max(cpu_count() // n_jobs, 1)
+
+ check_child_num_threads(workers_threadpool_infos, parent_info,
+ expected_child_num_threads)
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('inner_max_num_threads', [1, 2, 4, None])
+@parametrize('n_jobs', [2, -1])
+def test_threadpool_limitation_in_child_context(n_jobs, inner_max_num_threads):
+ # Check that the protection against oversubscription in workers is working
+ # using threadpoolctl functionalities.
+
+ # Skip this test if numpy is not linked to a BLAS library
+ parent_info = _check_numpy_threadpool_limits()
+ if len(parent_info) == 0:
+ pytest.skip(msg="Need a version of numpy linked to BLAS")
+
+ with parallel_backend('loky', inner_max_num_threads=inner_max_num_threads):
+ workers_threadpool_infos = Parallel(n_jobs=n_jobs)(
+ delayed(_check_numpy_threadpool_limits)() for i in range(2))
+
+ n_jobs = effective_n_jobs(n_jobs)
+ if inner_max_num_threads is None:
+ expected_child_num_threads = max(cpu_count() // n_jobs, 1)
+ else:
+ expected_child_num_threads = inner_max_num_threads
+
+ check_child_num_threads(workers_threadpool_infos, parent_info,
+ expected_child_num_threads)
+
+
+@with_multiprocessing
+@parametrize('n_jobs', [2, -1])
+@parametrize('var_name', ["OPENBLAS_NUM_THREADS",
+ "MKL_NUM_THREADS",
+ "OMP_NUM_THREADS"])
+def test_threadpool_limitation_in_child_override(n_jobs, var_name):
+ # Check that environment variables set by the user on the main process
+ # always have the priority.
+
+ # Clean up the existing executor because we change the environment of the
+ # parent at runtime and it is not detected in loky intentionally.
+ get_reusable_executor(reuse=True).shutdown()
+
+ def _get_env(var_name):
+ return os.environ.get(var_name)
+
+ original_var_value = os.environ.get(var_name)
+ try:
+ os.environ[var_name] = "4"
+ # Skip this test if numpy is not linked to a BLAS library
+ results = Parallel(n_jobs=n_jobs)(
+ delayed(_get_env)(var_name) for i in range(2))
+ assert results == ["4", "4"]
+
+ with parallel_backend('loky', inner_max_num_threads=1):
+ results = Parallel(n_jobs=n_jobs)(
+ delayed(_get_env)(var_name) for i in range(2))
+ assert results == ["1", "1"]
+
+ finally:
+ if original_var_value is None:
+ del os.environ[var_name]
+ else:
+ os.environ[var_name] = original_var_value
+
+
+@with_numpy
+@with_multiprocessing
+@parametrize('backend', ['multiprocessing', 'threading',
+ MultiprocessingBackend(), ThreadingBackend()])
+def test_threadpool_limitation_in_child_context_error(backend):
+
+ with raises(AssertionError, match=r"does not acc.*inner_max_num_threads"):
+ parallel_backend(backend, inner_max_num_threads=1)
+
+
+@with_multiprocessing
+@parametrize('n_jobs', [2, 4, -1])
+def test_loky_reuse_workers(n_jobs):
+ # Non-regression test for issue #967 where the workers are not reused when
+ # calling multiple Parallel loops.
+
+ def parallel_call(n_jobs):
+ x = range(10)
+ Parallel(n_jobs=n_jobs)(delayed(sum)(x) for i in range(10))
+
+ # Run a parallel loop and get the workers used for computations
+ parallel_call(n_jobs)
+ first_executor = get_reusable_executor(reuse=True)
+
+ # Ensure that the workers are reused for the next calls, as the executor is
+ # not restarted.
+ for _ in range(10):
+ parallel_call(n_jobs)
+ executor = get_reusable_executor(reuse=True)
+ assert executor == first_executor
diff --git a/runtime/Lib/site-packages/joblib/test/test_store_backends.py b/runtime/Lib/site-packages/joblib/test/test_store_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c6198fa675fe81ec38dc3b2a4596df16d002c3f
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_store_backends.py
@@ -0,0 +1,56 @@
+try:
+ # Python 2.7: use the C pickle to speed up
+ # test_concurrency_safe_write which pickles big python objects
+ import cPickle as cpickle
+except ImportError:
+ import pickle as cpickle
+import functools
+import time
+
+from joblib.testing import parametrize, timeout
+from joblib.test.common import with_multiprocessing
+from joblib.backports import concurrency_safe_rename
+from joblib import Parallel, delayed
+from joblib._store_backends import concurrency_safe_write
+
+
+def write_func(output, filename):
+ with open(filename, 'wb') as f:
+ cpickle.dump(output, f)
+
+
+def load_func(expected, filename):
+ for i in range(10):
+ try:
+ with open(filename, 'rb') as f:
+ reloaded = cpickle.load(f)
+ break
+ except (OSError, IOError):
+ # On Windows you can have WindowsError ([Error 5] Access
+ # is denied or [Error 13] Permission denied) when reading the file,
+ # probably because a writer process has a lock on the file
+ time.sleep(0.1)
+ else:
+ raise
+ assert expected == reloaded
+
+
+def concurrency_safe_write_rename(to_write, filename, write_func):
+ temporary_filename = concurrency_safe_write(to_write,
+ filename, write_func)
+ concurrency_safe_rename(temporary_filename, filename)
+
+
+@timeout(0) # No timeout as this test can be long
+@with_multiprocessing
+@parametrize('backend', ['multiprocessing', 'loky', 'threading'])
+def test_concurrency_safe_write(tmpdir, backend):
+ # Add one item to cache
+ filename = tmpdir.join('test.pkl').strpath
+
+ obj = {str(i): i for i in range(int(1e5))}
+ funcs = [functools.partial(concurrency_safe_write_rename,
+ write_func=write_func)
+ if i % 3 != 2 else load_func for i in range(12)]
+ Parallel(n_jobs=2, backend=backend)(
+ delayed(func)(obj, filename) for func in funcs)
diff --git a/runtime/Lib/site-packages/joblib/test/test_testing.py b/runtime/Lib/site-packages/joblib/test/test_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..39ac88097c9e3763fd346e2ca70a1a8688bc3a5a
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_testing.py
@@ -0,0 +1,73 @@
+import sys
+import re
+
+from joblib.testing import raises, check_subprocess_call
+
+
+def test_check_subprocess_call():
+ code = '\n'.join(['result = 1 + 2 * 3',
+ 'print(result)',
+ 'my_list = [1, 2, 3]',
+ 'print(my_list)'])
+
+ check_subprocess_call([sys.executable, '-c', code])
+
+ # Now checking stdout with a regex
+ check_subprocess_call([sys.executable, '-c', code],
+ # Regex needed for platform-specific line endings
+ stdout_regex=r'7\s{1,2}\[1, 2, 3\]')
+
+
+def test_check_subprocess_call_non_matching_regex():
+ code = '42'
+ non_matching_pattern = '_no_way_this_matches_anything_'
+
+ with raises(ValueError) as excinfo:
+ check_subprocess_call([sys.executable, '-c', code],
+ stdout_regex=non_matching_pattern)
+ excinfo.match('Unexpected stdout.+{}'.format(non_matching_pattern))
+
+
+def test_check_subprocess_call_wrong_command():
+ wrong_command = '_a_command_that_does_not_exist_'
+ with raises(OSError):
+ check_subprocess_call([wrong_command])
+
+
+def test_check_subprocess_call_non_zero_return_code():
+ code_with_non_zero_exit = '\n'.join([
+ 'import sys',
+ 'print("writing on stdout")',
+ 'sys.stderr.write("writing on stderr")',
+ 'sys.exit(123)'])
+
+ pattern = re.compile('Non-zero return code: 123.+'
+ 'Stdout:\nwriting on stdout.+'
+ 'Stderr:\nwriting on stderr', re.DOTALL)
+
+ with raises(ValueError) as excinfo:
+ check_subprocess_call([sys.executable, '-c', code_with_non_zero_exit])
+ excinfo.match(pattern)
+
+
+def test_check_subprocess_call_timeout():
+ code_timing_out = '\n'.join([
+ 'import time',
+ 'import sys',
+ 'print("before sleep on stdout")',
+ 'sys.stdout.flush()',
+ 'sys.stderr.write("before sleep on stderr")',
+ 'sys.stderr.flush()',
+ 'time.sleep(1.1)',
+ 'print("process should have be killed before")',
+ 'sys.stdout.flush()'])
+
+ pattern = re.compile('Non-zero return code:.+'
+ 'Stdout:\nbefore sleep on stdout\\s+'
+ 'Stderr:\nbefore sleep on stderr',
+ re.DOTALL)
+
+ with raises(ValueError) as excinfo:
+ check_subprocess_call([sys.executable, '-c', code_timing_out],
+ timeout=1)
+ excinfo.match(pattern)
diff --git a/runtime/Lib/site-packages/joblib/test/test_utils.py b/runtime/Lib/site-packages/joblib/test/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4999a212c462bdb6c10e9e08fdfba74d03b05294
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/test_utils.py
@@ -0,0 +1,27 @@
+import pytest
+
+from joblib._utils import eval_expr
+
+
+@pytest.mark.parametrize(
+ "expr",
+ ["exec('import os')", "print(1)", "import os", "1+1; import os", "1^1"],
+)
+def test_eval_expr_invalid(expr):
+ with pytest.raises(
+ ValueError, match="is not a valid or supported arithmetic"
+ ):
+ eval_expr(expr)
+
+
+@pytest.mark.parametrize(
+ "expr, result",
+ [
+ ("2*6", 12),
+ ("2**6", 64),
+ ("1 + 2*3**(4) / (6 + -7)", -161.0),
+ ("(20 // 3) % 5", 1),
+ ],
+)
+def test_eval_expr_valid(expr, result):
+ assert eval_expr(expr) == result
diff --git a/runtime/Lib/site-packages/joblib/test/testutils.py b/runtime/Lib/site-packages/joblib/test/testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..20ec8c1ba0a50da6be9fce3686ac1950b1a55ab5
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/test/testutils.py
@@ -0,0 +1,8 @@
+def return_slice_of_data(arr, start_idx, end_idx):
+ return arr[start_idx:end_idx]
+
+
+def print_filename_and_raise(arr):
+ from joblib._memmapping_reducer import _get_backing_memmap
+ print(_get_backing_memmap(arr).filename)
+ raise ValueError
diff --git a/runtime/Lib/site-packages/joblib/testing.py b/runtime/Lib/site-packages/joblib/testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8939f056f49a1822f0b5aeff649cb57105bb9e4
--- /dev/null
+++ b/runtime/Lib/site-packages/joblib/testing.py
@@ -0,0 +1,79 @@
+"""
+Helper for testing.
+"""
+
+import sys
+import warnings
+import os.path
+import re
+import subprocess
+import threading
+
+import pytest
+import _pytest
+
+
+raises = pytest.raises
+warns = pytest.warns
+SkipTest = _pytest.runner.Skipped
+skipif = pytest.mark.skipif
+fixture = pytest.fixture
+parametrize = pytest.mark.parametrize
+timeout = pytest.mark.timeout
+xfail = pytest.mark.xfail
+param = pytest.param
+
+
+def warnings_to_stdout():
+ """ Redirect all warnings to stdout.
+ """
+ showwarning_orig = warnings.showwarning
+
+ def showwarning(msg, cat, fname, lno, file=None, line=0):
+ showwarning_orig(msg, cat, os.path.basename(fname), line, sys.stdout)
+
+ warnings.showwarning = showwarning
+ # warnings.simplefilter('always')
+
+
+def check_subprocess_call(cmd, timeout=5, stdout_regex=None,
+ stderr_regex=None):
+ """Runs a command in a subprocess with timeout in seconds.
+
+ Also checks returncode is zero, stdout if stdout_regex is set, and
+ stderr if stderr_regex is set.
+ """
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ def kill_process():
+ warnings.warn("Timeout running {}".format(cmd))
+ proc.kill()
+
+ try:
+ if timeout is not None:
+ timer = threading.Timer(timeout, kill_process)
+ timer.start()
+ stdout, stderr = proc.communicate()
+ stdout, stderr = stdout.decode(), stderr.decode()
+ if proc.returncode != 0:
+ message = (
+ 'Non-zero return code: {}.\nStdout:\n{}\n'
+ 'Stderr:\n{}').format(
+ proc.returncode, stdout, stderr)
+ raise ValueError(message)
+
+ if (stdout_regex is not None and
+ not re.search(stdout_regex, stdout)):
+ raise ValueError(
+ "Unexpected stdout: {!r} does not match:\n{!r}".format(
+ stdout_regex, stdout))
+ if (stderr_regex is not None and
+ not re.search(stderr_regex, stderr)):
+ raise ValueError(
+ "Unexpected stderr: {!r} does not match:\n{!r}".format(
+ stderr_regex, stderr))
+
+ finally:
+ if timeout is not None:
+ timer.cancel()
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/INSTALLER b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/METADATA b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..07ec3f119bd9c7d0ed723219ee0a381e9e032cc1
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/METADATA
@@ -0,0 +1,195 @@
+Metadata-Version: 2.1
+Name: jsonschema
+Version: 4.17.3
+Summary: An implementation of JSON Schema validation for Python
+Project-URL: Homepage, https://github.com/python-jsonschema/jsonschema
+Project-URL: Documentation, https://python-jsonschema.readthedocs.io/
+Project-URL: Issues, https://github.com/python-jsonschema/jsonschema/issues/
+Project-URL: Funding, https://github.com/sponsors/Julian
+Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-jsonschema?utm_source=pypi-jsonschema&utm_medium=referral&utm_campaign=pypi-link
+Project-URL: Changelog, https://github.com/python-jsonschema/jsonschema/blob/main/CHANGELOG.rst
+Project-URL: Source, https://github.com/python-jsonschema/jsonschema
+Author: Julian Berman
+Author-email: Julian+jsonschema@GrayVines.com
+License: MIT
+License-File: COPYING
+Keywords: data validation,json,jsonschema,validation
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Requires-Python: >=3.7
+Requires-Dist: attrs>=17.4.0
+Requires-Dist: importlib-metadata; python_version < '3.8'
+Requires-Dist: importlib-resources>=1.4.0; python_version < '3.9'
+Requires-Dist: pkgutil-resolve-name>=1.3.10; python_version < '3.9'
+Requires-Dist: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0
+Requires-Dist: typing-extensions; python_version < '3.8'
+Provides-Extra: format
+Requires-Dist: fqdn; extra == 'format'
+Requires-Dist: idna; extra == 'format'
+Requires-Dist: isoduration; extra == 'format'
+Requires-Dist: jsonpointer>1.13; extra == 'format'
+Requires-Dist: rfc3339-validator; extra == 'format'
+Requires-Dist: rfc3987; extra == 'format'
+Requires-Dist: uri-template; extra == 'format'
+Requires-Dist: webcolors>=1.11; extra == 'format'
+Provides-Extra: format-nongpl
+Requires-Dist: fqdn; extra == 'format-nongpl'
+Requires-Dist: idna; extra == 'format-nongpl'
+Requires-Dist: isoduration; extra == 'format-nongpl'
+Requires-Dist: jsonpointer>1.13; extra == 'format-nongpl'
+Requires-Dist: rfc3339-validator; extra == 'format-nongpl'
+Requires-Dist: rfc3986-validator>0.1.0; extra == 'format-nongpl'
+Requires-Dist: uri-template; extra == 'format-nongpl'
+Requires-Dist: webcolors>=1.11; extra == 'format-nongpl'
+Description-Content-Type: text/x-rst
+
+==========
+jsonschema
+==========
+
+|PyPI| |Pythons| |CI| |ReadTheDocs| |Precommit| |Zenodo|
+
+.. |PyPI| image:: https://img.shields.io/pypi/v/jsonschema.svg
+ :alt: PyPI version
+ :target: https://pypi.org/project/jsonschema/
+
+.. |Pythons| image:: https://img.shields.io/pypi/pyversions/jsonschema.svg
+ :alt: Supported Python versions
+ :target: https://pypi.org/project/jsonschema/
+
+.. |CI| image:: https://github.com/python-jsonschema/jsonschema/workflows/CI/badge.svg
+ :alt: Build status
+ :target: https://github.com/python-jsonschema/jsonschema/actions?query=workflow%3ACI
+
+.. |ReadTheDocs| image:: https://readthedocs.org/projects/python-jsonschema/badge/?version=stable&style=flat
+ :alt: ReadTheDocs status
+ :target: https://python-jsonschema.readthedocs.io/en/stable/
+
+.. |Precommit| image:: https://results.pre-commit.ci/badge/github/python-jsonschema/jsonschema/main.svg
+ :alt: pre-commit.ci status
+ :target: https://results.pre-commit.ci/latest/github/python-jsonschema/jsonschema/main
+
+.. |Zenodo| image:: https://zenodo.org/badge/3072629.svg
+ :target: https://zenodo.org/badge/latestdoi/3072629
+
+
+``jsonschema`` is an implementation of the `JSON Schema
+`_ specification for Python.
+
+.. code-block:: python
+
+ >>> from jsonschema import validate
+
+ >>> # A sample schema, like what we'd get from json.load()
+ >>> schema = {
+ ... "type" : "object",
+ ... "properties" : {
+ ... "price" : {"type" : "number"},
+ ... "name" : {"type" : "string"},
+ ... },
+ ... }
+
+ >>> # If no exception is raised by validate(), the instance is valid.
+ >>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)
+
+ >>> validate(
+ ... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema,
+ ... ) # doctest: +IGNORE_EXCEPTION_DETAIL
+ Traceback (most recent call last):
+ ...
+ ValidationError: 'Invalid' is not of type 'number'
+
+It can also be used from console:
+
+.. code-block:: bash
+
+ $ jsonschema --instance sample.json sample.schema
+
+Features
+--------
+
+* Partial support for
+ `Draft 2020-12 `_ and
+ `Draft 2019-09 `_,
+ except for ``dynamicRef`` / ``recursiveRef`` and ``$vocabulary`` (in-progress).
+ Full support for
+ `Draft 7 `_,
+ `Draft 6 `_,
+ `Draft 4 `_
+ and
+ `Draft 3 `_
+
+* `Lazy validation `_
+ that can iteratively report *all* validation errors.
+
+* `Programmatic querying `_
+ of which properties or items failed validation.
+
+
+Installation
+------------
+
+``jsonschema`` is available on `PyPI `_. You can install using `pip `_:
+
+.. code-block:: bash
+
+ $ pip install jsonschema
+
+
+Extras
+======
+
+Two extras are available when installing the package, both currently related to ``format`` validation:
+
+ * ``format``
+ * ``format-nongpl``
+
+They can be used when installing in order to include additional dependencies, e.g.:
+
+.. code-block:: bash
+
+ $ pip install jsonschema'[format]'
+
+Be aware that the mere presence of these dependencies – or even the specification of ``format`` checks in a schema – do *not* activate format checks (as per the specification).
+Please read the `format validation documentation `_ for further details.
+
+About
+-----
+
+I'm Julian Berman.
+
+``jsonschema`` is on `GitHub `_.
+
+Get in touch, via GitHub or otherwise, if you've got something to contribute,
+it'd be most welcome!
+
+You can also generally find me on Libera (nick: ``Julian``) in various
+channels, including ``#python``.
+
+If you feel overwhelmingly grateful, you can also `sponsor me
+`_.
+
+And for companies who appreciate ``jsonschema`` and its continued support
+and growth, ``jsonschema`` is also now supportable via `TideLift
+`_.
+
+
+Release Information
+-------------------
+
+v4.17.3
+=======
+
+* Fix instantiating validators with cached refs to boolean schemas
+ rather than objects (#1018).
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/RECORD b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..b4b9a88f2f407e0d36de6046372a57b856caebf5
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/RECORD
@@ -0,0 +1,80 @@
+../../Scripts/jsonschema.exe,sha256=9mLg17ExbafPiGPeeJhGghnLtshNQiLyxEMqUL8-EMs,108386
+jsonschema-4.17.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+jsonschema-4.17.3.dist-info/METADATA,sha256=YnDEs-j6S4At_Fq54u7PqfYG4gQT8E5nrp8vu2PXeXw,7879
+jsonschema-4.17.3.dist-info/RECORD,,
+jsonschema-4.17.3.dist-info/WHEEL,sha256=NaLmgHHW_f9jTvv_wRh9vcK7c7EK9o5fwsIXMOzoGgM,87
+jsonschema-4.17.3.dist-info/entry_points.txt,sha256=vO7rX4Fs_xIVJy2pnAtKgTSxfpnozAVQ0DjCmpMxnWE,51
+jsonschema-4.17.3.dist-info/licenses/COPYING,sha256=T5KgFaE8TRoEC-8BiqE0MLTxvHO0Gxa7hGw0Z2bedDk,1057
+jsonschema/__init__.py,sha256=FRdJDXN8-AFk-Fj1qclckQsZNeGQB__r_QuMjtRoze4,2187
+jsonschema/__main__.py,sha256=Sfz1ZNeogymj_KZxq6JXY3F6O_1v28sLIiskusifQ5s,40
+jsonschema/__pycache__/__init__.cpython-39.pyc,,
+jsonschema/__pycache__/__main__.cpython-39.pyc,,
+jsonschema/__pycache__/_format.cpython-39.pyc,,
+jsonschema/__pycache__/_legacy_validators.cpython-39.pyc,,
+jsonschema/__pycache__/_types.cpython-39.pyc,,
+jsonschema/__pycache__/_utils.cpython-39.pyc,,
+jsonschema/__pycache__/_validators.cpython-39.pyc,,
+jsonschema/__pycache__/cli.cpython-39.pyc,,
+jsonschema/__pycache__/exceptions.cpython-39.pyc,,
+jsonschema/__pycache__/protocols.cpython-39.pyc,,
+jsonschema/__pycache__/validators.cpython-39.pyc,,
+jsonschema/_format.py,sha256=P7gjEZzWa1dU0wDu3NbyG1cNW6drM3i454a_7sJE8TY,14575
+jsonschema/_legacy_validators.py,sha256=0KDc3X0gTzuW52NRQJ123ZW_IBLcIDsBaVFVfMo_vNY,10549
+jsonschema/_types.py,sha256=YgKkjzf97pKRsiuc5RN76jJPGCpmdMHJlhcOVWjCW78,5425
+jsonschema/_utils.py,sha256=D3oRGTSk6llsZDFdDAVQWBEi62Uy_4SWVbjPiG9PJcs,10429
+jsonschema/_validators.py,sha256=4H0TI2BIXhmJrmF3iC1VzKgxwhCfiGreJfBWBtP20HY,15956
+jsonschema/benchmarks/__init__.py,sha256=A0sQrxDBVHSyQ-8ru3L11hMXf3q9gVuB9x_YgHb4R9M,70
+jsonschema/benchmarks/__pycache__/__init__.cpython-39.pyc,,
+jsonschema/benchmarks/__pycache__/issue232.cpython-39.pyc,,
+jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-39.pyc,,
+jsonschema/benchmarks/issue232.py,sha256=GKQBwm03sf-pPSxBxc4YDvBBnMYknOk6m-WtTntN5VE,506
+jsonschema/benchmarks/issue232/issue.json,sha256=eaPOZjMRu5u8RpKrsA9uk7ucPZS5tkKG4D_hkOTQ3Hk,117105
+jsonschema/benchmarks/json_schema_test_suite.py,sha256=PvfabpUYcF4_7csYDTcTauED8rnFEGYbdY5RqTXD08s,320
+jsonschema/cli.py,sha256=DJhWQs6X5nsmWfUqrnSjmAdzg5Sbd3igcRGguHJAEQU,8518
+jsonschema/exceptions.py,sha256=asZ8nwPwuQlMCXTb7Ztyi1OuxkqRiPnxK9TuwiDqGRo,11336
+jsonschema/protocols.py,sha256=zfj-Rmc2rsNIQjEIFnnMsHlYEoS-rprnBHTG5pgvCy0,7295
+jsonschema/schemas/draft2019-09.json,sha256=e3YbPhIfCgyh6ioLjizIVrz4AWBLgmjXG6yqICvAwTs,1785
+jsonschema/schemas/draft2020-12.json,sha256=Qdp29a-3zgYtJI92JGOpL3ykfk4PkFsiS6av7vkd7Q8,2452
+jsonschema/schemas/draft3.json,sha256=LPdfZENvtb43Si6qJ6uLfh_WUcm0ba6mxnsC_WTiRYs,2600
+jsonschema/schemas/draft4.json,sha256=4UidC0dV8CeTMCWR0_y48Htok6gqlPJIlfjk7fEbguI,4357
+jsonschema/schemas/draft6.json,sha256=wp386fVINcOgbAOzxdXsDtp3cGVo-cTffPvHVmpRAG0,4437
+jsonschema/schemas/draft7.json,sha256=PVOSCIJhYGxVm2A_OFMpyfGrRbXWZ-uZBodFOwVdQF4,4819
+jsonschema/schemas/vocabularies/draft2019-09/applicator,sha256=aJUQDplyb7sQcFhRK77D7P1LJOj9L6zuPlBe5ysNTDE,1860
+jsonschema/schemas/vocabularies/draft2019-09/content,sha256=m31PVaTi_bAsQwBo_f-rxzKt3OI42j8d8mkCScM1MnQ,517
+jsonschema/schemas/vocabularies/draft2019-09/core,sha256=taLElX9kldClCB8ECevooU5BOayyA_x0hHH47eKvWyw,1531
+jsonschema/schemas/vocabularies/draft2019-09/meta-data,sha256=1H4kRd1qgicaKY2DzGxsuNSuHhXg3Fa-zTehY-zwEoY,892
+jsonschema/schemas/vocabularies/draft2019-09/validation,sha256=HlJsHTNac0gF_ILPV5jBK5YK19olF8Zs2lobCTWcPBw,2834
+jsonschema/schemas/vocabularies/draft2020-12/applicator,sha256=xKbkFHuR_vf-ptwFjLG_k0AvdBS3ZXiosWqvHa1qrO8,1659
+jsonschema/schemas/vocabularies/draft2020-12/content,sha256=CDQ3R3ZOSlgUJieTz01lIFenkThjxZUNQyl-jh_axbY,519
+jsonschema/schemas/vocabularies/draft2020-12/core,sha256=wtEqjk3RHTNt_IOj9mOqTGnwtJs76wlP_rJbUxb0gD0,1564
+jsonschema/schemas/vocabularies/draft2020-12/format,sha256=UOu_55BhGoSbjMQAoJwdDg-2q1wNQ6DyIgH9NiUFa_Q,403
+jsonschema/schemas/vocabularies/draft2020-12/format-annotation,sha256=q8d1rf79idIjWBcNm_k_Tr0jSVY7u-3WDwK-98gSvMA,448
+jsonschema/schemas/vocabularies/draft2020-12/format-assertion,sha256=xSJCuaG7eGsmw-gset1CjDH5yW5XXc6Z5W6l_qptogw,445
+jsonschema/schemas/vocabularies/draft2020-12/meta-data,sha256=j3bW4U9Bubku-TO3CM3FFEyLUmhlGtEZGEhfsXVPHHY,892
+jsonschema/schemas/vocabularies/draft2020-12/unevaluated,sha256=Lb-8tzmUtnCwl2SSre4f_7RsIWgnhNL1pMpWH54tDLQ,506
+jsonschema/schemas/vocabularies/draft2020-12/validation,sha256=cBCjHlQfMtK-ch4t40jfdcmzaHaj7TBId_wKvaHTelg,2834
+jsonschema/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+jsonschema/tests/__pycache__/__init__.cpython-39.pyc,,
+jsonschema/tests/__pycache__/_helpers.cpython-39.pyc,,
+jsonschema/tests/__pycache__/_suite.cpython-39.pyc,,
+jsonschema/tests/__pycache__/fuzz_validate.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_cli.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_deprecations.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_exceptions.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_format.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_types.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_utils.cpython-39.pyc,,
+jsonschema/tests/__pycache__/test_validators.cpython-39.pyc,,
+jsonschema/tests/_helpers.py,sha256=yoWpWVYq4auuTPPd1_8FXV77RlczQtiyutSh6c191ZM,618
+jsonschema/tests/_suite.py,sha256=EyzqI3EGlJiMX_o3C-W51J2m4JVRU0uqrWFjdmCspgI,7052
+jsonschema/tests/fuzz_validate.py,sha256=fUA7yTJIihaCwJplkUehZeyB84HcXEcqtY5oPJXIO7I,1114
+jsonschema/tests/test_cli.py,sha256=e9kjwfVp1sSBCF9ffGH7FwgcRlTaBZUehcWiM-BmmLk,28857
+jsonschema/tests/test_deprecations.py,sha256=uf0ct-i9V3UBc3zm8DRcgxCitURKl2-Qt3wpAUoK0GU,9284
+jsonschema/tests/test_exceptions.py,sha256=vvh4zfHVvE9egGn4qc1jQo2s8fh09oVt1WcCRpaKivM,19639
+jsonschema/tests/test_format.py,sha256=h79gKpcKV58qOQOn8TsJNf2HFkrUYzNZ3Uai_cc2nQE,3810
+jsonschema/tests/test_jsonschema_test_suite.py,sha256=-sUumFw_1MTcfMGrG5-Zw3_yldVHCto6SxPh-aoh64g,18090
+jsonschema/tests/test_types.py,sha256=_m7chMGj9U5G57jB_CmUuP5mSit3PET584ehoIlKkf4,6983
+jsonschema/tests/test_utils.py,sha256=lJRVYyQeZQTUCTU_M3BhlkxPMgjsc8KQCd7U_Qkook8,3749
+jsonschema/tests/test_validators.py,sha256=JW4Y5mzVMuumYdBCEFhxPO7EIqN-k2MnbwzBXHq7LIE,78785
+jsonschema/validators.py,sha256=zwfdaiQFvH-Z9EoEH-G_Bh8hCQzOirJg6-_AFoT8_ow,38150
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/WHEEL b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..6d803659b75f74a2396884b98634329099146ede
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.11.1
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/entry_points.txt b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/entry_points.txt
new file mode 100644
index 0000000000000000000000000000000000000000..eecef9d8fad351de6b048532776160696a796ef9
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/entry_points.txt
@@ -0,0 +1,2 @@
+[console_scripts]
+jsonschema = jsonschema.cli:main
diff --git a/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/licenses/COPYING b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/licenses/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..af9cfbdb134f42e5205ecbad597421d778826481
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema-4.17.3.dist-info/licenses/COPYING
@@ -0,0 +1,19 @@
+Copyright (c) 2013 Julian Berman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/runtime/Lib/site-packages/jsonschema/__init__.py b/runtime/Lib/site-packages/jsonschema/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6628fc7eb9943f357b9bbc27b8e6a47c03a87d32
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/__init__.py
@@ -0,0 +1,71 @@
+"""
+An implementation of JSON Schema for Python
+
+The main functionality is provided by the validator classes for each of the
+supported JSON Schema versions.
+
+Most commonly, `jsonschema.validators.validate` is the quickest way to simply
+validate a given instance under a schema, and will create a validator
+for you.
+"""
+import warnings
+
+from jsonschema._format import FormatChecker
+from jsonschema._types import TypeChecker
+from jsonschema.exceptions import (
+ ErrorTree,
+ FormatError,
+ RefResolutionError,
+ SchemaError,
+ ValidationError,
+)
+from jsonschema.protocols import Validator
+from jsonschema.validators import (
+ Draft3Validator,
+ Draft4Validator,
+ Draft6Validator,
+ Draft7Validator,
+ Draft201909Validator,
+ Draft202012Validator,
+ RefResolver,
+ validate,
+)
+
+
+def __getattr__(name):
+ if name == "__version__":
+ warnings.warn(
+ "Accessing jsonschema.__version__ is deprecated and will be "
+ "removed in a future release. Use importlib.metadata directly "
+ "to query for jsonschema's version.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ try:
+ from importlib import metadata
+ except ImportError:
+ import importlib_metadata as metadata
+
+ return metadata.version("jsonschema")
+
+ format_checkers = {
+ "draft3_format_checker": Draft3Validator,
+ "draft4_format_checker": Draft4Validator,
+ "draft6_format_checker": Draft6Validator,
+ "draft7_format_checker": Draft7Validator,
+ "draft201909_format_checker": Draft201909Validator,
+ "draft202012_format_checker": Draft202012Validator,
+ }
+ ValidatorForFormat = format_checkers.get(name)
+ if ValidatorForFormat is not None:
+ warnings.warn(
+ f"Accessing jsonschema.{name} is deprecated and will be "
+ "removed in a future release. Instead, use the FORMAT_CHECKER "
+ "attribute on the corresponding Validator.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return ValidatorForFormat.FORMAT_CHECKER
+
+ raise AttributeError(f"module {__name__} has no attribute {name}")
diff --git a/runtime/Lib/site-packages/jsonschema/__main__.py b/runtime/Lib/site-packages/jsonschema/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc21e230637107aea2900c54c10ba837c9b8f85
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/__main__.py
@@ -0,0 +1,3 @@
+from jsonschema.cli import main
+
+main()
diff --git a/runtime/Lib/site-packages/jsonschema/_format.py b/runtime/Lib/site-packages/jsonschema/_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ec97977ad310c9ed7e7eb8dcd4c474ba925d439
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/_format.py
@@ -0,0 +1,518 @@
+from __future__ import annotations
+
+from contextlib import suppress
+from uuid import UUID
+import datetime
+import ipaddress
+import re
+import typing
+import warnings
+
+from jsonschema.exceptions import FormatError
+
+_FormatCheckCallable = typing.Callable[[object], bool]
+_F = typing.TypeVar("_F", bound=_FormatCheckCallable)
+_RaisesType = typing.Union[
+ typing.Type[Exception], typing.Tuple[typing.Type[Exception], ...],
+]
+
+
+class FormatChecker:
+ """
+ A ``format`` property checker.
+
+ JSON Schema does not mandate that the ``format`` property actually do any
+ validation. If validation is desired however, instances of this class can
+ be hooked into validators to enable format validation.
+
+ `FormatChecker` objects always return ``True`` when asked about
+ formats that they do not know how to validate.
+
+ To add a check for a custom format use the `FormatChecker.checks`
+ decorator.
+
+ Arguments:
+
+ formats:
+
+ The known formats to validate. This argument can be used to
+ limit which formats will be used during validation.
+ """
+
+ checkers: dict[
+ str,
+ tuple[_FormatCheckCallable, _RaisesType],
+ ] = {}
+
+ def __init__(self, formats: typing.Iterable[str] | None = None):
+ if formats is None:
+ formats = self.checkers.keys()
+ self.checkers = {k: self.checkers[k] for k in formats}
+
+ def __repr__(self):
+ return "".format(sorted(self.checkers))
+
+ def checks(
+ self, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ """
+ Register a decorated function as validating a new format.
+
+ Arguments:
+
+ format:
+
+ The format that the decorated function will check.
+
+ raises:
+
+ The exception(s) raised by the decorated function when an
+ invalid instance is found.
+
+ The exception object will be accessible as the
+ `jsonschema.exceptions.ValidationError.cause` attribute of the
+ resulting validation error.
+ """
+
+ def _checks(func: _F) -> _F:
+ self.checkers[format] = (func, raises)
+ return func
+
+ return _checks
+
+ @classmethod
+ def cls_checks(
+ cls, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ warnings.warn(
+ (
+ "FormatChecker.cls_checks is deprecated. Call "
+ "FormatChecker.checks on a specific FormatChecker instance "
+ "instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return cls._cls_checks(format=format, raises=raises)
+
+ @classmethod
+ def _cls_checks(
+ cls, format: str, raises: _RaisesType = (),
+ ) -> typing.Callable[[_F], _F]:
+ def _checks(func: _F) -> _F:
+ cls.checkers[format] = (func, raises)
+ return func
+
+ return _checks
+
+ def check(self, instance: object, format: str) -> None:
+ """
+ Check whether the instance conforms to the given format.
+
+ Arguments:
+
+ instance (*any primitive type*, i.e. str, number, bool):
+
+ The instance to check
+
+ format:
+
+ The format that instance should conform to
+
+ Raises:
+
+ FormatError:
+
+ if the instance does not conform to ``format``
+ """
+
+ if format not in self.checkers:
+ return
+
+ func, raises = self.checkers[format]
+ result, cause = None, None
+ try:
+ result = func(instance)
+ except raises as e:
+ cause = e
+ if not result:
+ raise FormatError(f"{instance!r} is not a {format!r}", cause=cause)
+
+ def conforms(self, instance: object, format: str) -> bool:
+ """
+ Check whether the instance conforms to the given format.
+
+ Arguments:
+
+ instance (*any primitive type*, i.e. str, number, bool):
+
+ The instance to check
+
+ format:
+
+ The format that instance should conform to
+
+ Returns:
+
+ bool: whether it conformed
+ """
+
+ try:
+ self.check(instance, format)
+ except FormatError:
+ return False
+ else:
+ return True
+
+
+draft3_format_checker = FormatChecker()
+draft4_format_checker = FormatChecker()
+draft6_format_checker = FormatChecker()
+draft7_format_checker = FormatChecker()
+draft201909_format_checker = FormatChecker()
+draft202012_format_checker = FormatChecker()
+
+_draft_checkers: dict[str, FormatChecker] = dict(
+ draft3=draft3_format_checker,
+ draft4=draft4_format_checker,
+ draft6=draft6_format_checker,
+ draft7=draft7_format_checker,
+ draft201909=draft201909_format_checker,
+ draft202012=draft202012_format_checker,
+)
+
+
+def _checks_drafts(
+ name=None,
+ draft3=None,
+ draft4=None,
+ draft6=None,
+ draft7=None,
+ draft201909=None,
+ draft202012=None,
+ raises=(),
+) -> typing.Callable[[_F], _F]:
+ draft3 = draft3 or name
+ draft4 = draft4 or name
+ draft6 = draft6 or name
+ draft7 = draft7 or name
+ draft201909 = draft201909 or name
+ draft202012 = draft202012 or name
+
+ def wrap(func: _F) -> _F:
+ if draft3:
+ func = _draft_checkers["draft3"].checks(draft3, raises)(func)
+ if draft4:
+ func = _draft_checkers["draft4"].checks(draft4, raises)(func)
+ if draft6:
+ func = _draft_checkers["draft6"].checks(draft6, raises)(func)
+ if draft7:
+ func = _draft_checkers["draft7"].checks(draft7, raises)(func)
+ if draft201909:
+ func = _draft_checkers["draft201909"].checks(draft201909, raises)(
+ func,
+ )
+ if draft202012:
+ func = _draft_checkers["draft202012"].checks(draft202012, raises)(
+ func,
+ )
+
+ # Oy. This is bad global state, but relied upon for now, until
+ # deprecation. See #519 and test_format_checkers_come_with_defaults
+ FormatChecker._cls_checks(
+ draft202012 or draft201909 or draft7 or draft6 or draft4 or draft3,
+ raises,
+ )(func)
+ return func
+
+ return wrap
+
+
+@_checks_drafts(name="idn-email")
+@_checks_drafts(name="email")
+def is_email(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return "@" in instance
+
+
+@_checks_drafts(
+ draft3="ip-address",
+ draft4="ipv4",
+ draft6="ipv4",
+ draft7="ipv4",
+ draft201909="ipv4",
+ draft202012="ipv4",
+ raises=ipaddress.AddressValueError,
+)
+def is_ipv4(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(ipaddress.IPv4Address(instance))
+
+
+@_checks_drafts(name="ipv6", raises=ipaddress.AddressValueError)
+def is_ipv6(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ address = ipaddress.IPv6Address(instance)
+ return not getattr(address, "scope_id", "")
+
+
+with suppress(ImportError):
+ from fqdn import FQDN
+
+ @_checks_drafts(
+ draft3="host-name",
+ draft4="hostname",
+ draft6="hostname",
+ draft7="hostname",
+ draft201909="hostname",
+ draft202012="hostname",
+ )
+ def is_host_name(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return FQDN(instance).is_valid
+
+
+with suppress(ImportError):
+ # The built-in `idna` codec only implements RFC 3890, so we go elsewhere.
+ import idna
+
+ @_checks_drafts(
+ draft7="idn-hostname",
+ draft201909="idn-hostname",
+ draft202012="idn-hostname",
+ raises=(idna.IDNAError, UnicodeError),
+ )
+ def is_idn_host_name(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ idna.encode(instance)
+ return True
+
+
+try:
+ import rfc3987
+except ImportError:
+ with suppress(ImportError):
+ from rfc3986_validator import validate_rfc3986
+
+ @_checks_drafts(name="uri")
+ def is_uri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3986(instance, rule="URI")
+
+ @_checks_drafts(
+ draft6="uri-reference",
+ draft7="uri-reference",
+ draft201909="uri-reference",
+ draft202012="uri-reference",
+ raises=ValueError,
+ )
+ def is_uri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3986(instance, rule="URI_reference")
+
+else:
+
+ @_checks_drafts(
+ draft7="iri",
+ draft201909="iri",
+ draft202012="iri",
+ raises=ValueError,
+ )
+ def is_iri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="IRI")
+
+ @_checks_drafts(
+ draft7="iri-reference",
+ draft201909="iri-reference",
+ draft202012="iri-reference",
+ raises=ValueError,
+ )
+ def is_iri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="IRI_reference")
+
+ @_checks_drafts(name="uri", raises=ValueError)
+ def is_uri(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="URI")
+
+ @_checks_drafts(
+ draft6="uri-reference",
+ draft7="uri-reference",
+ draft201909="uri-reference",
+ draft202012="uri-reference",
+ raises=ValueError,
+ )
+ def is_uri_reference(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return rfc3987.parse(instance, rule="URI_reference")
+
+
+with suppress(ImportError):
+ from rfc3339_validator import validate_rfc3339
+
+ @_checks_drafts(name="date-time")
+ def is_datetime(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return validate_rfc3339(instance.upper())
+
+ @_checks_drafts(
+ draft7="time",
+ draft201909="time",
+ draft202012="time",
+ )
+ def is_time(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return is_datetime("1970-01-01T" + instance)
+
+
+@_checks_drafts(name="regex", raises=re.error)
+def is_regex(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(re.compile(instance))
+
+
+@_checks_drafts(
+ draft3="date",
+ draft7="date",
+ draft201909="date",
+ draft202012="date",
+ raises=ValueError,
+)
+def is_date(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(instance.isascii() and datetime.date.fromisoformat(instance))
+
+
+@_checks_drafts(draft3="time", raises=ValueError)
+def is_draft3_time(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(datetime.datetime.strptime(instance, "%H:%M:%S"))
+
+
+with suppress(ImportError):
+ from webcolors import CSS21_NAMES_TO_HEX
+ import webcolors
+
+ def is_css_color_code(instance: object) -> bool:
+ return webcolors.normalize_hex(instance)
+
+ @_checks_drafts(draft3="color", raises=(ValueError, TypeError))
+ def is_css21_color(instance: object) -> bool:
+ if (
+ not isinstance(instance, str)
+ or instance.lower() in CSS21_NAMES_TO_HEX
+ ):
+ return True
+ return is_css_color_code(instance)
+
+
+with suppress(ImportError):
+ import jsonpointer
+
+ @_checks_drafts(
+ draft6="json-pointer",
+ draft7="json-pointer",
+ draft201909="json-pointer",
+ draft202012="json-pointer",
+ raises=jsonpointer.JsonPointerException,
+ )
+ def is_json_pointer(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return bool(jsonpointer.JsonPointer(instance))
+
+ # TODO: I don't want to maintain this, so it
+ # needs to go either into jsonpointer (pending
+ # https://github.com/stefankoegl/python-json-pointer/issues/34) or
+ # into a new external library.
+ @_checks_drafts(
+ draft7="relative-json-pointer",
+ draft201909="relative-json-pointer",
+ draft202012="relative-json-pointer",
+ raises=jsonpointer.JsonPointerException,
+ )
+ def is_relative_json_pointer(instance: object) -> bool:
+ # Definition taken from:
+ # https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3
+ if not isinstance(instance, str):
+ return True
+ if not instance:
+ return False
+
+ non_negative_integer, rest = [], ""
+ for i, character in enumerate(instance):
+ if character.isdigit():
+ # digits with a leading "0" are not allowed
+ if i > 0 and int(instance[i - 1]) == 0:
+ return False
+
+ non_negative_integer.append(character)
+ continue
+
+ if not non_negative_integer:
+ return False
+
+ rest = instance[i:]
+ break
+ return (rest == "#") or bool(jsonpointer.JsonPointer(rest))
+
+
+with suppress(ImportError):
+ import uri_template
+
+ @_checks_drafts(
+ draft6="uri-template",
+ draft7="uri-template",
+ draft201909="uri-template",
+ draft202012="uri-template",
+ )
+ def is_uri_template(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ return uri_template.validate(instance)
+
+
+with suppress(ImportError):
+ import isoduration
+
+ @_checks_drafts(
+ draft201909="duration",
+ draft202012="duration",
+ raises=isoduration.DurationParsingException,
+ )
+ def is_duration(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ isoduration.parse_duration(instance)
+ # FIXME: See bolsote/isoduration#25 and bolsote/isoduration#21
+ return instance.endswith(tuple("DMYWHMS"))
+
+
+@_checks_drafts(
+ draft201909="uuid",
+ draft202012="uuid",
+ raises=ValueError,
+)
+def is_uuid(instance: object) -> bool:
+ if not isinstance(instance, str):
+ return True
+ UUID(instance)
+ return all(instance[position] == "-" for position in (8, 13, 18, 23))
diff --git a/runtime/Lib/site-packages/jsonschema/_legacy_validators.py b/runtime/Lib/site-packages/jsonschema/_legacy_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc5e3f44c199d1f0350b8a26e80b210e3619d32b
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/_legacy_validators.py
@@ -0,0 +1,319 @@
+from jsonschema import _utils
+from jsonschema.exceptions import ValidationError
+
+
+def id_of_ignore_ref(property="$id"):
+ def id_of(schema):
+ """
+ Ignore an ``$id`` sibling of ``$ref`` if it is present.
+
+ Otherwise, return the ID of the given schema.
+ """
+ if schema is True or schema is False or "$ref" in schema:
+ return ""
+ return schema.get(property, "")
+ return id_of
+
+
+def ignore_ref_siblings(schema):
+ """
+ Ignore siblings of ``$ref`` if it is present.
+
+ Otherwise, return all keywords.
+
+ Suitable for use with `create`'s ``applicable_validators`` argument.
+ """
+ ref = schema.get("$ref")
+ if ref is not None:
+ return [("$ref", ref)]
+ else:
+ return schema.items()
+
+
+def dependencies_draft3(validator, dependencies, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependencies.items():
+ if property not in instance:
+ continue
+
+ if validator.is_type(dependency, "object"):
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+ elif validator.is_type(dependency, "string"):
+ if dependency not in instance:
+ message = f"{dependency!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+ else:
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+
+
+def dependencies_draft4_draft6_draft7(
+ validator,
+ dependencies,
+ instance,
+ schema,
+):
+ """
+ Support for the ``dependencies`` keyword from pre-draft 2019-09.
+
+ In later drafts, the keyword was split into separate
+ ``dependentRequired`` and ``dependentSchemas`` validators.
+ """
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependencies.items():
+ if property not in instance:
+ continue
+
+ if validator.is_type(dependency, "array"):
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+ else:
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+
+
+def disallow_draft3(validator, disallow, instance, schema):
+ for disallowed in _utils.ensure_list(disallow):
+ if validator.evolve(schema={"type": [disallowed]}).is_valid(instance):
+ message = f"{disallowed!r} is disallowed for {instance!r}"
+ yield ValidationError(message)
+
+
+def extends_draft3(validator, extends, instance, schema):
+ if validator.is_type(extends, "object"):
+ yield from validator.descend(instance, extends)
+ return
+ for index, subschema in enumerate(extends):
+ yield from validator.descend(instance, subschema, schema_path=index)
+
+
+def items_draft3_draft4(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if validator.is_type(items, "object"):
+ for index, item in enumerate(instance):
+ yield from validator.descend(item, items, path=index)
+ else:
+ for (index, item), subschema in zip(enumerate(instance), items):
+ yield from validator.descend(
+ item, subschema, path=index, schema_path=index,
+ )
+
+
+def items_draft6_draft7_draft201909(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if validator.is_type(items, "array"):
+ for (index, item), subschema in zip(enumerate(instance), items):
+ yield from validator.descend(
+ item, subschema, path=index, schema_path=index,
+ )
+ else:
+ for index, item in enumerate(instance):
+ yield from validator.descend(item, items, path=index)
+
+
+def minimum_draft3_draft4(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if schema.get("exclusiveMinimum", False):
+ failed = instance <= minimum
+ cmp = "less than or equal to"
+ else:
+ failed = instance < minimum
+ cmp = "less than"
+
+ if failed:
+ message = f"{instance!r} is {cmp} the minimum of {minimum!r}"
+ yield ValidationError(message)
+
+
+def maximum_draft3_draft4(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if schema.get("exclusiveMaximum", False):
+ failed = instance >= maximum
+ cmp = "greater than or equal to"
+ else:
+ failed = instance > maximum
+ cmp = "greater than"
+
+ if failed:
+ message = f"{instance!r} is {cmp} the maximum of {maximum!r}"
+ yield ValidationError(message)
+
+
+def properties_draft3(validator, properties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, subschema in properties.items():
+ if property in instance:
+ yield from validator.descend(
+ instance[property],
+ subschema,
+ path=property,
+ schema_path=property,
+ )
+ elif subschema.get("required", False):
+ error = ValidationError(f"{property!r} is a required property")
+ error._set(
+ validator="required",
+ validator_value=subschema["required"],
+ instance=instance,
+ schema=schema,
+ )
+ error.path.appendleft(property)
+ error.schema_path.extend([property, "required"])
+ yield error
+
+
+def type_draft3(validator, types, instance, schema):
+ types = _utils.ensure_list(types)
+
+ all_errors = []
+ for index, type in enumerate(types):
+ if validator.is_type(type, "object"):
+ errors = list(validator.descend(instance, type, schema_path=index))
+ if not errors:
+ return
+ all_errors.extend(errors)
+ else:
+ if validator.is_type(instance, type):
+ return
+ else:
+ reprs = []
+ for type in types:
+ try:
+ reprs.append(repr(type["name"]))
+ except Exception:
+ reprs.append(repr(type))
+ yield ValidationError(
+ f"{instance!r} is not of type {', '.join(reprs)}",
+ context=all_errors,
+ )
+
+
+def contains_draft6_draft7(validator, contains, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ if not any(
+ validator.evolve(schema=contains).is_valid(element)
+ for element in instance
+ ):
+ yield ValidationError(
+ f"None of {instance!r} are valid under the given schema",
+ )
+
+
+def recursiveRef(validator, recursiveRef, instance, schema):
+ lookup_url, target = validator.resolver.resolution_scope, validator.schema
+
+ for each in reversed(validator.resolver._scopes_stack[1:]):
+ lookup_url, next_target = validator.resolver.resolve(each)
+ if next_target.get("$recursiveAnchor"):
+ target = next_target
+ else:
+ break
+
+ fragment = recursiveRef.lstrip("#")
+ subschema = validator.resolver.resolve_fragment(target, fragment)
+ # FIXME: This is gutted (and not calling .descend) because it can trigger
+ # recursion errors, so there's a bug here. Re-enable the tests to
+ # see it.
+ subschema
+ return []
+
+
+def find_evaluated_item_indexes_by_schema(validator, instance, schema):
+ """
+ Get all indexes of items that get evaluated under the current schema
+
+ Covers all keywords related to unevaluatedItems: items, prefixItems, if,
+ then, else, contains, unevaluatedItems, allOf, oneOf, anyOf
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_indexes = []
+
+ if "additionalItems" in schema:
+ return list(range(0, len(instance)))
+
+ if "$ref" in schema:
+ scope, resolved = validator.resolver.resolve(schema["$ref"])
+ validator.resolver.push_scope(scope)
+
+ try:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, resolved,
+ )
+ finally:
+ validator.resolver.pop_scope()
+
+ if "items" in schema:
+ if validator.is_type(schema["items"], "object"):
+ return list(range(0, len(instance)))
+ evaluated_indexes += list(range(0, len(schema["items"])))
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["then"],
+ )
+ else:
+ if "else" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ for keyword in ["contains", "unevaluatedItems"]:
+ if keyword in schema:
+ for k, v in enumerate(instance):
+ if validator.evolve(schema=schema[keyword]).is_valid(v):
+ evaluated_indexes.append(k)
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = list(validator.descend(instance, subschema))
+ if not errs:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, subschema,
+ )
+
+ return evaluated_indexes
+
+
+def unevaluatedItems_draft2019(validator, unevaluatedItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+ evaluated_item_indexes = find_evaluated_item_indexes_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_items = [
+ item for index, item in enumerate(instance)
+ if index not in evaluated_item_indexes
+ ]
+ if unevaluated_items:
+ error = "Unevaluated items are not allowed (%s %s unexpected)"
+ yield ValidationError(error % _utils.extras_msg(unevaluated_items))
diff --git a/runtime/Lib/site-packages/jsonschema/_types.py b/runtime/Lib/site-packages/jsonschema/_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b543f71bb576eb4a169e8441152ef3c4e37c0f9
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/_types.py
@@ -0,0 +1,203 @@
+from __future__ import annotations
+
+import numbers
+import typing
+
+from pyrsistent import pmap
+from pyrsistent.typing import PMap
+import attr
+
+from jsonschema.exceptions import UndefinedTypeCheck
+
+
+# unfortunately, the type of pmap is generic, and if used as the attr.ib
+# converter, the generic type is presented to mypy, which then fails to match
+# the concrete type of a type checker mapping
+# this "do nothing" wrapper presents the correct information to mypy
+def _typed_pmap_converter(
+ init_val: typing.Mapping[
+ str,
+ typing.Callable[["TypeChecker", typing.Any], bool],
+ ],
+) -> PMap[str, typing.Callable[["TypeChecker", typing.Any], bool]]:
+ return pmap(init_val)
+
+
+def is_array(checker, instance):
+ return isinstance(instance, list)
+
+
+def is_bool(checker, instance):
+ return isinstance(instance, bool)
+
+
+def is_integer(checker, instance):
+ # bool inherits from int, so ensure bools aren't reported as ints
+ if isinstance(instance, bool):
+ return False
+ return isinstance(instance, int)
+
+
+def is_null(checker, instance):
+ return instance is None
+
+
+def is_number(checker, instance):
+ # bool inherits from int, so ensure bools aren't reported as ints
+ if isinstance(instance, bool):
+ return False
+ return isinstance(instance, numbers.Number)
+
+
+def is_object(checker, instance):
+ return isinstance(instance, dict)
+
+
+def is_string(checker, instance):
+ return isinstance(instance, str)
+
+
+def is_any(checker, instance):
+ return True
+
+
+@attr.s(frozen=True, repr=False)
+class TypeChecker:
+ """
+ A :kw:`type` property checker.
+
+ A `TypeChecker` performs type checking for a `Validator`, converting
+ between the defined JSON Schema types and some associated Python types or
+ objects.
+
+ Modifying the behavior just mentioned by redefining which Python objects
+ are considered to be of which JSON Schema types can be done using
+ `TypeChecker.redefine` or `TypeChecker.redefine_many`, and types can be
+ removed via `TypeChecker.remove`. Each of these return a new `TypeChecker`.
+
+ Arguments:
+
+ type_checkers:
+
+ The initial mapping of types to their checking functions.
+ """
+
+ _type_checkers: PMap[
+ str, typing.Callable[["TypeChecker", typing.Any], bool],
+ ] = attr.ib(
+ default=pmap(),
+ converter=_typed_pmap_converter,
+ )
+
+ def __repr__(self):
+ types = ", ".join(repr(k) for k in sorted(self._type_checkers))
+ return f"<{self.__class__.__name__} types={{{types}}}>"
+
+ def is_type(self, instance, type: str) -> bool:
+ """
+ Check if the instance is of the appropriate type.
+
+ Arguments:
+
+ instance:
+
+ The instance to check
+
+ type:
+
+ The name of the type that is expected.
+
+ Raises:
+
+ `jsonschema.exceptions.UndefinedTypeCheck`:
+
+ if ``type`` is unknown to this object.
+ """
+ try:
+ fn = self._type_checkers[type]
+ except KeyError:
+ raise UndefinedTypeCheck(type) from None
+
+ return fn(self, instance)
+
+ def redefine(self, type: str, fn) -> "TypeChecker":
+ """
+ Produce a new checker with the given type redefined.
+
+ Arguments:
+
+ type:
+
+ The name of the type to check.
+
+ fn (collections.abc.Callable):
+
+ A callable taking exactly two parameters - the type
+ checker calling the function and the instance to check.
+ The function should return true if instance is of this
+ type and false otherwise.
+ """
+ return self.redefine_many({type: fn})
+
+ def redefine_many(self, definitions=()) -> "TypeChecker":
+ """
+ Produce a new checker with the given types redefined.
+
+ Arguments:
+
+ definitions (dict):
+
+ A dictionary mapping types to their checking functions.
+ """
+ type_checkers = self._type_checkers.update(definitions)
+ return attr.evolve(self, type_checkers=type_checkers)
+
+ def remove(self, *types) -> "TypeChecker":
+ """
+ Produce a new checker with the given types forgotten.
+
+ Arguments:
+
+ types:
+
+ the names of the types to remove.
+
+ Raises:
+
+ `jsonschema.exceptions.UndefinedTypeCheck`:
+
+ if any given type is unknown to this object
+ """
+
+ type_checkers = self._type_checkers
+ for each in types:
+ try:
+ type_checkers = type_checkers.remove(each)
+ except KeyError:
+ raise UndefinedTypeCheck(each)
+ return attr.evolve(self, type_checkers=type_checkers)
+
+
+draft3_type_checker = TypeChecker(
+ {
+ "any": is_any,
+ "array": is_array,
+ "boolean": is_bool,
+ "integer": is_integer,
+ "object": is_object,
+ "null": is_null,
+ "number": is_number,
+ "string": is_string,
+ },
+)
+draft4_type_checker = draft3_type_checker.remove("any")
+draft6_type_checker = draft4_type_checker.redefine(
+ "integer",
+ lambda checker, instance: (
+ is_integer(checker, instance)
+ or isinstance(instance, float) and instance.is_integer()
+ ),
+)
+draft7_type_checker = draft6_type_checker
+draft201909_type_checker = draft7_type_checker
+draft202012_type_checker = draft201909_type_checker
diff --git a/runtime/Lib/site-packages/jsonschema/_utils.py b/runtime/Lib/site-packages/jsonschema/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..418348ce1ccc03f9c7fd00edd0eb035cd67de469
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/_utils.py
@@ -0,0 +1,349 @@
+from collections.abc import Mapping, MutableMapping, Sequence
+from urllib.parse import urlsplit
+import itertools
+import json
+import re
+import sys
+
+# The files() API was added in Python 3.9.
+if sys.version_info >= (3, 9): # pragma: no cover
+ from importlib import resources
+else: # pragma: no cover
+ import importlib_resources as resources # type: ignore
+
+
+class URIDict(MutableMapping):
+ """
+ Dictionary which uses normalized URIs as keys.
+ """
+
+ def normalize(self, uri):
+ return urlsplit(uri).geturl()
+
+ def __init__(self, *args, **kwargs):
+ self.store = dict()
+ self.store.update(*args, **kwargs)
+
+ def __getitem__(self, uri):
+ return self.store[self.normalize(uri)]
+
+ def __setitem__(self, uri, value):
+ self.store[self.normalize(uri)] = value
+
+ def __delitem__(self, uri):
+ del self.store[self.normalize(uri)]
+
+ def __iter__(self):
+ return iter(self.store)
+
+ def __len__(self):
+ return len(self.store)
+
+ def __repr__(self):
+ return repr(self.store)
+
+
+class Unset:
+ """
+ An as-of-yet unset attribute or unprovided default parameter.
+ """
+
+ def __repr__(self):
+ return ""
+
+
+def load_schema(name):
+ """
+ Load a schema from ./schemas/``name``.json and return it.
+ """
+
+ path = resources.files(__package__).joinpath(f"schemas/{name}.json")
+ data = path.read_text(encoding="utf-8")
+ return json.loads(data)
+
+
+def format_as_index(container, indices):
+ """
+ Construct a single string containing indexing operations for the indices.
+
+ For example for a container ``bar``, [1, 2, "foo"] -> bar[1][2]["foo"]
+
+ Arguments:
+
+ container (str):
+
+ A word to use for the thing being indexed
+
+ indices (sequence):
+
+ The indices to format.
+ """
+
+ if not indices:
+ return container
+ return f"{container}[{']['.join(repr(index) for index in indices)}]"
+
+
+def find_additional_properties(instance, schema):
+ """
+ Return the set of additional properties for the given ``instance``.
+
+ Weeds out properties that should have been validated by ``properties`` and
+ / or ``patternProperties``.
+
+ Assumes ``instance`` is dict-like already.
+ """
+
+ properties = schema.get("properties", {})
+ patterns = "|".join(schema.get("patternProperties", {}))
+ for property in instance:
+ if property not in properties:
+ if patterns and re.search(patterns, property):
+ continue
+ yield property
+
+
+def extras_msg(extras):
+ """
+ Create an error message for extra items or properties.
+ """
+
+ if len(extras) == 1:
+ verb = "was"
+ else:
+ verb = "were"
+ return ", ".join(repr(extra) for extra in sorted(extras)), verb
+
+
+def ensure_list(thing):
+ """
+ Wrap ``thing`` in a list if it's a single str.
+
+ Otherwise, return it unchanged.
+ """
+
+ if isinstance(thing, str):
+ return [thing]
+ return thing
+
+
+def _mapping_equal(one, two):
+ """
+ Check if two mappings are equal using the semantics of `equal`.
+ """
+ if len(one) != len(two):
+ return False
+ return all(
+ key in two and equal(value, two[key])
+ for key, value in one.items()
+ )
+
+
+def _sequence_equal(one, two):
+ """
+ Check if two sequences are equal using the semantics of `equal`.
+ """
+ if len(one) != len(two):
+ return False
+ return all(equal(i, j) for i, j in zip(one, two))
+
+
+def equal(one, two):
+ """
+ Check if two things are equal evading some Python type hierarchy semantics.
+
+ Specifically in JSON Schema, evade `bool` inheriting from `int`,
+ recursing into sequences to do the same.
+ """
+ if isinstance(one, str) or isinstance(two, str):
+ return one == two
+ if isinstance(one, Sequence) and isinstance(two, Sequence):
+ return _sequence_equal(one, two)
+ if isinstance(one, Mapping) and isinstance(two, Mapping):
+ return _mapping_equal(one, two)
+ return unbool(one) == unbool(two)
+
+
+def unbool(element, true=object(), false=object()):
+ """
+ A hack to make True and 1 and False and 0 unique for ``uniq``.
+ """
+
+ if element is True:
+ return true
+ elif element is False:
+ return false
+ return element
+
+
+def uniq(container):
+ """
+ Check if all of a container's elements are unique.
+
+ Tries to rely on the container being recursively sortable, or otherwise
+ falls back on (slow) brute force.
+ """
+ try:
+ sort = sorted(unbool(i) for i in container)
+ sliced = itertools.islice(sort, 1, None)
+
+ for i, j in zip(sort, sliced):
+ if equal(i, j):
+ return False
+
+ except (NotImplementedError, TypeError):
+ seen = []
+ for e in container:
+ e = unbool(e)
+
+ for i in seen:
+ if equal(i, e):
+ return False
+
+ seen.append(e)
+ return True
+
+
+def find_evaluated_item_indexes_by_schema(validator, instance, schema):
+ """
+ Get all indexes of items that get evaluated under the current schema
+
+ Covers all keywords related to unevaluatedItems: items, prefixItems, if,
+ then, else, contains, unevaluatedItems, allOf, oneOf, anyOf
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_indexes = []
+
+ if "items" in schema:
+ return list(range(0, len(instance)))
+
+ if "$ref" in schema:
+ scope, resolved = validator.resolver.resolve(schema["$ref"])
+ validator.resolver.push_scope(scope)
+
+ try:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, resolved,
+ )
+ finally:
+ validator.resolver.pop_scope()
+
+ if "prefixItems" in schema:
+ evaluated_indexes += list(range(0, len(schema["prefixItems"])))
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["then"],
+ )
+ else:
+ if "else" in schema:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ for keyword in ["contains", "unevaluatedItems"]:
+ if keyword in schema:
+ for k, v in enumerate(instance):
+ if validator.evolve(schema=schema[keyword]).is_valid(v):
+ evaluated_indexes.append(k)
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = list(validator.descend(instance, subschema))
+ if not errs:
+ evaluated_indexes += find_evaluated_item_indexes_by_schema(
+ validator, instance, subschema,
+ )
+
+ return evaluated_indexes
+
+
+def find_evaluated_property_keys_by_schema(validator, instance, schema):
+ """
+ Get all keys of items that get evaluated under the current schema
+
+ Covers all keywords related to unevaluatedProperties: properties,
+ additionalProperties, unevaluatedProperties, patternProperties,
+ dependentSchemas, allOf, oneOf, anyOf, if, then, else
+ """
+ if validator.is_type(schema, "boolean"):
+ return []
+ evaluated_keys = []
+
+ if "$ref" in schema:
+ scope, resolved = validator.resolver.resolve(schema["$ref"])
+ validator.resolver.push_scope(scope)
+
+ try:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, resolved,
+ )
+ finally:
+ validator.resolver.pop_scope()
+
+ for keyword in [
+ "properties", "additionalProperties", "unevaluatedProperties",
+ ]:
+ if keyword in schema:
+ if validator.is_type(schema[keyword], "boolean"):
+ for property, value in instance.items():
+ if validator.evolve(schema=schema[keyword]).is_valid(
+ {property: value},
+ ):
+ evaluated_keys.append(property)
+
+ if validator.is_type(schema[keyword], "object"):
+ for property, subschema in schema[keyword].items():
+ if property in instance and validator.evolve(
+ schema=subschema,
+ ).is_valid(instance[property]):
+ evaluated_keys.append(property)
+
+ if "patternProperties" in schema:
+ for property, value in instance.items():
+ for pattern, _ in schema["patternProperties"].items():
+ if re.search(pattern, property) and validator.evolve(
+ schema=schema["patternProperties"],
+ ).is_valid({property: value}):
+ evaluated_keys.append(property)
+
+ if "dependentSchemas" in schema:
+ for property, subschema in schema["dependentSchemas"].items():
+ if property not in instance:
+ continue
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ for keyword in ["allOf", "oneOf", "anyOf"]:
+ if keyword in schema:
+ for subschema in schema[keyword]:
+ errs = list(validator.descend(instance, subschema))
+ if not errs:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, subschema,
+ )
+
+ if "if" in schema:
+ if validator.evolve(schema=schema["if"]).is_valid(instance):
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["if"],
+ )
+ if "then" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["then"],
+ )
+ else:
+ if "else" in schema:
+ evaluated_keys += find_evaluated_property_keys_by_schema(
+ validator, instance, schema["else"],
+ )
+
+ return evaluated_keys
diff --git a/runtime/Lib/site-packages/jsonschema/_validators.py b/runtime/Lib/site-packages/jsonschema/_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..8542a879c8238e62be9673bf46bb869eb1af5374
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/_validators.py
@@ -0,0 +1,476 @@
+from fractions import Fraction
+from urllib.parse import urldefrag, urljoin
+import re
+
+from jsonschema._utils import (
+ ensure_list,
+ equal,
+ extras_msg,
+ find_additional_properties,
+ find_evaluated_item_indexes_by_schema,
+ find_evaluated_property_keys_by_schema,
+ unbool,
+ uniq,
+)
+from jsonschema.exceptions import FormatError, ValidationError
+
+
+def patternProperties(validator, patternProperties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for pattern, subschema in patternProperties.items():
+ for k, v in instance.items():
+ if re.search(pattern, k):
+ yield from validator.descend(
+ v, subschema, path=k, schema_path=pattern,
+ )
+
+
+def propertyNames(validator, propertyNames, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property in instance:
+ yield from validator.descend(instance=property, schema=propertyNames)
+
+
+def additionalProperties(validator, aP, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ extras = set(find_additional_properties(instance, schema))
+
+ if validator.is_type(aP, "object"):
+ for extra in extras:
+ yield from validator.descend(instance[extra], aP, path=extra)
+ elif not aP and extras:
+ if "patternProperties" in schema:
+ if len(extras) == 1:
+ verb = "does"
+ else:
+ verb = "do"
+
+ joined = ", ".join(repr(each) for each in sorted(extras))
+ patterns = ", ".join(
+ repr(each) for each in sorted(schema["patternProperties"])
+ )
+ error = f"{joined} {verb} not match any of the regexes: {patterns}"
+ yield ValidationError(error)
+ else:
+ error = "Additional properties are not allowed (%s %s unexpected)"
+ yield ValidationError(error % extras_msg(extras))
+
+
+def items(validator, items, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ prefix = len(schema.get("prefixItems", []))
+ total = len(instance)
+ if items is False and total > prefix:
+ message = f"Expected at most {prefix} items, but found {total}"
+ yield ValidationError(message)
+ else:
+ for index in range(prefix, total):
+ yield from validator.descend(
+ instance=instance[index],
+ schema=items,
+ path=index,
+ )
+
+
+def additionalItems(validator, aI, instance, schema):
+ if (
+ not validator.is_type(instance, "array")
+ or validator.is_type(schema.get("items", {}), "object")
+ ):
+ return
+
+ len_items = len(schema.get("items", []))
+ if validator.is_type(aI, "object"):
+ for index, item in enumerate(instance[len_items:], start=len_items):
+ yield from validator.descend(item, aI, path=index)
+ elif not aI and len(instance) > len(schema.get("items", [])):
+ error = "Additional items are not allowed (%s %s unexpected)"
+ yield ValidationError(
+ error % extras_msg(instance[len(schema.get("items", [])):]),
+ )
+
+
+def const(validator, const, instance, schema):
+ if not equal(instance, const):
+ yield ValidationError(f"{const!r} was expected")
+
+
+def contains(validator, contains, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ matches = 0
+ min_contains = schema.get("minContains", 1)
+ max_contains = schema.get("maxContains", len(instance))
+
+ for each in instance:
+ if validator.evolve(schema=contains).is_valid(each):
+ matches += 1
+ if matches > max_contains:
+ yield ValidationError(
+ "Too many items match the given schema "
+ f"(expected at most {max_contains})",
+ validator="maxContains",
+ validator_value=max_contains,
+ )
+ return
+
+ if matches < min_contains:
+ if not matches:
+ yield ValidationError(
+ f"{instance!r} does not contain items "
+ "matching the given schema",
+ )
+ else:
+ yield ValidationError(
+ "Too few items match the given schema (expected at least "
+ f"{min_contains} but only {matches} matched)",
+ validator="minContains",
+ validator_value=min_contains,
+ )
+
+
+def exclusiveMinimum(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance <= minimum:
+ yield ValidationError(
+ f"{instance!r} is less than or equal to "
+ f"the minimum of {minimum!r}",
+ )
+
+
+def exclusiveMaximum(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance >= maximum:
+ yield ValidationError(
+ f"{instance!r} is greater than or equal "
+ f"to the maximum of {maximum!r}",
+ )
+
+
+def minimum(validator, minimum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance < minimum:
+ message = f"{instance!r} is less than the minimum of {minimum!r}"
+ yield ValidationError(message)
+
+
+def maximum(validator, maximum, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if instance > maximum:
+ message = f"{instance!r} is greater than the maximum of {maximum!r}"
+ yield ValidationError(message)
+
+
+def multipleOf(validator, dB, instance, schema):
+ if not validator.is_type(instance, "number"):
+ return
+
+ if isinstance(dB, float):
+ quotient = instance / dB
+ try:
+ failed = int(quotient) != quotient
+ except OverflowError:
+ # When `instance` is large and `dB` is less than one,
+ # quotient can overflow to infinity; and then casting to int
+ # raises an error.
+ #
+ # In this case we fall back to Fraction logic, which is
+ # exact and cannot overflow. The performance is also
+ # acceptable: we try the fast all-float option first, and
+ # we know that fraction(dB) can have at most a few hundred
+ # digits in each part. The worst-case slowdown is therefore
+ # for already-slow enormous integers or Decimals.
+ failed = (Fraction(instance) / Fraction(dB)).denominator != 1
+ else:
+ failed = instance % dB
+
+ if failed:
+ yield ValidationError(f"{instance!r} is not a multiple of {dB}")
+
+
+def minItems(validator, mI, instance, schema):
+ if validator.is_type(instance, "array") and len(instance) < mI:
+ yield ValidationError(f"{instance!r} is too short")
+
+
+def maxItems(validator, mI, instance, schema):
+ if validator.is_type(instance, "array") and len(instance) > mI:
+ yield ValidationError(f"{instance!r} is too long")
+
+
+def uniqueItems(validator, uI, instance, schema):
+ if (
+ uI
+ and validator.is_type(instance, "array")
+ and not uniq(instance)
+ ):
+ yield ValidationError(f"{instance!r} has non-unique elements")
+
+
+def pattern(validator, patrn, instance, schema):
+ if (
+ validator.is_type(instance, "string")
+ and not re.search(patrn, instance)
+ ):
+ yield ValidationError(f"{instance!r} does not match {patrn!r}")
+
+
+def format(validator, format, instance, schema):
+ if validator.format_checker is not None:
+ try:
+ validator.format_checker.check(instance, format)
+ except FormatError as error:
+ yield ValidationError(error.message, cause=error.cause)
+
+
+def minLength(validator, mL, instance, schema):
+ if validator.is_type(instance, "string") and len(instance) < mL:
+ yield ValidationError(f"{instance!r} is too short")
+
+
+def maxLength(validator, mL, instance, schema):
+ if validator.is_type(instance, "string") and len(instance) > mL:
+ yield ValidationError(f"{instance!r} is too long")
+
+
+def dependentRequired(validator, dependentRequired, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependentRequired.items():
+ if property not in instance:
+ continue
+
+ for each in dependency:
+ if each not in instance:
+ message = f"{each!r} is a dependency of {property!r}"
+ yield ValidationError(message)
+
+
+def dependentSchemas(validator, dependentSchemas, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, dependency in dependentSchemas.items():
+ if property not in instance:
+ continue
+ yield from validator.descend(
+ instance, dependency, schema_path=property,
+ )
+
+
+def enum(validator, enums, instance, schema):
+ if instance == 0 or instance == 1:
+ unbooled = unbool(instance)
+ if all(unbooled != unbool(each) for each in enums):
+ yield ValidationError(f"{instance!r} is not one of {enums!r}")
+ elif instance not in enums:
+ yield ValidationError(f"{instance!r} is not one of {enums!r}")
+
+
+def ref(validator, ref, instance, schema):
+ resolve = getattr(validator.resolver, "resolve", None)
+ if resolve is None:
+ with validator.resolver.resolving(ref) as resolved:
+ yield from validator.descend(instance, resolved)
+ else:
+ scope, resolved = validator.resolver.resolve(ref)
+ validator.resolver.push_scope(scope)
+
+ try:
+ yield from validator.descend(instance, resolved)
+ finally:
+ validator.resolver.pop_scope()
+
+
+def dynamicRef(validator, dynamicRef, instance, schema):
+ _, fragment = urldefrag(dynamicRef)
+
+ for url in validator.resolver._scopes_stack:
+ lookup_url = urljoin(url, dynamicRef)
+ with validator.resolver.resolving(lookup_url) as subschema:
+ if ("$dynamicAnchor" in subschema
+ and fragment == subschema["$dynamicAnchor"]):
+ yield from validator.descend(instance, subschema)
+ break
+ else:
+ with validator.resolver.resolving(dynamicRef) as subschema:
+ yield from validator.descend(instance, subschema)
+
+
+def type(validator, types, instance, schema):
+ types = ensure_list(types)
+
+ if not any(validator.is_type(instance, type) for type in types):
+ reprs = ", ".join(repr(type) for type in types)
+ yield ValidationError(f"{instance!r} is not of type {reprs}")
+
+
+def properties(validator, properties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+
+ for property, subschema in properties.items():
+ if property in instance:
+ yield from validator.descend(
+ instance[property],
+ subschema,
+ path=property,
+ schema_path=property,
+ )
+
+
+def required(validator, required, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ for property in required:
+ if property not in instance:
+ yield ValidationError(f"{property!r} is a required property")
+
+
+def minProperties(validator, mP, instance, schema):
+ if validator.is_type(instance, "object") and len(instance) < mP:
+ yield ValidationError(f"{instance!r} does not have enough properties")
+
+
+def maxProperties(validator, mP, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ if validator.is_type(instance, "object") and len(instance) > mP:
+ yield ValidationError(f"{instance!r} has too many properties")
+
+
+def allOf(validator, allOf, instance, schema):
+ for index, subschema in enumerate(allOf):
+ yield from validator.descend(instance, subschema, schema_path=index)
+
+
+def anyOf(validator, anyOf, instance, schema):
+ all_errors = []
+ for index, subschema in enumerate(anyOf):
+ errs = list(validator.descend(instance, subschema, schema_path=index))
+ if not errs:
+ break
+ all_errors.extend(errs)
+ else:
+ yield ValidationError(
+ f"{instance!r} is not valid under any of the given schemas",
+ context=all_errors,
+ )
+
+
+def oneOf(validator, oneOf, instance, schema):
+ subschemas = enumerate(oneOf)
+ all_errors = []
+ for index, subschema in subschemas:
+ errs = list(validator.descend(instance, subschema, schema_path=index))
+ if not errs:
+ first_valid = subschema
+ break
+ all_errors.extend(errs)
+ else:
+ yield ValidationError(
+ f"{instance!r} is not valid under any of the given schemas",
+ context=all_errors,
+ )
+
+ more_valid = [
+ each for _, each in subschemas
+ if validator.evolve(schema=each).is_valid(instance)
+ ]
+ if more_valid:
+ more_valid.append(first_valid)
+ reprs = ", ".join(repr(schema) for schema in more_valid)
+ yield ValidationError(f"{instance!r} is valid under each of {reprs}")
+
+
+def not_(validator, not_schema, instance, schema):
+ if validator.evolve(schema=not_schema).is_valid(instance):
+ message = f"{instance!r} should not be valid under {not_schema!r}"
+ yield ValidationError(message)
+
+
+def if_(validator, if_schema, instance, schema):
+ if validator.evolve(schema=if_schema).is_valid(instance):
+ if "then" in schema:
+ then = schema["then"]
+ yield from validator.descend(instance, then, schema_path="then")
+ elif "else" in schema:
+ else_ = schema["else"]
+ yield from validator.descend(instance, else_, schema_path="else")
+
+
+def unevaluatedItems(validator, unevaluatedItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+ evaluated_item_indexes = find_evaluated_item_indexes_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_items = [
+ item for index, item in enumerate(instance)
+ if index not in evaluated_item_indexes
+ ]
+ if unevaluated_items:
+ error = "Unevaluated items are not allowed (%s %s unexpected)"
+ yield ValidationError(error % extras_msg(unevaluated_items))
+
+
+def unevaluatedProperties(validator, unevaluatedProperties, instance, schema):
+ if not validator.is_type(instance, "object"):
+ return
+ evaluated_keys = find_evaluated_property_keys_by_schema(
+ validator, instance, schema,
+ )
+ unevaluated_keys = []
+ for property in instance:
+ if property not in evaluated_keys:
+ for _ in validator.descend(
+ instance[property],
+ unevaluatedProperties,
+ path=property,
+ schema_path=property,
+ ):
+ # FIXME: Include context for each unevaluated property
+ # indicating why it's invalid under the subschema.
+ unevaluated_keys.append(property)
+
+ if unevaluated_keys:
+ if unevaluatedProperties is False:
+ error = "Unevaluated properties are not allowed (%s %s unexpected)"
+ yield ValidationError(error % extras_msg(unevaluated_keys))
+ else:
+ error = (
+ "Unevaluated properties are not valid under "
+ "the given schema (%s %s unevaluated and invalid)"
+ )
+ yield ValidationError(error % extras_msg(unevaluated_keys))
+
+
+def prefixItems(validator, prefixItems, instance, schema):
+ if not validator.is_type(instance, "array"):
+ return
+
+ for (index, item), subschema in zip(enumerate(instance), prefixItems):
+ yield from validator.descend(
+ instance=item,
+ schema=subschema,
+ schema_path=index,
+ path=index,
+ )
diff --git a/runtime/Lib/site-packages/jsonschema/benchmarks/__init__.py b/runtime/Lib/site-packages/jsonschema/benchmarks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3dcc689930da95198c251ce806637d6413c8b1e
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/benchmarks/__init__.py
@@ -0,0 +1,5 @@
+"""
+Benchmarks for validation.
+
+This package is *not* public API.
+"""
diff --git a/runtime/Lib/site-packages/jsonschema/benchmarks/issue232.py b/runtime/Lib/site-packages/jsonschema/benchmarks/issue232.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf357e911631578f89b2251136d55abbbf5aa9dc
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/benchmarks/issue232.py
@@ -0,0 +1,25 @@
+"""
+A performance benchmark using the example from issue #232.
+
+See https://github.com/python-jsonschema/jsonschema/pull/232.
+"""
+from pathlib import Path
+
+from pyperf import Runner
+from pyrsistent import m
+
+from jsonschema.tests._suite import Version
+import jsonschema
+
+issue232 = Version(
+ path=Path(__file__).parent / "issue232",
+ remotes=m(),
+ name="issue232",
+)
+
+
+if __name__ == "__main__":
+ issue232.benchmark(
+ runner=Runner(),
+ Validator=jsonschema.Draft4Validator,
+ )
diff --git a/runtime/Lib/site-packages/jsonschema/benchmarks/issue232/issue.json b/runtime/Lib/site-packages/jsonschema/benchmarks/issue232/issue.json
new file mode 100644
index 0000000000000000000000000000000000000000..804c340845fa0694e8db1083cfe7c290c04f36b1
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/benchmarks/issue232/issue.json
@@ -0,0 +1,2653 @@
+[
+ {
+ "description": "Petstore",
+ "schema": {
+ "title": "A JSON Schema for Swagger 2.0 API.",
+ "id": "http://swagger.io/v2/schema.json#",
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "type": "object",
+ "required": [
+ "swagger",
+ "info",
+ "paths"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "swagger": {
+ "type": "string",
+ "enum": [
+ "2.0"
+ ],
+ "description": "The Swagger version of this document."
+ },
+ "info": {
+ "$ref": "#/definitions/info"
+ },
+ "host": {
+ "type": "string",
+ "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$",
+ "description": "The host (name or ip) of the API. Example: 'swagger.io'"
+ },
+ "basePath": {
+ "type": "string",
+ "pattern": "^/",
+ "description": "The base path to the API. Example: '/api'."
+ },
+ "schemes": {
+ "$ref": "#/definitions/schemesList"
+ },
+ "consumes": {
+ "description": "A list of MIME types accepted by the API.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "produces": {
+ "description": "A list of MIME types the API can produce.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "paths": {
+ "$ref": "#/definitions/paths"
+ },
+ "definitions": {
+ "$ref": "#/definitions/definitions"
+ },
+ "parameters": {
+ "$ref": "#/definitions/parameterDefinitions"
+ },
+ "responses": {
+ "$ref": "#/definitions/responseDefinitions"
+ },
+ "security": {
+ "$ref": "#/definitions/security"
+ },
+ "securityDefinitions": {
+ "$ref": "#/definitions/securityDefinitions"
+ },
+ "tags": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/tag"
+ },
+ "uniqueItems": true
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ }
+ },
+ "definitions": {
+ "info": {
+ "type": "object",
+ "description": "General information about the API.",
+ "required": [
+ "version",
+ "title"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "title": {
+ "type": "string",
+ "description": "A unique and precise title of the API."
+ },
+ "version": {
+ "type": "string",
+ "description": "A semantic version number of the API."
+ },
+ "description": {
+ "type": "string",
+ "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed."
+ },
+ "termsOfService": {
+ "type": "string",
+ "description": "The terms of service for the API."
+ },
+ "contact": {
+ "$ref": "#/definitions/contact"
+ },
+ "license": {
+ "$ref": "#/definitions/license"
+ }
+ }
+ },
+ "contact": {
+ "type": "object",
+ "description": "Contact information for the owners of the API.",
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The identifying name of the contact person/organization."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL pointing to the contact information.",
+ "format": "uri"
+ },
+ "email": {
+ "type": "string",
+ "description": "The email address of the contact person/organization.",
+ "format": "email"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "license": {
+ "type": "object",
+ "required": [
+ "name"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "The name of the license type. It's encouraged to use an OSI compatible license."
+ },
+ "url": {
+ "type": "string",
+ "description": "The URL pointing to the license.",
+ "format": "uri"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "paths": {
+ "type": "object",
+ "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ },
+ "^/": {
+ "$ref": "#/definitions/pathItem"
+ }
+ },
+ "additionalProperties": false
+ },
+ "definitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/schema"
+ },
+ "description": "One or more JSON objects describing the schemas being consumed and produced by the API."
+ },
+ "parameterDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/parameter"
+ },
+ "description": "One or more JSON representations for parameters"
+ },
+ "responseDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/response"
+ },
+ "description": "One or more JSON representations for parameters"
+ },
+ "externalDocs": {
+ "type": "object",
+ "additionalProperties": false,
+ "description": "information about external documentation",
+ "required": [
+ "url"
+ ],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "url": {
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "examples": {
+ "type": "object",
+ "additionalProperties": true
+ },
+ "mimeType": {
+ "type": "string",
+ "description": "The MIME type of the HTTP message."
+ },
+ "operation": {
+ "type": "object",
+ "required": [
+ "responses"
+ ],
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "tags": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "uniqueItems": true
+ },
+ "summary": {
+ "type": "string",
+ "description": "A brief summary of the operation."
+ },
+ "description": {
+ "type": "string",
+ "description": "A longer description of the operation, GitHub Flavored Markdown is allowed."
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "operationId": {
+ "type": "string",
+ "description": "A unique identifier of the operation."
+ },
+ "produces": {
+ "description": "A list of MIME types the API can produce.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "consumes": {
+ "description": "A list of MIME types the API can consume.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/mediaTypeList"
+ }
+ ]
+ },
+ "parameters": {
+ "$ref": "#/definitions/parametersList"
+ },
+ "responses": {
+ "$ref": "#/definitions/responses"
+ },
+ "schemes": {
+ "$ref": "#/definitions/schemesList"
+ },
+ "deprecated": {
+ "type": "boolean",
+ "default": false
+ },
+ "security": {
+ "$ref": "#/definitions/security"
+ }
+ }
+ },
+ "pathItem": {
+ "type": "object",
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "$ref": {
+ "type": "string"
+ },
+ "get": {
+ "$ref": "#/definitions/operation"
+ },
+ "put": {
+ "$ref": "#/definitions/operation"
+ },
+ "post": {
+ "$ref": "#/definitions/operation"
+ },
+ "delete": {
+ "$ref": "#/definitions/operation"
+ },
+ "options": {
+ "$ref": "#/definitions/operation"
+ },
+ "head": {
+ "$ref": "#/definitions/operation"
+ },
+ "patch": {
+ "$ref": "#/definitions/operation"
+ },
+ "parameters": {
+ "$ref": "#/definitions/parametersList"
+ }
+ }
+ },
+ "responses": {
+ "type": "object",
+ "description": "Response objects names can either be any valid HTTP status code or 'default'.",
+ "minProperties": 1,
+ "additionalProperties": false,
+ "patternProperties": {
+ "^([0-9]{3})$|^(default)$": {
+ "$ref": "#/definitions/responseValue"
+ },
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "not": {
+ "type": "object",
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ }
+ },
+ "responseValue": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/response"
+ },
+ {
+ "$ref": "#/definitions/jsonReference"
+ }
+ ]
+ },
+ "response": {
+ "type": "object",
+ "required": [
+ "description"
+ ],
+ "properties": {
+ "description": {
+ "type": "string"
+ },
+ "schema": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "$ref": "#/definitions/fileSchema"
+ }
+ ]
+ },
+ "headers": {
+ "$ref": "#/definitions/headers"
+ },
+ "examples": {
+ "$ref": "#/definitions/examples"
+ }
+ },
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "headers": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/header"
+ }
+ },
+ "header": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "vendorExtension": {
+ "description": "Any property starting with x- is valid.",
+ "additionalProperties": true,
+ "additionalItems": true
+ },
+ "bodyParameter": {
+ "type": "object",
+ "required": [
+ "name",
+ "in",
+ "schema"
+ ],
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "body"
+ ]
+ },
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "schema": {
+ "$ref": "#/definitions/schema"
+ }
+ },
+ "additionalProperties": false
+ },
+ "headerParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "header"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "queryParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "query"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "allowEmptyValue": {
+ "type": "boolean",
+ "default": false,
+ "description": "allows sending a parameter by name only or with an empty value."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormatWithMulti"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "formDataParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "description": "Determines whether or not this parameter is required or optional.",
+ "default": false
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "formData"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "allowEmptyValue": {
+ "type": "boolean",
+ "default": false,
+ "description": "allows sending a parameter by name only or with an empty value."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array",
+ "file"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormatWithMulti"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "pathParameterSubSchema": {
+ "additionalProperties": false,
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "required": [
+ "required"
+ ],
+ "properties": {
+ "required": {
+ "type": "boolean",
+ "enum": [
+ true
+ ],
+ "description": "Determines whether or not this parameter is required or optional."
+ },
+ "in": {
+ "type": "string",
+ "description": "Determines the location of the parameter.",
+ "enum": [
+ "path"
+ ]
+ },
+ "description": {
+ "type": "string",
+ "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed."
+ },
+ "name": {
+ "type": "string",
+ "description": "The name of the parameter."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "integer",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ }
+ },
+ "nonBodyParameter": {
+ "type": "object",
+ "required": [
+ "name",
+ "in",
+ "type"
+ ],
+ "oneOf": [
+ {
+ "$ref": "#/definitions/headerParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/formDataParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/queryParameterSubSchema"
+ },
+ {
+ "$ref": "#/definitions/pathParameterSubSchema"
+ }
+ ]
+ },
+ "parameter": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/bodyParameter"
+ },
+ {
+ "$ref": "#/definitions/nonBodyParameter"
+ }
+ ]
+ },
+ "schema": {
+ "type": "object",
+ "description": "A deterministic version of a JSON Schema object.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "properties": {
+ "$ref": {
+ "type": "string"
+ },
+ "format": {
+ "type": "string"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "multipleOf": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
+ },
+ "maximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "pattern": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern"
+ },
+ "maxItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "uniqueItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
+ },
+ "maxProperties": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minProperties": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "required": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray"
+ },
+ "enum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/enum"
+ },
+ "additionalProperties": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "type": "boolean"
+ }
+ ],
+ "default": {}
+ },
+ "type": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/type"
+ },
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/schema"
+ },
+ {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/definitions/schema"
+ }
+ }
+ ],
+ "default": {}
+ },
+ "allOf": {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#/definitions/schema"
+ }
+ },
+ "properties": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/schema"
+ },
+ "default": {}
+ },
+ "discriminator": {
+ "type": "string"
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "xml": {
+ "$ref": "#/definitions/xml"
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "example": {}
+ },
+ "additionalProperties": false
+ },
+ "fileSchema": {
+ "type": "object",
+ "description": "A deterministic version of a JSON Schema object.",
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "format": {
+ "type": "string"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "required": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "file"
+ ]
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ },
+ "example": {}
+ },
+ "additionalProperties": false
+ },
+ "primitivesItems": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "string",
+ "number",
+ "integer",
+ "boolean",
+ "array"
+ ]
+ },
+ "format": {
+ "type": "string"
+ },
+ "items": {
+ "$ref": "#/definitions/primitivesItems"
+ },
+ "collectionFormat": {
+ "$ref": "#/definitions/collectionFormat"
+ },
+ "default": {
+ "$ref": "#/definitions/default"
+ },
+ "maximum": {
+ "$ref": "#/definitions/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "#/definitions/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "#/definitions/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "#/definitions/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "#/definitions/maxLength"
+ },
+ "minLength": {
+ "$ref": "#/definitions/minLength"
+ },
+ "pattern": {
+ "$ref": "#/definitions/pattern"
+ },
+ "maxItems": {
+ "$ref": "#/definitions/maxItems"
+ },
+ "minItems": {
+ "$ref": "#/definitions/minItems"
+ },
+ "uniqueItems": {
+ "$ref": "#/definitions/uniqueItems"
+ },
+ "enum": {
+ "$ref": "#/definitions/enum"
+ },
+ "multipleOf": {
+ "$ref": "#/definitions/multipleOf"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "security": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/securityRequirement"
+ },
+ "uniqueItems": true
+ },
+ "securityRequirement": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "uniqueItems": true
+ }
+ },
+ "xml": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "namespace": {
+ "type": "string"
+ },
+ "prefix": {
+ "type": "string"
+ },
+ "attribute": {
+ "type": "boolean",
+ "default": false
+ },
+ "wrapped": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "tag": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name"
+ ],
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "externalDocs": {
+ "$ref": "#/definitions/externalDocs"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "securityDefinitions": {
+ "type": "object",
+ "additionalProperties": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/basicAuthenticationSecurity"
+ },
+ {
+ "$ref": "#/definitions/apiKeySecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2ImplicitSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2PasswordSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2ApplicationSecurity"
+ },
+ {
+ "$ref": "#/definitions/oauth2AccessCodeSecurity"
+ }
+ ]
+ }
+ },
+ "basicAuthenticationSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "basic"
+ ]
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "apiKeySecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "name",
+ "in"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "apiKey"
+ ]
+ },
+ "name": {
+ "type": "string"
+ },
+ "in": {
+ "type": "string",
+ "enum": [
+ "header",
+ "query"
+ ]
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2ImplicitSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "authorizationUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "implicit"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "authorizationUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2PasswordSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "password"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2ApplicationSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "application"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2AccessCodeSecurity": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "type",
+ "flow",
+ "authorizationUrl",
+ "tokenUrl"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "oauth2"
+ ]
+ },
+ "flow": {
+ "type": "string",
+ "enum": [
+ "accessCode"
+ ]
+ },
+ "scopes": {
+ "$ref": "#/definitions/oauth2Scopes"
+ },
+ "authorizationUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "tokenUrl": {
+ "type": "string",
+ "format": "uri"
+ },
+ "description": {
+ "type": "string"
+ }
+ },
+ "patternProperties": {
+ "^x-": {
+ "$ref": "#/definitions/vendorExtension"
+ }
+ }
+ },
+ "oauth2Scopes": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "string"
+ }
+ },
+ "mediaTypeList": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/mimeType"
+ },
+ "uniqueItems": true
+ },
+ "parametersList": {
+ "type": "array",
+ "description": "The parameters needed to send a valid API call.",
+ "additionalItems": false,
+ "items": {
+ "oneOf": [
+ {
+ "$ref": "#/definitions/parameter"
+ },
+ {
+ "$ref": "#/definitions/jsonReference"
+ }
+ ]
+ },
+ "uniqueItems": true
+ },
+ "schemesList": {
+ "type": "array",
+ "description": "The transfer protocol of the API.",
+ "items": {
+ "type": "string",
+ "enum": [
+ "http",
+ "https",
+ "ws",
+ "wss"
+ ]
+ },
+ "uniqueItems": true
+ },
+ "collectionFormat": {
+ "type": "string",
+ "enum": [
+ "csv",
+ "ssv",
+ "tsv",
+ "pipes"
+ ],
+ "default": "csv"
+ },
+ "collectionFormatWithMulti": {
+ "type": "string",
+ "enum": [
+ "csv",
+ "ssv",
+ "tsv",
+ "pipes",
+ "multi"
+ ],
+ "default": "csv"
+ },
+ "title": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/title"
+ },
+ "description": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/description"
+ },
+ "default": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/default"
+ },
+ "multipleOf": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
+ },
+ "maximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
+ },
+ "exclusiveMaximum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
+ },
+ "minimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum"
+ },
+ "exclusiveMinimum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
+ },
+ "maxLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minLength": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "pattern": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern"
+ },
+ "maxItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
+ },
+ "minItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
+ },
+ "uniqueItems": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
+ },
+ "enum": {
+ "$ref": "http://json-schema.org/draft-04/schema#/properties/enum"
+ },
+ "jsonReference": {
+ "type": "object",
+ "required": [
+ "$ref"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "$ref": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ },
+ "tests": [
+ {
+ "description": "Example petsore",
+ "data": {
+ "swagger": "2.0",
+ "info": {
+ "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
+ "version": "1.0.0",
+ "title": "Swagger Petstore",
+ "termsOfService": "http://swagger.io/terms/",
+ "contact": {
+ "email": "apiteam@swagger.io"
+ },
+ "license": {
+ "name": "Apache 2.0",
+ "url": "http://www.apache.org/licenses/LICENSE-2.0.html"
+ }
+ },
+ "host": "petstore.swagger.io",
+ "basePath": "/v2",
+ "tags": [
+ {
+ "name": "pet",
+ "description": "Everything about your Pets",
+ "externalDocs": {
+ "description": "Find out more",
+ "url": "http://swagger.io"
+ }
+ },
+ {
+ "name": "store",
+ "description": "Access to Petstore orders"
+ },
+ {
+ "name": "user",
+ "description": "Operations about user",
+ "externalDocs": {
+ "description": "Find out more about our store",
+ "url": "http://swagger.io"
+ }
+ }
+ ],
+ "schemes": [
+ "http"
+ ],
+ "paths": {
+ "/pet": {
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Add a new pet to the store",
+ "description": "",
+ "operationId": "addPet",
+ "consumes": [
+ "application/json",
+ "application/xml"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Pet object that needs to be added to the store",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ ],
+ "responses": {
+ "405": {
+ "description": "Invalid input"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ },
+ "put": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Update an existing pet",
+ "description": "",
+ "operationId": "updatePet",
+ "consumes": [
+ "application/json",
+ "application/xml"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Pet object that needs to be added to the store",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ },
+ "405": {
+ "description": "Validation exception"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/findByStatus": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Finds Pets by status",
+ "description": "Multiple status values can be provided with comma separated strings",
+ "operationId": "findPetsByStatus",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "status",
+ "in": "query",
+ "description": "Status values that need to be considered for filter",
+ "required": true,
+ "type": "array",
+ "items": {
+ "type": "string",
+ "enum": [
+ "available",
+ "pending",
+ "sold"
+ ],
+ "default": "available"
+ },
+ "collectionFormat": "multi"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid status value"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/findByTags": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Finds Pets by tags",
+ "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",
+ "operationId": "findPetsByTags",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "tags",
+ "in": "query",
+ "description": "Tags to filter by",
+ "required": true,
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "collectionFormat": "multi"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Pet"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid tag value"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ],
+ "deprecated": true
+ }
+ },
+ "/pet/{petId}": {
+ "get": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Find pet by ID",
+ "description": "Returns a single pet",
+ "operationId": "getPetById",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet to return",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Pet"
+ }
+ },
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Updates a pet in the store with form data",
+ "description": "",
+ "operationId": "updatePetWithForm",
+ "consumes": [
+ "application/x-www-form-urlencoded"
+ ],
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet that needs to be updated",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "name": "name",
+ "in": "formData",
+ "description": "Updated name of the pet",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "status",
+ "in": "formData",
+ "description": "Updated status of the pet",
+ "required": false,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "405": {
+ "description": "Invalid input"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ },
+ "delete": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "Deletes a pet",
+ "description": "",
+ "operationId": "deletePet",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "api_key",
+ "in": "header",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "Pet id to delete",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Pet not found"
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/pet/{petId}/uploadImage": {
+ "post": {
+ "tags": [
+ "pet"
+ ],
+ "summary": "uploads an image",
+ "description": "",
+ "operationId": "uploadFile",
+ "consumes": [
+ "multipart/form-data"
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "petId",
+ "in": "path",
+ "description": "ID of pet to update",
+ "required": true,
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "name": "additionalMetadata",
+ "in": "formData",
+ "description": "Additional data to pass to server",
+ "required": false,
+ "type": "string"
+ },
+ {
+ "name": "file",
+ "in": "formData",
+ "description": "file to upload",
+ "required": false,
+ "type": "file"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/ApiResponse"
+ }
+ }
+ },
+ "security": [
+ {
+ "petstore_auth": [
+ "write:pets",
+ "read:pets"
+ ]
+ }
+ ]
+ }
+ },
+ "/store/inventory": {
+ "get": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Returns pet inventories by status",
+ "description": "Returns a map of status codes to quantities",
+ "operationId": "getInventory",
+ "produces": [
+ "application/json"
+ ],
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "integer",
+ "format": "int32"
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/store/order": {
+ "post": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Place an order for a pet",
+ "description": "",
+ "operationId": "placeOrder",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "order placed for purchasing the pet",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ },
+ "400": {
+ "description": "Invalid Order"
+ }
+ }
+ }
+ },
+ "/store/order/{orderId}": {
+ "get": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Find purchase order by ID",
+ "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions",
+ "operationId": "getOrderById",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "orderId",
+ "in": "path",
+ "description": "ID of pet that needs to be fetched",
+ "required": true,
+ "type": "integer",
+ "maximum": 10.0,
+ "minimum": 1.0,
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/Order"
+ }
+ },
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Order not found"
+ }
+ }
+ },
+ "delete": {
+ "tags": [
+ "store"
+ ],
+ "summary": "Delete purchase order by ID",
+ "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors",
+ "operationId": "deleteOrder",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "orderId",
+ "in": "path",
+ "description": "ID of the order that needs to be deleted",
+ "required": true,
+ "type": "integer",
+ "minimum": 1.0,
+ "format": "int64"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid ID supplied"
+ },
+ "404": {
+ "description": "Order not found"
+ }
+ }
+ }
+ },
+ "/user": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Create user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "createUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Created user object",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/createWithArray": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Creates list of users with given input array",
+ "description": "",
+ "operationId": "createUsersWithArrayInput",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "List of user object",
+ "required": true,
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/createWithList": {
+ "post": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Creates list of users with given input array",
+ "description": "",
+ "operationId": "createUsersWithListInput",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "in": "body",
+ "name": "body",
+ "description": "List of user object",
+ "required": true,
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ }
+ ],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/login": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Logs user into the system",
+ "description": "",
+ "operationId": "loginUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "query",
+ "description": "The user name for login",
+ "required": true,
+ "type": "string"
+ },
+ {
+ "name": "password",
+ "in": "query",
+ "description": "The password for login in clear text",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "string"
+ },
+ "headers": {
+ "X-Rate-Limit": {
+ "type": "integer",
+ "format": "int32",
+ "description": "calls per hour allowed by the user"
+ },
+ "X-Expires-After": {
+ "type": "string",
+ "format": "date-time",
+ "description": "date in UTC when token expires"
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid username/password supplied"
+ }
+ }
+ }
+ },
+ "/user/logout": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Logs out current logged in user session",
+ "description": "",
+ "operationId": "logoutUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [],
+ "responses": {
+ "default": {
+ "description": "successful operation"
+ }
+ }
+ }
+ },
+ "/user/{username}": {
+ "get": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Get user by user name",
+ "description": "",
+ "operationId": "getUserByName",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "The name that needs to be fetched. Use user1 for testing. ",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ },
+ "400": {
+ "description": "Invalid username supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ },
+ "put": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Updated user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "updateUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "name that need to be updated",
+ "required": true,
+ "type": "string"
+ },
+ {
+ "in": "body",
+ "name": "body",
+ "description": "Updated user object",
+ "required": true,
+ "schema": {
+ "$ref": "#/definitions/User"
+ }
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid user supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ },
+ "delete": {
+ "tags": [
+ "user"
+ ],
+ "summary": "Delete user",
+ "description": "This can only be done by the logged in user.",
+ "operationId": "deleteUser",
+ "produces": [
+ "application/xml",
+ "application/json"
+ ],
+ "parameters": [
+ {
+ "name": "username",
+ "in": "path",
+ "description": "The name that needs to be deleted",
+ "required": true,
+ "type": "string"
+ }
+ ],
+ "responses": {
+ "400": {
+ "description": "Invalid username supplied"
+ },
+ "404": {
+ "description": "User not found"
+ }
+ }
+ }
+ }
+ },
+ "securityDefinitions": {
+ "petstore_auth": {
+ "type": "oauth2",
+ "authorizationUrl": "http://petstore.swagger.io/oauth/dialog",
+ "flow": "implicit",
+ "scopes": {
+ "write:pets": "modify pets in your account",
+ "read:pets": "read your pets"
+ }
+ },
+ "api_key": {
+ "type": "apiKey",
+ "name": "api_key",
+ "in": "header"
+ }
+ },
+ "definitions": {
+ "Order": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "petId": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "quantity": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "shipDate": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "status": {
+ "type": "string",
+ "description": "Order Status",
+ "enum": [
+ "placed",
+ "approved",
+ "delivered"
+ ]
+ },
+ "complete": {
+ "type": "boolean",
+ "default": false
+ }
+ },
+ "xml": {
+ "name": "Order"
+ }
+ },
+ "Category": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "xml": {
+ "name": "Category"
+ }
+ },
+ "User": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "username": {
+ "type": "string"
+ },
+ "firstName": {
+ "type": "string"
+ },
+ "lastName": {
+ "type": "string"
+ },
+ "email": {
+ "type": "string"
+ },
+ "password": {
+ "type": "string"
+ },
+ "phone": {
+ "type": "string"
+ },
+ "userStatus": {
+ "type": "integer",
+ "format": "int32",
+ "description": "User Status"
+ }
+ },
+ "xml": {
+ "name": "User"
+ }
+ },
+ "Tag": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "xml": {
+ "name": "Tag"
+ }
+ },
+ "Pet": {
+ "type": "object",
+ "required": [
+ "name",
+ "photoUrls"
+ ],
+ "properties": {
+ "id": {
+ "type": "integer",
+ "format": "int64"
+ },
+ "category": {
+ "$ref": "#/definitions/Category"
+ },
+ "name": {
+ "type": "string",
+ "example": "doggie"
+ },
+ "photoUrls": {
+ "type": "array",
+ "xml": {
+ "name": "photoUrl",
+ "wrapped": true
+ },
+ "items": {
+ "type": "string"
+ }
+ },
+ "tags": {
+ "type": "array",
+ "xml": {
+ "name": "tag",
+ "wrapped": true
+ },
+ "items": {
+ "$ref": "#/definitions/Tag"
+ }
+ },
+ "status": {
+ "type": "string",
+ "description": "pet status in the store",
+ "enum": [
+ "available",
+ "pending",
+ "sold"
+ ]
+ }
+ },
+ "xml": {
+ "name": "Pet"
+ }
+ },
+ "ApiResponse": {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "format": "int32"
+ },
+ "type": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "externalDocs": {
+ "description": "Find out more about Swagger",
+ "url": "http://swagger.io"
+ }
+ },
+ "valid": true
+ }
+ ]
+ }
+]
diff --git a/runtime/Lib/site-packages/jsonschema/benchmarks/json_schema_test_suite.py b/runtime/Lib/site-packages/jsonschema/benchmarks/json_schema_test_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..905fb6a3b88faf56e3288f7eb5053172f97abe8b
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/benchmarks/json_schema_test_suite.py
@@ -0,0 +1,12 @@
+"""
+A performance benchmark using the official test suite.
+
+This benchmarks jsonschema using every valid example in the
+JSON-Schema-Test-Suite. It will take some time to complete.
+"""
+from pyperf import Runner
+
+from jsonschema.tests._suite import Suite
+
+if __name__ == "__main__":
+ Suite().benchmark(runner=Runner())
diff --git a/runtime/Lib/site-packages/jsonschema/cli.py b/runtime/Lib/site-packages/jsonschema/cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..f93b5c5a085b0a21c288e7ba8e7ceea48169e7f1
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/cli.py
@@ -0,0 +1,299 @@
+"""
+The ``jsonschema`` command line.
+"""
+
+from json import JSONDecodeError
+from textwrap import dedent
+import argparse
+import json
+import sys
+import traceback
+import warnings
+
+try:
+ from importlib import metadata
+except ImportError:
+ import importlib_metadata as metadata # type: ignore
+
+try:
+ from pkgutil import resolve_name
+except ImportError:
+ from pkgutil_resolve_name import resolve_name # type: ignore
+
+import attr
+
+from jsonschema.exceptions import SchemaError
+from jsonschema.validators import RefResolver, validator_for
+
+warnings.warn(
+ (
+ "The jsonschema CLI is deprecated and will be removed in a future "
+ "version. Please use check-jsonschema instead, which can be installed "
+ "from https://pypi.org/project/check-jsonschema/"
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+)
+
+
+class _CannotLoadFile(Exception):
+ pass
+
+
+@attr.s
+class _Outputter:
+
+ _formatter = attr.ib()
+ _stdout = attr.ib()
+ _stderr = attr.ib()
+
+ @classmethod
+ def from_arguments(cls, arguments, stdout, stderr):
+ if arguments["output"] == "plain":
+ formatter = _PlainFormatter(arguments["error_format"])
+ elif arguments["output"] == "pretty":
+ formatter = _PrettyFormatter()
+ return cls(formatter=formatter, stdout=stdout, stderr=stderr)
+
+ def load(self, path):
+ try:
+ file = open(path)
+ except FileNotFoundError:
+ self.filenotfound_error(path=path, exc_info=sys.exc_info())
+ raise _CannotLoadFile()
+
+ with file:
+ try:
+ return json.load(file)
+ except JSONDecodeError:
+ self.parsing_error(path=path, exc_info=sys.exc_info())
+ raise _CannotLoadFile()
+
+ def filenotfound_error(self, **kwargs):
+ self._stderr.write(self._formatter.filenotfound_error(**kwargs))
+
+ def parsing_error(self, **kwargs):
+ self._stderr.write(self._formatter.parsing_error(**kwargs))
+
+ def validation_error(self, **kwargs):
+ self._stderr.write(self._formatter.validation_error(**kwargs))
+
+ def validation_success(self, **kwargs):
+ self._stdout.write(self._formatter.validation_success(**kwargs))
+
+
+@attr.s
+class _PrettyFormatter:
+
+ _ERROR_MSG = dedent(
+ """\
+ ===[{type}]===({path})===
+
+ {body}
+ -----------------------------
+ """,
+ )
+ _SUCCESS_MSG = "===[SUCCESS]===({path})===\n"
+
+ def filenotfound_error(self, path, exc_info):
+ return self._ERROR_MSG.format(
+ path=path,
+ type="FileNotFoundError",
+ body="{!r} does not exist.".format(path),
+ )
+
+ def parsing_error(self, path, exc_info):
+ exc_type, exc_value, exc_traceback = exc_info
+ exc_lines = "".join(
+ traceback.format_exception(exc_type, exc_value, exc_traceback),
+ )
+ return self._ERROR_MSG.format(
+ path=path,
+ type=exc_type.__name__,
+ body=exc_lines,
+ )
+
+ def validation_error(self, instance_path, error):
+ return self._ERROR_MSG.format(
+ path=instance_path,
+ type=error.__class__.__name__,
+ body=error,
+ )
+
+ def validation_success(self, instance_path):
+ return self._SUCCESS_MSG.format(path=instance_path)
+
+
+@attr.s
+class _PlainFormatter:
+
+ _error_format = attr.ib()
+
+ def filenotfound_error(self, path, exc_info):
+ return "{!r} does not exist.\n".format(path)
+
+ def parsing_error(self, path, exc_info):
+ return "Failed to parse {}: {}\n".format(
+ "" if path == "" else repr(path),
+ exc_info[1],
+ )
+
+ def validation_error(self, instance_path, error):
+ return self._error_format.format(file_name=instance_path, error=error)
+
+ def validation_success(self, instance_path):
+ return ""
+
+
+def _resolve_name_with_default(name):
+ if "." not in name:
+ name = "jsonschema." + name
+ return resolve_name(name)
+
+
+parser = argparse.ArgumentParser(
+ description="JSON Schema Validation CLI",
+)
+parser.add_argument(
+ "-i", "--instance",
+ action="append",
+ dest="instances",
+ help="""
+ a path to a JSON instance (i.e. filename.json) to validate (may
+ be specified multiple times). If no instances are provided via this
+ option, one will be expected on standard input.
+ """,
+)
+parser.add_argument(
+ "-F", "--error-format",
+ help="""
+ the format to use for each validation error message, specified
+ in a form suitable for str.format. This string will be passed
+ one formatted object named 'error' for each ValidationError.
+ Only provide this option when using --output=plain, which is the
+ default. If this argument is unprovided and --output=plain is
+ used, a simple default representation will be used.
+ """,
+)
+parser.add_argument(
+ "-o", "--output",
+ choices=["plain", "pretty"],
+ default="plain",
+ help="""
+ an output format to use. 'plain' (default) will produce minimal
+ text with one line for each error, while 'pretty' will produce
+ more detailed human-readable output on multiple lines.
+ """,
+)
+parser.add_argument(
+ "-V", "--validator",
+ type=_resolve_name_with_default,
+ help="""
+ the fully qualified object name of a validator to use, or, for
+ validators that are registered with jsonschema, simply the name
+ of the class.
+ """,
+)
+parser.add_argument(
+ "--base-uri",
+ help="""
+ a base URI to assign to the provided schema, even if it does not
+ declare one (via e.g. $id). This option can be used if you wish to
+ resolve relative references to a particular URI (or local path)
+ """,
+)
+parser.add_argument(
+ "--version",
+ action="version",
+ version=metadata.version("jsonschema"),
+)
+parser.add_argument(
+ "schema",
+ help="the path to a JSON Schema to validate with (i.e. schema.json)",
+)
+
+
+def parse_args(args):
+ arguments = vars(parser.parse_args(args=args or ["--help"]))
+ if arguments["output"] != "plain" and arguments["error_format"]:
+ raise parser.error(
+ "--error-format can only be used with --output plain",
+ )
+ if arguments["output"] == "plain" and arguments["error_format"] is None:
+ arguments["error_format"] = "{error.instance}: {error.message}\n"
+ return arguments
+
+
+def _validate_instance(instance_path, instance, validator, outputter):
+ invalid = False
+ for error in validator.iter_errors(instance):
+ invalid = True
+ outputter.validation_error(instance_path=instance_path, error=error)
+
+ if not invalid:
+ outputter.validation_success(instance_path=instance_path)
+ return invalid
+
+
+def main(args=sys.argv[1:]):
+ sys.exit(run(arguments=parse_args(args=args)))
+
+
+def run(arguments, stdout=sys.stdout, stderr=sys.stderr, stdin=sys.stdin):
+ outputter = _Outputter.from_arguments(
+ arguments=arguments,
+ stdout=stdout,
+ stderr=stderr,
+ )
+
+ try:
+ schema = outputter.load(arguments["schema"])
+ except _CannotLoadFile:
+ return 1
+
+ if arguments["validator"] is None:
+ arguments["validator"] = validator_for(schema)
+
+ try:
+ arguments["validator"].check_schema(schema)
+ except SchemaError as error:
+ outputter.validation_error(
+ instance_path=arguments["schema"],
+ error=error,
+ )
+ return 1
+
+ if arguments["instances"]:
+ load, instances = outputter.load, arguments["instances"]
+ else:
+ def load(_):
+ try:
+ return json.load(stdin)
+ except JSONDecodeError:
+ outputter.parsing_error(
+ path="", exc_info=sys.exc_info(),
+ )
+ raise _CannotLoadFile()
+ instances = [""]
+
+ resolver = RefResolver(
+ base_uri=arguments["base_uri"],
+ referrer=schema,
+ ) if arguments["base_uri"] is not None else None
+
+ validator = arguments["validator"](schema, resolver=resolver)
+ exit_code = 0
+ for each in instances:
+ try:
+ instance = load(each)
+ except _CannotLoadFile:
+ exit_code = 1
+ else:
+ exit_code |= _validate_instance(
+ instance_path=each,
+ instance=instance,
+ validator=validator,
+ outputter=outputter,
+ )
+
+ return exit_code
diff --git a/runtime/Lib/site-packages/jsonschema/exceptions.py b/runtime/Lib/site-packages/jsonschema/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..87db3df3a6dde1bbc0aae1128ca21f365e774666
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/exceptions.py
@@ -0,0 +1,396 @@
+"""
+Validation errors, and some surrounding helpers.
+"""
+from __future__ import annotations
+
+from collections import defaultdict, deque
+from pprint import pformat
+from textwrap import dedent, indent
+import heapq
+import itertools
+
+import attr
+
+from jsonschema import _utils
+
+WEAK_MATCHES: frozenset[str] = frozenset(["anyOf", "oneOf"])
+STRONG_MATCHES: frozenset[str] = frozenset()
+
+_unset = _utils.Unset()
+
+
+class _Error(Exception):
+ def __init__(
+ self,
+ message,
+ validator=_unset,
+ path=(),
+ cause=None,
+ context=(),
+ validator_value=_unset,
+ instance=_unset,
+ schema=_unset,
+ schema_path=(),
+ parent=None,
+ type_checker=_unset,
+ ):
+ super(_Error, self).__init__(
+ message,
+ validator,
+ path,
+ cause,
+ context,
+ validator_value,
+ instance,
+ schema,
+ schema_path,
+ parent,
+ )
+ self.message = message
+ self.path = self.relative_path = deque(path)
+ self.schema_path = self.relative_schema_path = deque(schema_path)
+ self.context = list(context)
+ self.cause = self.__cause__ = cause
+ self.validator = validator
+ self.validator_value = validator_value
+ self.instance = instance
+ self.schema = schema
+ self.parent = parent
+ self._type_checker = type_checker
+
+ for error in context:
+ error.parent = self
+
+ def __repr__(self):
+ return f"<{self.__class__.__name__}: {self.message!r}>"
+
+ def __str__(self):
+ essential_for_verbose = (
+ self.validator, self.validator_value, self.instance, self.schema,
+ )
+ if any(m is _unset for m in essential_for_verbose):
+ return self.message
+
+ schema_path = _utils.format_as_index(
+ container=self._word_for_schema_in_error_message,
+ indices=list(self.relative_schema_path)[:-1],
+ )
+ instance_path = _utils.format_as_index(
+ container=self._word_for_instance_in_error_message,
+ indices=self.relative_path,
+ )
+ prefix = 16 * " "
+
+ return dedent(
+ f"""\
+ {self.message}
+
+ Failed validating {self.validator!r} in {schema_path}:
+ {indent(pformat(self.schema, width=72), prefix).lstrip()}
+
+ On {instance_path}:
+ {indent(pformat(self.instance, width=72), prefix).lstrip()}
+ """.rstrip(),
+ )
+
+ @classmethod
+ def create_from(cls, other):
+ return cls(**other._contents())
+
+ @property
+ def absolute_path(self):
+ parent = self.parent
+ if parent is None:
+ return self.relative_path
+
+ path = deque(self.relative_path)
+ path.extendleft(reversed(parent.absolute_path))
+ return path
+
+ @property
+ def absolute_schema_path(self):
+ parent = self.parent
+ if parent is None:
+ return self.relative_schema_path
+
+ path = deque(self.relative_schema_path)
+ path.extendleft(reversed(parent.absolute_schema_path))
+ return path
+
+ @property
+ def json_path(self):
+ path = "$"
+ for elem in self.absolute_path:
+ if isinstance(elem, int):
+ path += "[" + str(elem) + "]"
+ else:
+ path += "." + elem
+ return path
+
+ def _set(self, type_checker=None, **kwargs):
+ if type_checker is not None and self._type_checker is _unset:
+ self._type_checker = type_checker
+
+ for k, v in kwargs.items():
+ if getattr(self, k) is _unset:
+ setattr(self, k, v)
+
+ def _contents(self):
+ attrs = (
+ "message", "cause", "context", "validator", "validator_value",
+ "path", "schema_path", "instance", "schema", "parent",
+ )
+ return dict((attr, getattr(self, attr)) for attr in attrs)
+
+ def _matches_type(self):
+ try:
+ expected = self.schema["type"]
+ except (KeyError, TypeError):
+ return False
+
+ if isinstance(expected, str):
+ return self._type_checker.is_type(self.instance, expected)
+
+ return any(
+ self._type_checker.is_type(self.instance, expected_type)
+ for expected_type in expected
+ )
+
+
+class ValidationError(_Error):
+ """
+ An instance was invalid under a provided schema.
+ """
+
+ _word_for_schema_in_error_message = "schema"
+ _word_for_instance_in_error_message = "instance"
+
+
+class SchemaError(_Error):
+ """
+ A schema was invalid under its corresponding metaschema.
+ """
+
+ _word_for_schema_in_error_message = "metaschema"
+ _word_for_instance_in_error_message = "schema"
+
+
+@attr.s(hash=True)
+class RefResolutionError(Exception):
+ """
+ A ref could not be resolved.
+ """
+
+ _cause = attr.ib()
+
+ def __str__(self):
+ return str(self._cause)
+
+
+class UndefinedTypeCheck(Exception):
+ """
+ A type checker was asked to check a type it did not have registered.
+ """
+
+ def __init__(self, type):
+ self.type = type
+
+ def __str__(self):
+ return f"Type {self.type!r} is unknown to this type checker"
+
+
+class UnknownType(Exception):
+ """
+ A validator was asked to validate an instance against an unknown type.
+ """
+
+ def __init__(self, type, instance, schema):
+ self.type = type
+ self.instance = instance
+ self.schema = schema
+
+ def __str__(self):
+ prefix = 16 * " "
+
+ return dedent(
+ f"""\
+ Unknown type {self.type!r} for validator with schema:
+ {indent(pformat(self.schema, width=72), prefix).lstrip()}
+
+ While checking instance:
+ {indent(pformat(self.instance, width=72), prefix).lstrip()}
+ """.rstrip(),
+ )
+
+
+class FormatError(Exception):
+ """
+ Validating a format failed.
+ """
+
+ def __init__(self, message, cause=None):
+ super(FormatError, self).__init__(message, cause)
+ self.message = message
+ self.cause = self.__cause__ = cause
+
+ def __str__(self):
+ return self.message
+
+
+class ErrorTree:
+ """
+ ErrorTrees make it easier to check which validations failed.
+ """
+
+ _instance = _unset
+
+ def __init__(self, errors=()):
+ self.errors = {}
+ self._contents = defaultdict(self.__class__)
+
+ for error in errors:
+ container = self
+ for element in error.path:
+ container = container[element]
+ container.errors[error.validator] = error
+
+ container._instance = error.instance
+
+ def __contains__(self, index):
+ """
+ Check whether ``instance[index]`` has any errors.
+ """
+
+ return index in self._contents
+
+ def __getitem__(self, index):
+ """
+ Retrieve the child tree one level down at the given ``index``.
+
+ If the index is not in the instance that this tree corresponds
+ to and is not known by this tree, whatever error would be raised
+ by ``instance.__getitem__`` will be propagated (usually this is
+ some subclass of `LookupError`.
+ """
+
+ if self._instance is not _unset and index not in self:
+ self._instance[index]
+ return self._contents[index]
+
+ def __setitem__(self, index, value):
+ """
+ Add an error to the tree at the given ``index``.
+ """
+ self._contents[index] = value
+
+ def __iter__(self):
+ """
+ Iterate (non-recursively) over the indices in the instance with errors.
+ """
+
+ return iter(self._contents)
+
+ def __len__(self):
+ """
+ Return the `total_errors`.
+ """
+ return self.total_errors
+
+ def __repr__(self):
+ total = len(self)
+ errors = "error" if total == 1 else "errors"
+ return f"<{self.__class__.__name__} ({total} total {errors})>"
+
+ @property
+ def total_errors(self):
+ """
+ The total number of errors in the entire tree, including children.
+ """
+
+ child_errors = sum(len(tree) for _, tree in self._contents.items())
+ return len(self.errors) + child_errors
+
+
+def by_relevance(weak=WEAK_MATCHES, strong=STRONG_MATCHES):
+ """
+ Create a key function that can be used to sort errors by relevance.
+
+ Arguments:
+ weak (set):
+ a collection of validation keywords to consider to be
+ "weak". If there are two errors at the same level of the
+ instance and one is in the set of weak validation keywords,
+ the other error will take priority. By default, :kw:`anyOf`
+ and :kw:`oneOf` are considered weak keywords and will be
+ superseded by other same-level validation errors.
+
+ strong (set):
+ a collection of validation keywords to consider to be
+ "strong"
+ """
+ def relevance(error):
+ validator = error.validator
+ return (
+ -len(error.path),
+ validator not in weak,
+ validator in strong,
+ not error._matches_type(),
+ )
+ return relevance
+
+
+relevance = by_relevance()
+
+
+def best_match(errors, key=relevance):
+ """
+ Try to find an error that appears to be the best match among given errors.
+
+ In general, errors that are higher up in the instance (i.e. for which
+ `ValidationError.path` is shorter) are considered better matches,
+ since they indicate "more" is wrong with the instance.
+
+ If the resulting match is either :kw:`oneOf` or :kw:`anyOf`, the
+ *opposite* assumption is made -- i.e. the deepest error is picked,
+ since these keywords only need to match once, and any other errors
+ may not be relevant.
+
+ Arguments:
+ errors (collections.abc.Iterable):
+
+ the errors to select from. Do not provide a mixture of
+ errors from different validation attempts (i.e. from
+ different instances or schemas), since it won't produce
+ sensical output.
+
+ key (collections.abc.Callable):
+
+ the key to use when sorting errors. See `relevance` and
+ transitively `by_relevance` for more details (the default is
+ to sort with the defaults of that function). Changing the
+ default is only useful if you want to change the function
+ that rates errors but still want the error context descent
+ done by this function.
+
+ Returns:
+ the best matching error, or ``None`` if the iterable was empty
+
+ .. note::
+
+ This function is a heuristic. Its return value may change for a given
+ set of inputs from version to version if better heuristics are added.
+ """
+ errors = iter(errors)
+ best = next(errors, None)
+ if best is None:
+ return
+ best = max(itertools.chain([best], errors), key=key)
+
+ while best.context:
+ # Calculate the minimum via nsmallest, because we don't recurse if
+ # all nested errors have the same relevance (i.e. if min == max == all)
+ smallest = heapq.nsmallest(2, best.context, key=key)
+ if len(smallest) == 2 and key(smallest[0]) == key(smallest[1]):
+ return best
+ best = smallest[0]
+ return best
diff --git a/runtime/Lib/site-packages/jsonschema/protocols.py b/runtime/Lib/site-packages/jsonschema/protocols.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f52166faf6424e318079cb1df55c1f4fa65494f
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/protocols.py
@@ -0,0 +1,225 @@
+"""
+typing.Protocol classes for jsonschema interfaces.
+"""
+
+# for reference material on Protocols, see
+# https://www.python.org/dev/peps/pep-0544/
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from typing import TYPE_CHECKING, Any, ClassVar, Iterable
+import sys
+
+# doing these imports with `try ... except ImportError` doesn't pass mypy
+# checking because mypy sees `typing._SpecialForm` and
+# `typing_extensions._SpecialForm` as incompatible
+#
+# see:
+# https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module
+# https://github.com/python/mypy/issues/4427
+if sys.version_info >= (3, 8):
+ from typing import Protocol, runtime_checkable
+else:
+ from typing_extensions import Protocol, runtime_checkable
+
+# in order for Sphinx to resolve references accurately from type annotations,
+# it needs to see names like `jsonschema.TypeChecker`
+# therefore, only import at type-checking time (to avoid circular references),
+# but use `jsonschema` for any types which will otherwise not be resolvable
+if TYPE_CHECKING:
+ import jsonschema
+ import jsonschema.validators
+
+from jsonschema.exceptions import ValidationError
+
+# For code authors working on the validator protocol, these are the three
+# use-cases which should be kept in mind:
+#
+# 1. As a protocol class, it can be used in type annotations to describe the
+# available methods and attributes of a validator
+# 2. It is the source of autodoc for the validator documentation
+# 3. It is runtime_checkable, meaning that it can be used in isinstance()
+# checks.
+#
+# Since protocols are not base classes, isinstance() checking is limited in
+# its capabilities. See docs on runtime_checkable for detail
+
+
+@runtime_checkable
+class Validator(Protocol):
+ """
+ The protocol to which all validator classes adhere.
+
+ Arguments:
+
+ schema:
+
+ The schema that the validator object will validate with.
+ It is assumed to be valid, and providing
+ an invalid schema can lead to undefined behavior. See
+ `Validator.check_schema` to validate a schema first.
+
+ resolver:
+
+ a resolver that will be used to resolve :kw:`$ref`
+ properties (JSON references). If unprovided, one will be created.
+
+ format_checker:
+
+ if provided, a checker which will be used to assert about
+ :kw:`format` properties present in the schema. If unprovided,
+ *no* format validation is done, and the presence of format
+ within schemas is strictly informational. Certain formats
+ require additional packages to be installed in order to assert
+ against instances. Ensure you've installed `jsonschema` with
+ its `extra (optional) dependencies ` when
+ invoking ``pip``.
+
+ .. deprecated:: v4.12.0
+
+ Subclassing validator classes now explicitly warns this is not part of
+ their public API.
+ """
+
+ #: An object representing the validator's meta schema (the schema that
+ #: describes valid schemas in the given version).
+ META_SCHEMA: ClassVar[Mapping]
+
+ #: A mapping of validation keywords (`str`\s) to functions that
+ #: validate the keyword with that name. For more information see
+ #: `creating-validators`.
+ VALIDATORS: ClassVar[Mapping]
+
+ #: A `jsonschema.TypeChecker` that will be used when validating
+ #: :kw:`type` keywords in JSON schemas.
+ TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
+
+ #: A `jsonschema.FormatChecker` that will be used when validating
+ #: :kw:`format` keywords in JSON schemas.
+ FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
+
+ #: A function which given a schema returns its ID.
+ ID_OF: Callable[[Any], str | None]
+
+ #: The schema that will be used to validate instances
+ schema: Mapping | bool
+
+ def __init__(
+ self,
+ schema: Mapping | bool,
+ resolver: jsonschema.validators.RefResolver | None = None,
+ format_checker: jsonschema.FormatChecker | None = None,
+ ) -> None:
+ ...
+
+ @classmethod
+ def check_schema(cls, schema: Mapping | bool) -> None:
+ """
+ Validate the given schema against the validator's `META_SCHEMA`.
+
+ Raises:
+
+ `jsonschema.exceptions.SchemaError`:
+
+ if the schema is invalid
+ """
+
+ def is_type(self, instance: Any, type: str) -> bool:
+ """
+ Check if the instance is of the given (JSON Schema) type.
+
+ Arguments:
+
+ instance:
+
+ the value to check
+
+ type:
+
+ the name of a known (JSON Schema) type
+
+ Returns:
+
+ whether the instance is of the given type
+
+ Raises:
+
+ `jsonschema.exceptions.UnknownType`:
+
+ if ``type`` is not a known type
+ """
+
+ def is_valid(self, instance: Any) -> bool:
+ """
+ Check if the instance is valid under the current `schema`.
+
+ Returns:
+
+ whether the instance is valid or not
+
+ >>> schema = {"maxItems" : 2}
+ >>> Draft202012Validator(schema).is_valid([2, 3, 4])
+ False
+ """
+
+ def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
+ r"""
+ Lazily yield each of the validation errors in the given instance.
+
+ >>> schema = {
+ ... "type" : "array",
+ ... "items" : {"enum" : [1, 2, 3]},
+ ... "maxItems" : 2,
+ ... }
+ >>> v = Draft202012Validator(schema)
+ >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
+ ... print(error.message)
+ 4 is not one of [1, 2, 3]
+ [2, 3, 4] is too long
+
+ .. deprecated:: v4.0.0
+
+ Calling this function with a second schema argument is deprecated.
+ Use `Validator.evolve` instead.
+ """
+
+ def validate(self, instance: Any) -> None:
+ """
+ Check if the instance is valid under the current `schema`.
+
+ Raises:
+
+ `jsonschema.exceptions.ValidationError`:
+
+ if the instance is invalid
+
+ >>> schema = {"maxItems" : 2}
+ >>> Draft202012Validator(schema).validate([2, 3, 4])
+ Traceback (most recent call last):
+ ...
+ ValidationError: [2, 3, 4] is too long
+ """
+
+ def evolve(self, **kwargs) -> "Validator":
+ """
+ Create a new validator like this one, but with given changes.
+
+ Preserves all other attributes, so can be used to e.g. create a
+ validator with a different schema but with the same :kw:`$ref`
+ resolution behavior.
+
+ >>> validator = Draft202012Validator({})
+ >>> validator.evolve(schema={"type": "number"})
+ Draft202012Validator(schema={'type': 'number'}, format_checker=None)
+
+ The returned object satisfies the validator protocol, but may not
+ be of the same concrete class! In particular this occurs
+ when a :kw:`$ref` occurs to a schema with a different
+ :kw:`$schema` than this one (i.e. for a different draft).
+
+ >>> validator.evolve(
+ ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
+ ... )
+ Draft7Validator(schema=..., format_checker=None)
+ """
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft2019-09.json b/runtime/Lib/site-packages/jsonschema/schemas/draft2019-09.json
new file mode 100644
index 0000000000000000000000000000000000000000..2248a0c80bbfc51b67863f848f60466f135cdb2b
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft2019-09.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/schema",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/core": true,
+ "https://json-schema.org/draft/2019-09/vocab/applicator": true,
+ "https://json-schema.org/draft/2019-09/vocab/validation": true,
+ "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
+ "https://json-schema.org/draft/2019-09/vocab/format": false,
+ "https://json-schema.org/draft/2019-09/vocab/content": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Core and Validation specifications meta-schema",
+ "allOf": [
+ {"$ref": "meta/core"},
+ {"$ref": "meta/applicator"},
+ {"$ref": "meta/validation"},
+ {"$ref": "meta/meta-data"},
+ {"$ref": "meta/format"},
+ {"$ref": "meta/content"}
+ ],
+ "type": ["object", "boolean"],
+ "properties": {
+ "definitions": {
+ "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
+ "type": "object",
+ "additionalProperties": { "$recursiveRef": "#" },
+ "default": {}
+ },
+ "dependencies": {
+ "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ { "$recursiveRef": "#" },
+ { "$ref": "meta/validation#/$defs/stringArray" }
+ ]
+ }
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft2020-12.json b/runtime/Lib/site-packages/jsonschema/schemas/draft2020-12.json
new file mode 100644
index 0000000000000000000000000000000000000000..d5e2d31c3c88e61f4c204cb6616887bba7e105dd
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft2020-12.json
@@ -0,0 +1,58 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/schema",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/core": true,
+ "https://json-schema.org/draft/2020-12/vocab/applicator": true,
+ "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
+ "https://json-schema.org/draft/2020-12/vocab/validation": true,
+ "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
+ "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
+ "https://json-schema.org/draft/2020-12/vocab/content": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Core and Validation specifications meta-schema",
+ "allOf": [
+ {"$ref": "meta/core"},
+ {"$ref": "meta/applicator"},
+ {"$ref": "meta/unevaluated"},
+ {"$ref": "meta/validation"},
+ {"$ref": "meta/meta-data"},
+ {"$ref": "meta/format-annotation"},
+ {"$ref": "meta/content"}
+ ],
+ "type": ["object", "boolean"],
+ "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
+ "properties": {
+ "definitions": {
+ "$comment": "\"definitions\" has been replaced by \"$defs\".",
+ "type": "object",
+ "additionalProperties": { "$dynamicRef": "#meta" },
+ "deprecated": true,
+ "default": {}
+ },
+ "dependencies": {
+ "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ { "$dynamicRef": "#meta" },
+ { "$ref": "meta/validation#/$defs/stringArray" }
+ ]
+ },
+ "deprecated": true,
+ "default": {}
+ },
+ "$recursiveAnchor": {
+ "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
+ "$ref": "meta/core#/$defs/anchorString",
+ "deprecated": true
+ },
+ "$recursiveRef": {
+ "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
+ "$ref": "meta/core#/$defs/uriReferenceString",
+ "deprecated": true
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft3.json b/runtime/Lib/site-packages/jsonschema/schemas/draft3.json
new file mode 100644
index 0000000000000000000000000000000000000000..8b26b1f89f9852e4f69f466dd7d718b21ba5b989
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft3.json
@@ -0,0 +1,172 @@
+{
+ "$schema" : "http://json-schema.org/draft-03/schema#",
+ "id" : "http://json-schema.org/draft-03/schema#",
+ "type" : "object",
+
+ "properties" : {
+ "type" : {
+ "type" : ["string", "array"],
+ "items" : {
+ "type" : ["string", {"$ref" : "#"}]
+ },
+ "uniqueItems" : true,
+ "default" : "any"
+ },
+
+ "properties" : {
+ "type" : "object",
+ "additionalProperties" : {"$ref" : "#"},
+ "default" : {}
+ },
+
+ "patternProperties" : {
+ "type" : "object",
+ "additionalProperties" : {"$ref" : "#"},
+ "default" : {}
+ },
+
+ "additionalProperties" : {
+ "type" : [{"$ref" : "#"}, "boolean"],
+ "default" : {}
+ },
+
+ "items" : {
+ "type" : [{"$ref" : "#"}, "array"],
+ "items" : {"$ref" : "#"},
+ "default" : {}
+ },
+
+ "additionalItems" : {
+ "type" : [{"$ref" : "#"}, "boolean"],
+ "default" : {}
+ },
+
+ "required" : {
+ "type" : "boolean",
+ "default" : false
+ },
+
+ "dependencies" : {
+ "type" : "object",
+ "additionalProperties" : {
+ "type" : ["string", "array", {"$ref" : "#"}],
+ "items" : {
+ "type" : "string"
+ }
+ },
+ "default" : {}
+ },
+
+ "minimum" : {
+ "type" : "number"
+ },
+
+ "maximum" : {
+ "type" : "number"
+ },
+
+ "exclusiveMinimum" : {
+ "type" : "boolean",
+ "default" : false
+ },
+
+ "exclusiveMaximum" : {
+ "type" : "boolean",
+ "default" : false
+ },
+
+ "minItems" : {
+ "type" : "integer",
+ "minimum" : 0,
+ "default" : 0
+ },
+
+ "maxItems" : {
+ "type" : "integer",
+ "minimum" : 0
+ },
+
+ "uniqueItems" : {
+ "type" : "boolean",
+ "default" : false
+ },
+
+ "pattern" : {
+ "type" : "string",
+ "format" : "regex"
+ },
+
+ "minLength" : {
+ "type" : "integer",
+ "minimum" : 0,
+ "default" : 0
+ },
+
+ "maxLength" : {
+ "type" : "integer"
+ },
+
+ "enum" : {
+ "type" : "array",
+ "minItems" : 1,
+ "uniqueItems" : true
+ },
+
+ "default" : {
+ "type" : "any"
+ },
+
+ "title" : {
+ "type" : "string"
+ },
+
+ "description" : {
+ "type" : "string"
+ },
+
+ "format" : {
+ "type" : "string"
+ },
+
+ "divisibleBy" : {
+ "type" : "number",
+ "minimum" : 0,
+ "exclusiveMinimum" : true,
+ "default" : 1
+ },
+
+ "disallow" : {
+ "type" : ["string", "array"],
+ "items" : {
+ "type" : ["string", {"$ref" : "#"}]
+ },
+ "uniqueItems" : true
+ },
+
+ "extends" : {
+ "type" : [{"$ref" : "#"}, "array"],
+ "items" : {"$ref" : "#"},
+ "default" : {}
+ },
+
+ "id" : {
+ "type" : "string"
+ },
+
+ "$ref" : {
+ "type" : "string"
+ },
+
+ "$schema" : {
+ "type" : "string",
+ "format" : "uri"
+ }
+ },
+
+ "dependencies" : {
+ "exclusiveMinimum" : "minimum",
+ "exclusiveMaximum" : "maximum"
+ },
+
+ "default" : {}
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft4.json b/runtime/Lib/site-packages/jsonschema/schemas/draft4.json
new file mode 100644
index 0000000000000000000000000000000000000000..bcbb84743e3838fab7cbec5f0a5bcbafcfc99136
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft4.json
@@ -0,0 +1,149 @@
+{
+ "id": "http://json-schema.org/draft-04/schema#",
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "description": "Core schema meta-schema",
+ "definitions": {
+ "schemaArray": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#" }
+ },
+ "positiveInteger": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "positiveIntegerDefault0": {
+ "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
+ },
+ "simpleTypes": {
+ "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
+ },
+ "stringArray": {
+ "type": "array",
+ "items": { "type": "string" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ },
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "$schema": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "default": {},
+ "multipleOf": {
+ "type": "number",
+ "minimum": 0,
+ "exclusiveMinimum": true
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "exclusiveMaximum": {
+ "type": "boolean",
+ "default": false
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "exclusiveMinimum": {
+ "type": "boolean",
+ "default": false
+ },
+ "maxLength": { "$ref": "#/definitions/positiveInteger" },
+ "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
+ "pattern": {
+ "type": "string",
+ "format": "regex"
+ },
+ "additionalItems": {
+ "anyOf": [
+ { "type": "boolean" },
+ { "$ref": "#" }
+ ],
+ "default": {}
+ },
+ "items": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/schemaArray" }
+ ],
+ "default": {}
+ },
+ "maxItems": { "$ref": "#/definitions/positiveInteger" },
+ "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
+ "uniqueItems": {
+ "type": "boolean",
+ "default": false
+ },
+ "maxProperties": { "$ref": "#/definitions/positiveInteger" },
+ "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
+ "required": { "$ref": "#/definitions/stringArray" },
+ "additionalProperties": {
+ "anyOf": [
+ { "type": "boolean" },
+ { "$ref": "#" }
+ ],
+ "default": {}
+ },
+ "definitions": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "properties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "patternProperties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "dependencies": {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/stringArray" }
+ ]
+ }
+ },
+ "enum": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true
+ },
+ "type": {
+ "anyOf": [
+ { "$ref": "#/definitions/simpleTypes" },
+ {
+ "type": "array",
+ "items": { "$ref": "#/definitions/simpleTypes" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ ]
+ },
+ "format": { "type": "string" },
+ "allOf": { "$ref": "#/definitions/schemaArray" },
+ "anyOf": { "$ref": "#/definitions/schemaArray" },
+ "oneOf": { "$ref": "#/definitions/schemaArray" },
+ "not": { "$ref": "#" }
+ },
+ "dependencies": {
+ "exclusiveMaximum": [ "maximum" ],
+ "exclusiveMinimum": [ "minimum" ]
+ },
+ "default": {}
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft6.json b/runtime/Lib/site-packages/jsonschema/schemas/draft6.json
new file mode 100644
index 0000000000000000000000000000000000000000..a0d2bf7896c2619ae657cd3b3266660156021706
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft6.json
@@ -0,0 +1,153 @@
+{
+ "$schema": "http://json-schema.org/draft-06/schema#",
+ "$id": "http://json-schema.org/draft-06/schema#",
+ "title": "Core schema meta-schema",
+ "definitions": {
+ "schemaArray": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#" }
+ },
+ "nonNegativeInteger": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "nonNegativeIntegerDefault0": {
+ "allOf": [
+ { "$ref": "#/definitions/nonNegativeInteger" },
+ { "default": 0 }
+ ]
+ },
+ "simpleTypes": {
+ "enum": [
+ "array",
+ "boolean",
+ "integer",
+ "null",
+ "number",
+ "object",
+ "string"
+ ]
+ },
+ "stringArray": {
+ "type": "array",
+ "items": { "type": "string" },
+ "uniqueItems": true,
+ "default": []
+ }
+ },
+ "type": ["object", "boolean"],
+ "properties": {
+ "$id": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "$schema": {
+ "type": "string",
+ "format": "uri"
+ },
+ "$ref": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "default": {},
+ "examples": {
+ "type": "array",
+ "items": {}
+ },
+ "multipleOf": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "exclusiveMaximum": {
+ "type": "number"
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "exclusiveMinimum": {
+ "type": "number"
+ },
+ "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "pattern": {
+ "type": "string",
+ "format": "regex"
+ },
+ "additionalItems": { "$ref": "#" },
+ "items": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/schemaArray" }
+ ],
+ "default": {}
+ },
+ "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "uniqueItems": {
+ "type": "boolean",
+ "default": false
+ },
+ "contains": { "$ref": "#" },
+ "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "required": { "$ref": "#/definitions/stringArray" },
+ "additionalProperties": { "$ref": "#" },
+ "definitions": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "properties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "patternProperties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "propertyNames": { "format": "regex" },
+ "default": {}
+ },
+ "dependencies": {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/stringArray" }
+ ]
+ }
+ },
+ "propertyNames": { "$ref": "#" },
+ "const": {},
+ "enum": {
+ "type": "array"
+ },
+ "type": {
+ "anyOf": [
+ { "$ref": "#/definitions/simpleTypes" },
+ {
+ "type": "array",
+ "items": { "$ref": "#/definitions/simpleTypes" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ ]
+ },
+ "format": { "type": "string" },
+ "allOf": { "$ref": "#/definitions/schemaArray" },
+ "anyOf": { "$ref": "#/definitions/schemaArray" },
+ "oneOf": { "$ref": "#/definitions/schemaArray" },
+ "not": { "$ref": "#" }
+ },
+ "default": {}
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/draft7.json b/runtime/Lib/site-packages/jsonschema/schemas/draft7.json
new file mode 100644
index 0000000000000000000000000000000000000000..746cde9690134529bdcde889f72c7ad5259f24ad
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/draft7.json
@@ -0,0 +1,166 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "http://json-schema.org/draft-07/schema#",
+ "title": "Core schema meta-schema",
+ "definitions": {
+ "schemaArray": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#" }
+ },
+ "nonNegativeInteger": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "nonNegativeIntegerDefault0": {
+ "allOf": [
+ { "$ref": "#/definitions/nonNegativeInteger" },
+ { "default": 0 }
+ ]
+ },
+ "simpleTypes": {
+ "enum": [
+ "array",
+ "boolean",
+ "integer",
+ "null",
+ "number",
+ "object",
+ "string"
+ ]
+ },
+ "stringArray": {
+ "type": "array",
+ "items": { "type": "string" },
+ "uniqueItems": true,
+ "default": []
+ }
+ },
+ "type": ["object", "boolean"],
+ "properties": {
+ "$id": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "$schema": {
+ "type": "string",
+ "format": "uri"
+ },
+ "$ref": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "$comment": {
+ "type": "string"
+ },
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "default": true,
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "examples": {
+ "type": "array",
+ "items": true
+ },
+ "multipleOf": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "exclusiveMaximum": {
+ "type": "number"
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "exclusiveMinimum": {
+ "type": "number"
+ },
+ "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "pattern": {
+ "type": "string",
+ "format": "regex"
+ },
+ "additionalItems": { "$ref": "#" },
+ "items": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/schemaArray" }
+ ],
+ "default": true
+ },
+ "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "uniqueItems": {
+ "type": "boolean",
+ "default": false
+ },
+ "contains": { "$ref": "#" },
+ "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
+ "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
+ "required": { "$ref": "#/definitions/stringArray" },
+ "additionalProperties": { "$ref": "#" },
+ "definitions": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "properties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "default": {}
+ },
+ "patternProperties": {
+ "type": "object",
+ "additionalProperties": { "$ref": "#" },
+ "propertyNames": { "format": "regex" },
+ "default": {}
+ },
+ "dependencies": {
+ "type": "object",
+ "additionalProperties": {
+ "anyOf": [
+ { "$ref": "#" },
+ { "$ref": "#/definitions/stringArray" }
+ ]
+ }
+ },
+ "propertyNames": { "$ref": "#" },
+ "const": true,
+ "enum": {
+ "type": "array",
+ "items": true
+ },
+ "type": {
+ "anyOf": [
+ { "$ref": "#/definitions/simpleTypes" },
+ {
+ "type": "array",
+ "items": { "$ref": "#/definitions/simpleTypes" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ ]
+ },
+ "format": { "type": "string" },
+ "contentMediaType": { "type": "string" },
+ "contentEncoding": { "type": "string" },
+ "if": {"$ref": "#"},
+ "then": {"$ref": "#"},
+ "else": {"$ref": "#"},
+ "allOf": { "$ref": "#/definitions/schemaArray" },
+ "anyOf": { "$ref": "#/definitions/schemaArray" },
+ "oneOf": { "$ref": "#/definitions/schemaArray" },
+ "not": { "$ref": "#" }
+ },
+ "default": true
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/applicator b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/applicator
new file mode 100644
index 0000000000000000000000000000000000000000..24a1cc4f4f54b5a556de93c2799853b31e78e512
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/applicator
@@ -0,0 +1,56 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/applicator": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Applicator vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "additionalItems": { "$recursiveRef": "#" },
+ "unevaluatedItems": { "$recursiveRef": "#" },
+ "items": {
+ "anyOf": [
+ { "$recursiveRef": "#" },
+ { "$ref": "#/$defs/schemaArray" }
+ ]
+ },
+ "contains": { "$recursiveRef": "#" },
+ "additionalProperties": { "$recursiveRef": "#" },
+ "unevaluatedProperties": { "$recursiveRef": "#" },
+ "properties": {
+ "type": "object",
+ "additionalProperties": { "$recursiveRef": "#" },
+ "default": {}
+ },
+ "patternProperties": {
+ "type": "object",
+ "additionalProperties": { "$recursiveRef": "#" },
+ "propertyNames": { "format": "regex" },
+ "default": {}
+ },
+ "dependentSchemas": {
+ "type": "object",
+ "additionalProperties": {
+ "$recursiveRef": "#"
+ }
+ },
+ "propertyNames": { "$recursiveRef": "#" },
+ "if": { "$recursiveRef": "#" },
+ "then": { "$recursiveRef": "#" },
+ "else": { "$recursiveRef": "#" },
+ "allOf": { "$ref": "#/$defs/schemaArray" },
+ "anyOf": { "$ref": "#/$defs/schemaArray" },
+ "oneOf": { "$ref": "#/$defs/schemaArray" },
+ "not": { "$recursiveRef": "#" }
+ },
+ "$defs": {
+ "schemaArray": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$recursiveRef": "#" }
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/content b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/content
new file mode 100644
index 0000000000000000000000000000000000000000..f6752a8efbeb74a7b7b2e74cbb272c422a975363
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/content
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/content",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/content": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Content vocabulary meta-schema",
+
+ "type": ["object", "boolean"],
+ "properties": {
+ "contentMediaType": { "type": "string" },
+ "contentEncoding": { "type": "string" },
+ "contentSchema": { "$recursiveRef": "#" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/core b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/core
new file mode 100644
index 0000000000000000000000000000000000000000..eb708a56044146bb7903fd59159725a0c693aefe
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/core
@@ -0,0 +1,57 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/core",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/core": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Core vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "$id": {
+ "type": "string",
+ "format": "uri-reference",
+ "$comment": "Non-empty fragments not allowed.",
+ "pattern": "^[^#]*#?$"
+ },
+ "$schema": {
+ "type": "string",
+ "format": "uri"
+ },
+ "$anchor": {
+ "type": "string",
+ "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
+ },
+ "$ref": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "$recursiveRef": {
+ "type": "string",
+ "format": "uri-reference"
+ },
+ "$recursiveAnchor": {
+ "type": "boolean",
+ "default": false
+ },
+ "$vocabulary": {
+ "type": "object",
+ "propertyNames": {
+ "type": "string",
+ "format": "uri"
+ },
+ "additionalProperties": {
+ "type": "boolean"
+ }
+ },
+ "$comment": {
+ "type": "string"
+ },
+ "$defs": {
+ "type": "object",
+ "additionalProperties": { "$recursiveRef": "#" },
+ "default": {}
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/meta-data b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/meta-data
new file mode 100644
index 0000000000000000000000000000000000000000..da04cff6d346f26bfe5bd21b636609fecd583628
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/meta-data
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/meta-data": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Meta-data vocabulary meta-schema",
+
+ "type": ["object", "boolean"],
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "default": true,
+ "deprecated": {
+ "type": "boolean",
+ "default": false
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "writeOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "examples": {
+ "type": "array",
+ "items": true
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/validation b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/validation
new file mode 100644
index 0000000000000000000000000000000000000000..9f59677b30c238f07a358c0c8ee72c3b710dc24d
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2019-09/validation
@@ -0,0 +1,98 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/validation",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/validation": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Validation vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "multipleOf": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "exclusiveMaximum": {
+ "type": "number"
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "exclusiveMinimum": {
+ "type": "number"
+ },
+ "maxLength": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "pattern": {
+ "type": "string",
+ "format": "regex"
+ },
+ "maxItems": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "uniqueItems": {
+ "type": "boolean",
+ "default": false
+ },
+ "maxContains": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minContains": {
+ "$ref": "#/$defs/nonNegativeInteger",
+ "default": 1
+ },
+ "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "required": { "$ref": "#/$defs/stringArray" },
+ "dependentRequired": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/stringArray"
+ }
+ },
+ "const": true,
+ "enum": {
+ "type": "array",
+ "items": true
+ },
+ "type": {
+ "anyOf": [
+ { "$ref": "#/$defs/simpleTypes" },
+ {
+ "type": "array",
+ "items": { "$ref": "#/$defs/simpleTypes" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ ]
+ }
+ },
+ "$defs": {
+ "nonNegativeInteger": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "nonNegativeIntegerDefault0": {
+ "$ref": "#/$defs/nonNegativeInteger",
+ "default": 0
+ },
+ "simpleTypes": {
+ "enum": [
+ "array",
+ "boolean",
+ "integer",
+ "null",
+ "number",
+ "object",
+ "string"
+ ]
+ },
+ "stringArray": {
+ "type": "array",
+ "items": { "type": "string" },
+ "uniqueItems": true,
+ "default": []
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/applicator b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/applicator
new file mode 100644
index 0000000000000000000000000000000000000000..ca69923096f3a2e4fe5eb8152a92d87d146cf021
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/applicator
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/applicator": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Applicator vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "prefixItems": { "$ref": "#/$defs/schemaArray" },
+ "items": { "$dynamicRef": "#meta" },
+ "contains": { "$dynamicRef": "#meta" },
+ "additionalProperties": { "$dynamicRef": "#meta" },
+ "properties": {
+ "type": "object",
+ "additionalProperties": { "$dynamicRef": "#meta" },
+ "default": {}
+ },
+ "patternProperties": {
+ "type": "object",
+ "additionalProperties": { "$dynamicRef": "#meta" },
+ "propertyNames": { "format": "regex" },
+ "default": {}
+ },
+ "dependentSchemas": {
+ "type": "object",
+ "additionalProperties": { "$dynamicRef": "#meta" },
+ "default": {}
+ },
+ "propertyNames": { "$dynamicRef": "#meta" },
+ "if": { "$dynamicRef": "#meta" },
+ "then": { "$dynamicRef": "#meta" },
+ "else": { "$dynamicRef": "#meta" },
+ "allOf": { "$ref": "#/$defs/schemaArray" },
+ "anyOf": { "$ref": "#/$defs/schemaArray" },
+ "oneOf": { "$ref": "#/$defs/schemaArray" },
+ "not": { "$dynamicRef": "#meta" }
+ },
+ "$defs": {
+ "schemaArray": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "$dynamicRef": "#meta" }
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/content b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/content
new file mode 100644
index 0000000000000000000000000000000000000000..2f6e056a9ac2399582eaf05985a26acf9161f213
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/content
@@ -0,0 +1,17 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/content",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/content": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Content vocabulary meta-schema",
+
+ "type": ["object", "boolean"],
+ "properties": {
+ "contentEncoding": { "type": "string" },
+ "contentMediaType": { "type": "string" },
+ "contentSchema": { "$dynamicRef": "#meta" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/core b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/core
new file mode 100644
index 0000000000000000000000000000000000000000..dfc092d9646e1ea89e4d771bfcf2a4ca87eeac75
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/core
@@ -0,0 +1,51 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/core",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/core": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Core vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "$id": {
+ "$ref": "#/$defs/uriReferenceString",
+ "$comment": "Non-empty fragments not allowed.",
+ "pattern": "^[^#]*#?$"
+ },
+ "$schema": { "$ref": "#/$defs/uriString" },
+ "$ref": { "$ref": "#/$defs/uriReferenceString" },
+ "$anchor": { "$ref": "#/$defs/anchorString" },
+ "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" },
+ "$dynamicAnchor": { "$ref": "#/$defs/anchorString" },
+ "$vocabulary": {
+ "type": "object",
+ "propertyNames": { "$ref": "#/$defs/uriString" },
+ "additionalProperties": {
+ "type": "boolean"
+ }
+ },
+ "$comment": {
+ "type": "string"
+ },
+ "$defs": {
+ "type": "object",
+ "additionalProperties": { "$dynamicRef": "#meta" }
+ }
+ },
+ "$defs": {
+ "anchorString": {
+ "type": "string",
+ "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
+ },
+ "uriString": {
+ "type": "string",
+ "format": "uri"
+ },
+ "uriReferenceString": {
+ "type": "string",
+ "format": "uri-reference"
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format
new file mode 100644
index 0000000000000000000000000000000000000000..09bbfdda972ca77cd26e290d70ab59db4bbe8a27
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "$id": "https://json-schema.org/draft/2019-09/meta/format",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2019-09/vocab/format": true
+ },
+ "$recursiveAnchor": true,
+
+ "title": "Format vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "format": { "type": "string" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-annotation b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-annotation
new file mode 100644
index 0000000000000000000000000000000000000000..51ef7ea118c34e8ac3da66c973bae02b9e8325d8
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-annotation
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Format vocabulary meta-schema for annotation results",
+ "type": ["object", "boolean"],
+ "properties": {
+ "format": { "type": "string" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-assertion b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-assertion
new file mode 100644
index 0000000000000000000000000000000000000000..5e73fd7571e504990f7a055da960056f07dcdb19
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/format-assertion
@@ -0,0 +1,14 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/format-assertion",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/format-assertion": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Format vocabulary meta-schema for assertion results",
+ "type": ["object", "boolean"],
+ "properties": {
+ "format": { "type": "string" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/meta-data b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/meta-data
new file mode 100644
index 0000000000000000000000000000000000000000..05cbc22afde5ebe6ba84957ca412277bde1e4b08
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/meta-data
@@ -0,0 +1,37 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/meta-data": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Meta-data vocabulary meta-schema",
+
+ "type": ["object", "boolean"],
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "default": true,
+ "deprecated": {
+ "type": "boolean",
+ "default": false
+ },
+ "readOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "writeOnly": {
+ "type": "boolean",
+ "default": false
+ },
+ "examples": {
+ "type": "array",
+ "items": true
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/unevaluated b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/unevaluated
new file mode 100644
index 0000000000000000000000000000000000000000..5f62a3ffa20be07dc813d6b8a154fa8451d0dc61
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/unevaluated
@@ -0,0 +1,15 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Unevaluated applicator vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "unevaluatedItems": { "$dynamicRef": "#meta" },
+ "unevaluatedProperties": { "$dynamicRef": "#meta" }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/validation b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/validation
new file mode 100644
index 0000000000000000000000000000000000000000..606b87ba2ec213d63b9e2035a6acc4edcb4b8357
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/schemas/vocabularies/draft2020-12/validation
@@ -0,0 +1,98 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://json-schema.org/draft/2020-12/meta/validation",
+ "$vocabulary": {
+ "https://json-schema.org/draft/2020-12/vocab/validation": true
+ },
+ "$dynamicAnchor": "meta",
+
+ "title": "Validation vocabulary meta-schema",
+ "type": ["object", "boolean"],
+ "properties": {
+ "type": {
+ "anyOf": [
+ { "$ref": "#/$defs/simpleTypes" },
+ {
+ "type": "array",
+ "items": { "$ref": "#/$defs/simpleTypes" },
+ "minItems": 1,
+ "uniqueItems": true
+ }
+ ]
+ },
+ "const": true,
+ "enum": {
+ "type": "array",
+ "items": true
+ },
+ "multipleOf": {
+ "type": "number",
+ "exclusiveMinimum": 0
+ },
+ "maximum": {
+ "type": "number"
+ },
+ "exclusiveMaximum": {
+ "type": "number"
+ },
+ "minimum": {
+ "type": "number"
+ },
+ "exclusiveMinimum": {
+ "type": "number"
+ },
+ "maxLength": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "pattern": {
+ "type": "string",
+ "format": "regex"
+ },
+ "maxItems": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "uniqueItems": {
+ "type": "boolean",
+ "default": false
+ },
+ "maxContains": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minContains": {
+ "$ref": "#/$defs/nonNegativeInteger",
+ "default": 1
+ },
+ "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" },
+ "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" },
+ "required": { "$ref": "#/$defs/stringArray" },
+ "dependentRequired": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/$defs/stringArray"
+ }
+ }
+ },
+ "$defs": {
+ "nonNegativeInteger": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "nonNegativeIntegerDefault0": {
+ "$ref": "#/$defs/nonNegativeInteger",
+ "default": 0
+ },
+ "simpleTypes": {
+ "enum": [
+ "array",
+ "boolean",
+ "integer",
+ "null",
+ "number",
+ "object",
+ "string"
+ ]
+ },
+ "stringArray": {
+ "type": "array",
+ "items": { "type": "string" },
+ "uniqueItems": true,
+ "default": []
+ }
+ }
+}
diff --git a/runtime/Lib/site-packages/jsonschema/tests/__init__.py b/runtime/Lib/site-packages/jsonschema/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/runtime/Lib/site-packages/jsonschema/tests/_helpers.py b/runtime/Lib/site-packages/jsonschema/tests/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..754ff83095e72b175a9905439f96af8bb189c07a
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/_helpers.py
@@ -0,0 +1,25 @@
+from urllib.parse import urljoin
+
+
+def issues_url(organization, repository):
+ return urljoin(
+ "https://github.com/", f"{organization}/{repository}/issues/",
+ )
+
+
+ISSUES_URL = issues_url("python-jsonschema", "jsonschema")
+TEST_SUITE_ISSUES_URL = issues_url("json-schema-org", "JSON-Schema-Test-Suite")
+
+
+def bug(issue=None):
+ message = "A known bug."
+ if issue is not None:
+ message += f" See {urljoin(ISSUES_URL, str(issue))}."
+ return message
+
+
+def test_suite_bug(issue):
+ return (
+ "A known test suite bug. "
+ f"See {urljoin(TEST_SUITE_ISSUES_URL, str(issue))}."
+ )
diff --git a/runtime/Lib/site-packages/jsonschema/tests/_suite.py b/runtime/Lib/site-packages/jsonschema/tests/_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3129e045fc938d96ba43b227865f7177d14eda1
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/_suite.py
@@ -0,0 +1,241 @@
+"""
+Python representations of the JSON Schema Test Suite tests.
+"""
+
+from functools import partial
+from pathlib import Path
+import json
+import os
+import re
+import subprocess
+import sys
+import unittest
+
+import attr
+
+from jsonschema.validators import _VALIDATORS
+import jsonschema
+
+
+def _find_suite():
+ root = os.environ.get("JSON_SCHEMA_TEST_SUITE")
+ if root is not None:
+ return Path(root)
+
+ root = Path(jsonschema.__file__).parent.parent / "json"
+ if not root.is_dir(): # pragma: no cover
+ raise ValueError(
+ (
+ "Can't find the JSON-Schema-Test-Suite directory. "
+ "Set the 'JSON_SCHEMA_TEST_SUITE' environment "
+ "variable or run the tests from alongside a checkout "
+ "of the suite."
+ ),
+ )
+ return root
+
+
+@attr.s(hash=True)
+class Suite:
+
+ _root = attr.ib(default=attr.Factory(_find_suite))
+
+ def _remotes(self):
+ jsonschema_suite = self._root.joinpath("bin", "jsonschema_suite")
+ remotes = subprocess.check_output(
+ [sys.executable, str(jsonschema_suite), "remotes"],
+ )
+ return json.loads(remotes.decode("utf-8"))
+
+ def benchmark(self, runner): # pragma: no cover
+ for name, Validator in _VALIDATORS.items():
+ self.version(name=name).benchmark(
+ runner=runner,
+ Validator=Validator,
+ )
+
+ def version(self, name):
+ return Version(
+ name=name,
+ path=self._root.joinpath("tests", name),
+ remotes=self._remotes(),
+ )
+
+
+@attr.s(hash=True)
+class Version:
+
+ _path = attr.ib()
+ _remotes = attr.ib()
+
+ name = attr.ib()
+
+ def benchmark(self, runner, **kwargs): # pragma: no cover
+ for suite in self.tests():
+ for test in suite:
+ runner.bench_func(
+ test.fully_qualified_name,
+ partial(test.validate_ignoring_errors, **kwargs),
+ )
+
+ def tests(self):
+ return (
+ test
+ for child in self._path.glob("*.json")
+ for test in self._tests_in(
+ subject=child.name[:-5],
+ path=child,
+ )
+ )
+
+ def format_tests(self):
+ path = self._path.joinpath("optional", "format")
+ return (
+ test
+ for child in path.glob("*.json")
+ for test in self._tests_in(
+ subject=child.name[:-5],
+ path=child,
+ )
+ )
+
+ def optional_tests_of(self, name):
+ return self._tests_in(
+ subject=name,
+ path=self._path.joinpath("optional", name + ".json"),
+ )
+
+ def to_unittest_testcase(self, *suites, **kwargs):
+ name = kwargs.pop("name", "Test" + self.name.title().replace("-", ""))
+ methods = {
+ test.method_name: test.to_unittest_method(**kwargs)
+ for suite in suites
+ for tests in suite
+ for test in tests
+ }
+ cls = type(name, (unittest.TestCase,), methods)
+
+ try:
+ cls.__module__ = _someone_save_us_the_module_of_the_caller()
+ except Exception: # pragma: no cover
+ # We're doing crazy things, so if they go wrong, like a function
+ # behaving differently on some other interpreter, just make them
+ # not happen.
+ pass
+
+ return cls
+
+ def _tests_in(self, subject, path):
+ for each in json.loads(path.read_text(encoding="utf-8")):
+ yield (
+ _Test(
+ version=self,
+ subject=subject,
+ case_description=each["description"],
+ schema=each["schema"],
+ remotes=self._remotes,
+ **test,
+ ) for test in each["tests"]
+ )
+
+
+@attr.s(hash=True, repr=False)
+class _Test:
+
+ version = attr.ib()
+
+ subject = attr.ib()
+ case_description = attr.ib()
+ description = attr.ib()
+
+ data = attr.ib()
+ schema = attr.ib(repr=False)
+
+ valid = attr.ib()
+
+ _remotes = attr.ib()
+
+ comment = attr.ib(default=None)
+
+ def __repr__(self): # pragma: no cover
+ return "".format(self.fully_qualified_name)
+
+ @property
+ def fully_qualified_name(self): # pragma: no cover
+ return " > ".join(
+ [
+ self.version.name,
+ self.subject,
+ self.case_description,
+ self.description,
+ ],
+ )
+
+ @property
+ def method_name(self):
+ delimiters = r"[\W\- ]+"
+ return "test_{}_{}_{}".format(
+ re.sub(delimiters, "_", self.subject),
+ re.sub(delimiters, "_", self.case_description),
+ re.sub(delimiters, "_", self.description),
+ )
+
+ def to_unittest_method(self, skip=lambda test: None, **kwargs):
+ if self.valid:
+ def fn(this):
+ self.validate(**kwargs)
+ else:
+ def fn(this):
+ with this.assertRaises(jsonschema.ValidationError):
+ self.validate(**kwargs)
+
+ fn.__name__ = self.method_name
+ reason = skip(self)
+ if reason is None or os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
+ return fn
+ elif os.environ.get("JSON_SCHEMA_EXPECTED_FAILURES", "0") != "0":
+ return unittest.expectedFailure(fn)
+ else:
+ return unittest.skip(reason)(fn)
+
+ def validate(self, Validator, **kwargs):
+ Validator.check_schema(self.schema)
+ resolver = jsonschema.RefResolver.from_schema(
+ schema=self.schema,
+ store=self._remotes,
+ id_of=Validator.ID_OF,
+ )
+
+ # XXX: #693 asks to improve the public API for this, since yeah, it's
+ # bad. Figures that since it's hard for end-users, we experience
+ # the pain internally here too.
+ def prevent_network_access(uri):
+ raise RuntimeError(f"Tried to access the network: {uri}")
+ resolver.resolve_remote = prevent_network_access
+
+ validator = Validator(schema=self.schema, resolver=resolver, **kwargs)
+ if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0":
+ breakpoint()
+ validator.validate(instance=self.data)
+
+ def validate_ignoring_errors(self, Validator): # pragma: no cover
+ try:
+ self.validate(Validator=Validator)
+ except jsonschema.ValidationError:
+ pass
+
+
+def _someone_save_us_the_module_of_the_caller():
+ """
+ The FQON of the module 2nd stack frames up from here.
+
+ This is intended to allow us to dynamically return test case classes that
+ are indistinguishable from being defined in the module that wants them.
+
+ Otherwise, trial will mis-print the FQON, and copy pasting it won't re-run
+ the class that really is running.
+
+ Save us all, this is all so so so so so terrible.
+ """
+
+ return sys._getframe(2).f_globals["__name__"]
diff --git a/runtime/Lib/site-packages/jsonschema/tests/fuzz_validate.py b/runtime/Lib/site-packages/jsonschema/tests/fuzz_validate.py
new file mode 100644
index 0000000000000000000000000000000000000000..c12e88bcfe9bfdc0e0ffaab502789a6b585d4be2
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/fuzz_validate.py
@@ -0,0 +1,50 @@
+"""
+Fuzzing setup for OSS-Fuzz.
+
+See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the
+other half of the setup here.
+"""
+import sys
+
+from hypothesis import given, strategies
+
+import jsonschema
+
+PRIM = strategies.one_of(
+ strategies.booleans(),
+ strategies.integers(),
+ strategies.floats(allow_nan=False, allow_infinity=False),
+ strategies.text(),
+)
+DICT = strategies.recursive(
+ base=strategies.one_of(
+ strategies.booleans(),
+ strategies.dictionaries(strategies.text(), PRIM),
+ ),
+ extend=lambda inner: strategies.dictionaries(strategies.text(), inner),
+)
+
+
+@given(obj1=DICT, obj2=DICT)
+def test_schemas(obj1, obj2):
+ try:
+ jsonschema.validate(instance=obj1, schema=obj2)
+ except jsonschema.exceptions.ValidationError:
+ pass
+ except jsonschema.exceptions.SchemaError:
+ pass
+
+
+def main():
+ atheris.instrument_all()
+ atheris.Setup(
+ sys.argv,
+ test_schemas.hypothesis.fuzz_one_input,
+ enable_python_coverage=True,
+ )
+ atheris.Fuzz()
+
+
+if __name__ == "__main__":
+ import atheris
+ main()
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_cli.py b/runtime/Lib/site-packages/jsonschema/tests/test_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..9011a76189fde68513eba0d0447bf4c5d88d7304
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_cli.py
@@ -0,0 +1,918 @@
+from contextlib import redirect_stderr, redirect_stdout
+from io import StringIO
+from json import JSONDecodeError
+from pathlib import Path
+from textwrap import dedent
+from unittest import TestCase
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import warnings
+
+try: # pragma: no cover
+ from importlib import metadata
+except ImportError: # pragma: no cover
+ import importlib_metadata as metadata # type: ignore
+
+from pyrsistent import m
+
+from jsonschema import Draft4Validator, Draft202012Validator
+from jsonschema.exceptions import (
+ RefResolutionError,
+ SchemaError,
+ ValidationError,
+)
+from jsonschema.validators import _LATEST_VERSION, validate
+
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ from jsonschema import cli
+
+
+def fake_validator(*errors):
+ errors = list(reversed(errors))
+
+ class FakeValidator:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def iter_errors(self, instance):
+ if errors:
+ return errors.pop()
+ return [] # pragma: no cover
+
+ @classmethod
+ def check_schema(self, schema):
+ pass
+
+ return FakeValidator
+
+
+def fake_open(all_contents):
+ def open(path):
+ contents = all_contents.get(path)
+ if contents is None:
+ raise FileNotFoundError(path)
+ return StringIO(contents)
+ return open
+
+
+def _message_for(non_json):
+ try:
+ json.loads(non_json)
+ except JSONDecodeError as error:
+ return str(error)
+ else: # pragma: no cover
+ raise RuntimeError("Tried and failed to capture a JSON dump error.")
+
+
+class TestCLI(TestCase):
+ def run_cli(
+ self, argv, files=m(), stdin=StringIO(), exit_code=0, **override,
+ ):
+ arguments = cli.parse_args(argv)
+ arguments.update(override)
+
+ self.assertFalse(hasattr(cli, "open"))
+ cli.open = fake_open(files)
+ try:
+ stdout, stderr = StringIO(), StringIO()
+ actual_exit_code = cli.run(
+ arguments,
+ stdin=stdin,
+ stdout=stdout,
+ stderr=stderr,
+ )
+ finally:
+ del cli.open
+
+ self.assertEqual(
+ actual_exit_code, exit_code, msg=dedent(
+ """
+ Expected an exit code of {} != {}.
+
+ stdout: {}
+
+ stderr: {}
+ """.format(
+ exit_code,
+ actual_exit_code,
+ stdout.getvalue(),
+ stderr.getvalue(),
+ ),
+ ),
+ )
+ return stdout.getvalue(), stderr.getvalue()
+
+ def assertOutputs(self, stdout="", stderr="", **kwargs):
+ self.assertEqual(
+ self.run_cli(**kwargs),
+ (dedent(stdout), dedent(stderr)),
+ )
+
+ def test_invalid_instance(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="12: I am an error!\n",
+ )
+
+ def test_invalid_instance_pretty_output(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_instance)===
+
+ I am an error!
+ -----------------------------
+ """,
+ )
+
+ def test_invalid_instance_explicit_plain_output(self):
+ error = ValidationError("I am an error!", instance=12)
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(error.instance),
+ ),
+ validator=fake_validator([error]),
+
+ argv=["--output", "plain", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="12: I am an error!\n",
+ )
+
+ def test_invalid_instance_multiple_errors(self):
+ instance = 12
+ first = ValidationError("First error", instance=instance)
+ second = ValidationError("Second error", instance=instance)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(instance),
+ ),
+ validator=fake_validator([first, second]),
+
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: First error
+ 12: Second error
+ """,
+ )
+
+ def test_invalid_instance_multiple_errors_pretty_output(self):
+ instance = 12
+ first = ValidationError("First error", instance=instance)
+ second = ValidationError("Second error", instance=instance)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_instance=json.dumps(instance),
+ ),
+ validator=fake_validator([first, second]),
+
+ argv=["-i", "some_instance", "--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_instance)===
+
+ First error
+ -----------------------------
+ ===[ValidationError]===(some_instance)===
+
+ Second error
+ -----------------------------
+ """,
+ )
+
+ def test_multiple_invalid_instances(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ 12: An error
+ 12: Another error
+ foo: BOOM
+ """,
+ )
+
+ def test_multiple_invalid_instances_pretty_output(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "--output", "pretty",
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[ValidationError]===(some_first_instance)===
+
+ An error
+ -----------------------------
+ ===[ValidationError]===(some_first_instance)===
+
+ Another error
+ -----------------------------
+ ===[ValidationError]===(some_second_instance)===
+
+ BOOM
+ -----------------------------
+ """,
+ )
+
+ def test_custom_error_format(self):
+ first_instance = 12
+ first_errors = [
+ ValidationError("An error", instance=first_instance),
+ ValidationError("Another error", instance=first_instance),
+ ]
+ second_instance = "foo"
+ second_errors = [ValidationError("BOOM", instance=second_instance)]
+
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"does not": "matter since it is stubbed"}',
+ some_first_instance=json.dumps(first_instance),
+ some_second_instance=json.dumps(second_instance),
+ ),
+ validator=fake_validator(first_errors, second_errors),
+
+ argv=[
+ "--error-format", ":{error.message}._-_.{error.instance}:",
+ "-i", "some_first_instance",
+ "-i", "some_second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr=":An error._-_.12::Another error._-_.12::BOOM._-_.foo:",
+ )
+
+ def test_invalid_schema(self):
+ self.assertOutputs(
+ files=dict(some_schema='{"type": 12}'),
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: 12 is not valid under any of the given schemas
+ """,
+ )
+
+ def test_invalid_schema_pretty_output(self):
+ schema = {"type": 12}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance="")
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_schema_multiple_errors(self):
+ self.assertOutputs(
+ files=dict(some_schema='{"type": 12, "items": 57}'),
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 57: 57 is not of type 'object', 'boolean'
+ """,
+ )
+
+ def test_invalid_schema_multiple_errors_pretty_output(self):
+ schema = {"type": 12, "items": 57}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance="")
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_schema_with_invalid_instance(self):
+ """
+ "Validating" an instance that's invalid under an invalid schema
+ just shows the schema error.
+ """
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"type": 12, "minimum": 30}',
+ some_instance="13",
+ ),
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 12: 12 is not valid under any of the given schemas
+ """,
+ )
+
+ def test_invalid_schema_with_invalid_instance_pretty_output(self):
+ instance, schema = 13, {"type": 12, "minimum": 30}
+
+ with self.assertRaises(SchemaError) as e:
+ validate(schema=schema, instance=instance)
+ error = str(e.exception)
+
+ self.assertOutputs(
+ files=dict(
+ some_schema=json.dumps(schema),
+ some_instance=json.dumps(instance),
+ ),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr=(
+ "===[SchemaError]===(some_schema)===\n\n"
+ + str(error)
+ + "\n-----------------------------\n"
+ ),
+ )
+
+ def test_invalid_instance_continues_with_the_rest(self):
+ self.assertOutputs(
+ files=dict(
+ some_schema='{"minimum": 30}',
+ first_instance="not valid JSON!",
+ second_instance="12",
+ ),
+ argv=[
+ "-i", "first_instance",
+ "-i", "second_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse 'first_instance': {}
+ 12: 12 is less than the minimum of 30
+ """.format(_message_for("not valid JSON!")),
+ )
+
+ def test_custom_error_format_applies_to_schema_errors(self):
+ instance, schema = 13, {"type": 12, "minimum": 30}
+
+ with self.assertRaises(SchemaError):
+ validate(schema=schema, instance=instance)
+
+ self.assertOutputs(
+ files=dict(some_schema=json.dumps(schema)),
+
+ argv=[
+ "--error-format", ":{error.message}._-_.{error.instance}:",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr=":12 is not valid under any of the given schemas._-_.12:",
+ )
+
+ def test_instance_is_invalid_JSON(self):
+ instance = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse 'some_instance': {}
+ """.format(_message_for(instance)),
+ )
+
+ def test_instance_is_invalid_JSON_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(
+ some_schema="{}",
+ some_instance="not valid JSON!",
+ ),
+
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_instance)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_schema", stderr)
+
+ def test_instance_is_invalid_JSON_on_stdin(self):
+ instance = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO(instance),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse : {}
+ """.format(_message_for(instance)),
+ )
+
+ def test_instance_is_invalid_JSON_on_stdin_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("not valid JSON!"),
+
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "()===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_schema", stderr)
+
+ def test_schema_is_invalid_JSON(self):
+ schema = "not valid JSON!"
+
+ self.assertOutputs(
+ files=dict(some_schema=schema),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse 'some_schema': {}
+ """.format(_message_for(schema)),
+ )
+
+ def test_schema_is_invalid_JSON_pretty_output(self):
+ stdout, stderr = self.run_cli(
+ files=dict(some_schema="not valid JSON!"),
+
+ argv=["--output", "pretty", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_schema)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+
+ def test_schema_and_instance_are_both_invalid_JSON(self):
+ """
+ Only the schema error is reported, as we abort immediately.
+ """
+ schema, instance = "not valid JSON!", "also not valid JSON!"
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+
+ argv=["some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ Failed to parse 'some_schema': {}
+ """.format(_message_for(schema)),
+ )
+
+ def test_schema_and_instance_are_both_invalid_JSON_pretty_output(self):
+ """
+ Only the schema error is reported, as we abort immediately.
+ """
+ stdout, stderr = self.run_cli(
+ files=dict(
+ some_schema="not valid JSON!",
+ some_instance="also not valid JSON!",
+ ),
+
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+
+ exit_code=1,
+ )
+ self.assertFalse(stdout)
+ self.assertIn(
+ "(some_schema)===\n\nTraceback (most recent call last):\n",
+ stderr,
+ )
+ self.assertNotIn("some_instance", stderr)
+
+ def test_instance_does_not_exist(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ argv=["-i", "nonexisting_instance", "some_schema"],
+
+ exit_code=1,
+ stderr="""\
+ 'nonexisting_instance' does not exist.
+ """,
+ )
+
+ def test_instance_does_not_exist_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ argv=[
+ "--output", "pretty",
+ "-i", "nonexisting_instance",
+ "some_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_instance)===
+
+ 'nonexisting_instance' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_schema_does_not_exist(self):
+ self.assertOutputs(
+ argv=["nonexisting_schema"],
+
+ exit_code=1,
+ stderr="'nonexisting_schema' does not exist.\n",
+ )
+
+ def test_schema_does_not_exist_pretty_output(self):
+ self.assertOutputs(
+ argv=["--output", "pretty", "nonexisting_schema"],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_schema)===
+
+ 'nonexisting_schema' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_neither_instance_nor_schema_exist(self):
+ self.assertOutputs(
+ argv=["-i", "nonexisting_instance", "nonexisting_schema"],
+
+ exit_code=1,
+ stderr="'nonexisting_schema' does not exist.\n",
+ )
+
+ def test_neither_instance_nor_schema_exist_pretty_output(self):
+ self.assertOutputs(
+ argv=[
+ "--output", "pretty",
+ "-i", "nonexisting_instance",
+ "nonexisting_schema",
+ ],
+
+ exit_code=1,
+ stderr="""\
+ ===[FileNotFoundError]===(nonexisting_schema)===
+
+ 'nonexisting_schema' does not exist.
+ -----------------------------
+ """,
+ )
+
+ def test_successful_validation(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+ stdout="===[SUCCESS]===(some_instance)===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_of_stdin(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("{}"),
+ argv=["some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_of_stdin_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}"),
+ stdin=StringIO("{}"),
+ argv=["--output", "pretty", "some_schema"],
+ stdout="===[SUCCESS]===()===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_of_just_the_schema(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+ def test_successful_validation_of_just_the_schema_pretty_output(self):
+ self.assertOutputs(
+ files=dict(some_schema="{}", some_instance="{}"),
+ argv=["--output", "pretty", "-i", "some_instance", "some_schema"],
+ stdout="===[SUCCESS]===(some_instance)===\n",
+ stderr="",
+ )
+
+ def test_successful_validation_via_explicit_base_uri(self):
+ ref_schema_file = tempfile.NamedTemporaryFile(delete=False)
+ ref_schema_file.close()
+ self.addCleanup(os.remove, ref_schema_file.name)
+
+ ref_path = Path(ref_schema_file.name)
+ ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
+
+ schema = f'{{"$ref": "{ref_path.name}#definitions/num"}}'
+
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance="1"),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", ref_path.parent.as_uri() + "/",
+ "some_schema",
+ ],
+ stdout="",
+ stderr="",
+ )
+
+ def test_unsuccessful_validation_via_explicit_base_uri(self):
+ ref_schema_file = tempfile.NamedTemporaryFile(delete=False)
+ ref_schema_file.close()
+ self.addCleanup(os.remove, ref_schema_file.name)
+
+ ref_path = Path(ref_schema_file.name)
+ ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}')
+
+ schema = f'{{"$ref": "{ref_path.name}#definitions/num"}}'
+
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance='"1"'),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", ref_path.parent.as_uri() + "/",
+ "some_schema",
+ ],
+ exit_code=1,
+ stdout="",
+ stderr="1: '1' is not of type 'integer'\n",
+ )
+
+ def test_nonexistent_file_with_explicit_base_uri(self):
+ schema = '{"$ref": "someNonexistentFile.json#definitions/num"}'
+ instance = "1"
+
+ with self.assertRaises(RefResolutionError) as e:
+ self.assertOutputs(
+ files=dict(
+ some_schema=schema,
+ some_instance=instance,
+ ),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", Path.cwd().as_uri(),
+ "some_schema",
+ ],
+ )
+ error = str(e.exception)
+ self.assertIn(f"{os.sep}someNonexistentFile.json'", error)
+
+ def test_invalid_exlicit_base_uri(self):
+ schema = '{"$ref": "foo.json#definitions/num"}'
+ instance = "1"
+
+ with self.assertRaises(RefResolutionError) as e:
+ self.assertOutputs(
+ files=dict(
+ some_schema=schema,
+ some_instance=instance,
+ ),
+ argv=[
+ "-i", "some_instance",
+ "--base-uri", "not@UR1",
+ "some_schema",
+ ],
+ )
+ error = str(e.exception)
+ self.assertEqual(
+ error, "unknown url type: 'foo.json'",
+ )
+
+ def test_it_validates_using_the_latest_validator_when_unspecified(self):
+ # There isn't a better way now I can think of to ensure that the
+ # latest version was used, given that the call to validator_for
+ # is hidden inside the CLI, so guard that that's the case, and
+ # this test will have to be updated when versions change until
+ # we can think of a better way to ensure this behavior.
+ self.assertIs(Draft202012Validator, _LATEST_VERSION)
+
+ self.assertOutputs(
+ files=dict(some_schema='{"const": "check"}', some_instance='"a"'),
+ argv=["-i", "some_instance", "some_schema"],
+ exit_code=1,
+ stdout="",
+ stderr="a: 'check' was expected\n",
+ )
+
+ def test_it_validates_using_draft7_when_specified(self):
+ """
+ Specifically, `const` validation applies for Draft 7.
+ """
+ schema = """
+ {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "const": "check"
+ }
+ """
+ instance = '"foo"'
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+ exit_code=1,
+ stdout="",
+ stderr="foo: 'check' was expected\n",
+ )
+
+ def test_it_validates_using_draft4_when_specified(self):
+ """
+ Specifically, `const` validation *does not* apply for Draft 4.
+ """
+ schema = """
+ {
+ "$schema": "http://json-schema.org/draft-04/schema#",
+ "const": "check"
+ }
+ """
+ instance = '"foo"'
+ self.assertOutputs(
+ files=dict(some_schema=schema, some_instance=instance),
+ argv=["-i", "some_instance", "some_schema"],
+ stdout="",
+ stderr="",
+ )
+
+
+class TestParser(TestCase):
+
+ FakeValidator = fake_validator()
+
+ def test_find_validator_by_fully_qualified_object_name(self):
+ arguments = cli.parse_args(
+ [
+ "--validator",
+ "jsonschema.tests.test_cli.TestParser.FakeValidator",
+ "--instance", "mem://some/instance",
+ "mem://some/schema",
+ ],
+ )
+ self.assertIs(arguments["validator"], self.FakeValidator)
+
+ def test_find_validator_in_jsonschema(self):
+ arguments = cli.parse_args(
+ [
+ "--validator", "Draft4Validator",
+ "--instance", "mem://some/instance",
+ "mem://some/schema",
+ ],
+ )
+ self.assertIs(arguments["validator"], Draft4Validator)
+
+ def cli_output_for(self, *argv):
+ stdout, stderr = StringIO(), StringIO()
+ with redirect_stdout(stdout), redirect_stderr(stderr):
+ with self.assertRaises(SystemExit):
+ cli.parse_args(argv)
+ return stdout.getvalue(), stderr.getvalue()
+
+ def test_unknown_output(self):
+ stdout, stderr = self.cli_output_for(
+ "--output", "foo",
+ "mem://some/schema",
+ )
+ self.assertIn("invalid choice: 'foo'", stderr)
+ self.assertFalse(stdout)
+
+ def test_useless_error_format(self):
+ stdout, stderr = self.cli_output_for(
+ "--output", "pretty",
+ "--error-format", "foo",
+ "mem://some/schema",
+ )
+ self.assertIn(
+ "--error-format can only be used with --output plain",
+ stderr,
+ )
+ self.assertFalse(stdout)
+
+
+class TestCLIIntegration(TestCase):
+ def test_license(self):
+ output = subprocess.check_output(
+ [sys.executable, "-m", "pip", "show", "jsonschema"],
+ stderr=subprocess.STDOUT,
+ )
+ self.assertIn(b"License: MIT", output)
+
+ def test_version(self):
+ version = subprocess.check_output(
+ [sys.executable, "-W", "ignore", "-m", "jsonschema", "--version"],
+ stderr=subprocess.STDOUT,
+ )
+ version = version.decode("utf-8").strip()
+ self.assertEqual(version, metadata.version("jsonschema"))
+
+ def test_no_arguments_shows_usage_notes(self):
+ output = subprocess.check_output(
+ [sys.executable, "-m", "jsonschema"],
+ stderr=subprocess.STDOUT,
+ )
+ output_for_help = subprocess.check_output(
+ [sys.executable, "-m", "jsonschema", "--help"],
+ stderr=subprocess.STDOUT,
+ )
+ self.assertEqual(output, output_for_help)
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_deprecations.py b/runtime/Lib/site-packages/jsonschema/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e8a9cc47c12669a7640747c35b09cbb09c1c07d
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_deprecations.py
@@ -0,0 +1,293 @@
+from unittest import TestCase
+import importlib
+import subprocess
+import sys
+
+from jsonschema import FormatChecker, validators
+
+
+class TestDeprecations(TestCase):
+ def test_version(self):
+ """
+ As of v4.0.0, __version__ is deprecated in favor of importlib.metadata.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import __version__ # noqa
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.__version__ is deprecated",
+ ),
+ )
+
+ def test_validators_ErrorTree(self):
+ """
+ As of v4.0.0, importing ErrorTree from jsonschema.validators is
+ deprecated in favor of doing so from jsonschema.exceptions.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema.validators import ErrorTree # noqa
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Importing ErrorTree from jsonschema.validators is deprecated",
+ ),
+ )
+
+ def test_validators_validators(self):
+ """
+ As of v4.0.0, accessing jsonschema.validators.validators is
+ deprecated.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ value = validators.validators
+ self.assertEqual(value, validators._VALIDATORS)
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.validators.validators is deprecated",
+ ),
+ )
+
+ def test_validators_meta_schemas(self):
+ """
+ As of v4.0.0, accessing jsonschema.validators.meta_schemas is
+ deprecated.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ value = validators.meta_schemas
+ self.assertEqual(value, validators._META_SCHEMAS)
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.validators.meta_schemas is deprecated",
+ ),
+ )
+
+ def test_RefResolver_in_scope(self):
+ """
+ As of v4.0.0, RefResolver.in_scope is deprecated.
+ """
+
+ resolver = validators.RefResolver.from_schema({})
+ with self.assertWarns(DeprecationWarning) as w:
+ with resolver.in_scope("foo"):
+ pass
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "jsonschema.RefResolver.in_scope is deprecated ",
+ ),
+ )
+
+ def test_Validator_is_valid_two_arguments(self):
+ """
+ As of v4.0.0, calling is_valid with two arguments (to provide a
+ different schema) is deprecated.
+ """
+
+ validator = validators.Draft7Validator({})
+ with self.assertWarns(DeprecationWarning) as w:
+ result = validator.is_valid("foo", {"type": "number"})
+
+ self.assertFalse(result)
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Passing a schema to Validator.is_valid is deprecated ",
+ ),
+ )
+
+ def test_Validator_iter_errors_two_arguments(self):
+ """
+ As of v4.0.0, calling iter_errors with two arguments (to provide a
+ different schema) is deprecated.
+ """
+
+ validator = validators.Draft7Validator({})
+ with self.assertWarns(DeprecationWarning) as w:
+ error, = validator.iter_errors("foo", {"type": "number"})
+
+ self.assertEqual(error.validator, "type")
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Passing a schema to Validator.iter_errors is deprecated ",
+ ),
+ )
+
+ def test_Validator_subclassing(self):
+ """
+ As of v4.12.0, subclassing a validator class produces an explicit
+ deprecation warning.
+
+ This was never intended to be public API (and some comments over the
+ years in issues said so, but obviously that's not a great way to make
+ sure it's followed).
+
+ A future version will explicitly raise an error.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ class Subclass(validators.Draft202012Validator):
+ pass
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith("Subclassing validator classes is "),
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ class AnotherSubclass(validators.create(meta_schema={})):
+ pass
+
+ def test_FormatChecker_cls_checks(self):
+ """
+ As of v4.14.0, FormatChecker.cls_checks is deprecated without
+ replacement.
+ """
+
+ self.addCleanup(FormatChecker.checkers.pop, "boom", None)
+
+ with self.assertWarns(DeprecationWarning) as w:
+ FormatChecker.cls_checks("boom")
+
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith("FormatChecker.cls_checks "),
+ )
+
+ def test_draftN_format_checker(self):
+ """
+ As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated
+ in favor of Validator.FORMAT_CHECKER.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft202012_format_checker # noqa
+
+ self.assertIs(
+ draft202012_format_checker,
+ validators.Draft202012Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft202012_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft201909_format_checker # noqa
+
+ self.assertIs(
+ draft201909_format_checker,
+ validators.Draft201909Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft201909_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft7_format_checker # noqa
+
+ self.assertIs(
+ draft7_format_checker,
+ validators.Draft7Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft7_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft6_format_checker # noqa
+
+ self.assertIs(
+ draft6_format_checker,
+ validators.Draft6Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft6_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft4_format_checker # noqa
+
+ self.assertIs(
+ draft4_format_checker,
+ validators.Draft4Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft4_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertWarns(DeprecationWarning) as w:
+ from jsonschema import draft3_format_checker # noqa
+
+ self.assertIs(
+ draft3_format_checker,
+ validators.Draft3Validator.FORMAT_CHECKER,
+ )
+ self.assertEqual(w.filename, __file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "Accessing jsonschema.draft3_format_checker is ",
+ ),
+ msg=w.warning,
+ )
+
+ with self.assertRaises(ImportError):
+ from jsonschema import draft1234_format_checker # noqa
+
+ def test_import_cli(self):
+ """
+ As of v4.17.0, importing jsonschema.cli is deprecated.
+ """
+
+ with self.assertWarns(DeprecationWarning) as w:
+ import jsonschema.cli
+ importlib.reload(jsonschema.cli)
+
+ self.assertEqual(w.filename, importlib.__file__)
+ self.assertTrue(
+ str(w.warning).startswith(
+ "The jsonschema CLI is deprecated and will be removed ",
+ ),
+ )
+
+ def test_cli(self):
+ """
+ As of v4.17.0, the jsonschema CLI is deprecated.
+ """
+
+ process = subprocess.run(
+ [sys.executable, "-m", "jsonschema"],
+ capture_output=True,
+ )
+ self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr)
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_exceptions.py b/runtime/Lib/site-packages/jsonschema/tests/test_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ff3009173c3abd8912366ae74645d2db5b233e
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_exceptions.py
@@ -0,0 +1,601 @@
+from unittest import TestCase
+import textwrap
+
+from jsonschema import exceptions
+from jsonschema.validators import _LATEST_VERSION
+
+
+class TestBestMatch(TestCase):
+ def best_match_of(self, instance, schema):
+ errors = list(_LATEST_VERSION(schema).iter_errors(instance))
+ best = exceptions.best_match(iter(errors))
+ reversed_best = exceptions.best_match(reversed(errors))
+ self.assertEqual(
+ best._contents(),
+ reversed_best._contents(),
+ f"No consistent best match!\nGot: {best}\n\nThen: {reversed_best}",
+ )
+ return best
+
+ def test_shallower_errors_are_better_matches(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "minProperties": 2,
+ "properties": {"bar": {"type": "object"}},
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": []}}, schema=schema)
+ self.assertEqual(best.validator, "minProperties")
+
+ def test_oneOf_and_anyOf_are_weak_matches(self):
+ """
+ A property you *must* match is probably better than one you have to
+ match a part of.
+ """
+
+ schema = {
+ "minProperties": 2,
+ "anyOf": [{"type": "string"}, {"type": "number"}],
+ "oneOf": [{"type": "string"}, {"type": "number"}],
+ }
+ best = self.best_match_of(instance={}, schema=schema)
+ self.assertEqual(best.validator, "minProperties")
+
+ def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
+ """
+ If the most relevant error is an anyOf, then we traverse its context
+ and select the otherwise *least* relevant error, since in this case
+ that means the most specific, deep, error inside the instance.
+
+ I.e. since only one of the schemas must match, we look for the most
+ relevant one.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_no_anyOf_traversal_for_equally_relevant_errors(self):
+ """
+ We don't traverse into an anyOf (as above) if all of its context errors
+ seem to be equally "wrong" against the instance.
+ """
+
+ schema = {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "integer"},
+ {"type": "object"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "anyOf")
+
+ def test_anyOf_traversal_for_single_equally_relevant_error(self):
+ """
+ We *do* traverse anyOf with a single nested error, even though it is
+ vacuously equally relevant to itself.
+ """
+
+ schema = {
+ "anyOf": [
+ {"type": "string"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "type")
+
+ def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
+ """
+ If the most relevant error is an oneOf, then we traverse its context
+ and select the otherwise *least* relevant error, since in this case
+ that means the most specific, deep, error inside the instance.
+
+ I.e. since only one of the schemas must match, we look for the most
+ relevant one.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "oneOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_no_oneOf_traversal_for_equally_relevant_errors(self):
+ """
+ We don't traverse into an oneOf (as above) if all of its context errors
+ seem to be equally "wrong" against the instance.
+ """
+
+ schema = {
+ "oneOf": [
+ {"type": "string"},
+ {"type": "integer"},
+ {"type": "object"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "oneOf")
+
+ def test_oneOf_traversal_for_single_equally_relevant_error(self):
+ """
+ We *do* traverse oneOf with a single nested error, even though it is
+ vacuously equally relevant to itself.
+ """
+
+ schema = {
+ "oneOf": [
+ {"type": "string"},
+ ],
+ }
+ best = self.best_match_of(instance=[], schema=schema)
+ self.assertEqual(best.validator, "type")
+
+ def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
+ """
+ Now, if the error is allOf, we traverse but select the *most* relevant
+ error from the context, because all schemas here must match anyways.
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "allOf": [
+ {"type": "string"},
+ {"properties": {"bar": {"type": "array"}}},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "string")
+
+ def test_nested_context_for_oneOf(self):
+ """
+ We traverse into nested contexts (a oneOf containing an error in a
+ nested oneOf here).
+ """
+
+ schema = {
+ "properties": {
+ "foo": {
+ "oneOf": [
+ {"type": "string"},
+ {
+ "oneOf": [
+ {"type": "string"},
+ {
+ "properties": {
+ "bar": {"type": "array"},
+ },
+ },
+ ],
+ },
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema)
+ self.assertEqual(best.validator_value, "array")
+
+ def test_it_prioritizes_matching_types(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "array", "minItems": 2},
+ {"type": "string", "minLength": 10},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertEqual(best.validator, "minLength")
+
+ reordered = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string", "minLength": 10},
+ {"type": "array", "minItems": 2},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
+ self.assertEqual(best.validator, "minLength")
+
+ def test_it_prioritizes_matching_union_types(self):
+ schema = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": ["array", "object"], "minItems": 2},
+ {"type": ["integer", "string"], "minLength": 10},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertEqual(best.validator, "minLength")
+
+ reordered = {
+ "properties": {
+ "foo": {
+ "anyOf": [
+ {"type": "string", "minLength": 10},
+ {"type": "array", "minItems": 2},
+ ],
+ },
+ },
+ }
+ best = self.best_match_of(instance={"foo": "bar"}, schema=reordered)
+ self.assertEqual(best.validator, "minLength")
+
+ def test_boolean_schemas(self):
+ schema = {"properties": {"foo": False}}
+ best = self.best_match_of(instance={"foo": "bar"}, schema=schema)
+ self.assertIsNone(best.validator)
+
+ def test_one_error(self):
+ validator = _LATEST_VERSION({"minProperties": 2})
+ error, = validator.iter_errors({})
+ self.assertEqual(
+ exceptions.best_match(validator.iter_errors({})).validator,
+ "minProperties",
+ )
+
+ def test_no_errors(self):
+ validator = _LATEST_VERSION({})
+ self.assertIsNone(exceptions.best_match(validator.iter_errors({})))
+
+
+class TestByRelevance(TestCase):
+ def test_short_paths_are_better_matches(self):
+ shallow = exceptions.ValidationError("Oh no!", path=["baz"])
+ deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"])
+ match = max([shallow, deep], key=exceptions.relevance)
+ self.assertIs(match, shallow)
+
+ match = max([deep, shallow], key=exceptions.relevance)
+ self.assertIs(match, shallow)
+
+ def test_global_errors_are_even_better_matches(self):
+ shallow = exceptions.ValidationError("Oh no!", path=[])
+ deep = exceptions.ValidationError("Oh yes!", path=["foo"])
+
+ errors = sorted([shallow, deep], key=exceptions.relevance)
+ self.assertEqual(
+ [list(error.path) for error in errors],
+ [["foo"], []],
+ )
+
+ errors = sorted([deep, shallow], key=exceptions.relevance)
+ self.assertEqual(
+ [list(error.path) for error in errors],
+ [["foo"], []],
+ )
+
+ def test_weak_keywords_are_lower_priority(self):
+ weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
+ normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
+
+ best_match = exceptions.by_relevance(weak="a")
+
+ match = max([weak, normal], key=best_match)
+ self.assertIs(match, normal)
+
+ match = max([normal, weak], key=best_match)
+ self.assertIs(match, normal)
+
+ def test_strong_keywords_are_higher_priority(self):
+ weak = exceptions.ValidationError("Oh no!", path=[], validator="a")
+ normal = exceptions.ValidationError("Oh yes!", path=[], validator="b")
+ strong = exceptions.ValidationError("Oh fine!", path=[], validator="c")
+
+ best_match = exceptions.by_relevance(weak="a", strong="c")
+
+ match = max([weak, normal, strong], key=best_match)
+ self.assertIs(match, strong)
+
+ match = max([strong, normal, weak], key=best_match)
+ self.assertIs(match, strong)
+
+
+class TestErrorTree(TestCase):
+ def test_it_knows_how_many_total_errors_it_contains(self):
+ # FIXME: #442
+ errors = [
+ exceptions.ValidationError("Something", validator=i)
+ for i in range(8)
+ ]
+ tree = exceptions.ErrorTree(errors)
+ self.assertEqual(tree.total_errors, 8)
+
+ def test_it_contains_an_item_if_the_item_had_an_error(self):
+ errors = [exceptions.ValidationError("a message", path=["bar"])]
+ tree = exceptions.ErrorTree(errors)
+ self.assertIn("bar", tree)
+
+ def test_it_does_not_contain_an_item_if_the_item_had_no_error(self):
+ errors = [exceptions.ValidationError("a message", path=["bar"])]
+ tree = exceptions.ErrorTree(errors)
+ self.assertNotIn("foo", tree)
+
+ def test_keywords_that_failed_appear_in_errors_dict(self):
+ error = exceptions.ValidationError("a message", validator="foo")
+ tree = exceptions.ErrorTree([error])
+ self.assertEqual(tree.errors, {"foo": error})
+
+ def test_it_creates_a_child_tree_for_each_nested_path(self):
+ errors = [
+ exceptions.ValidationError("a bar message", path=["bar"]),
+ exceptions.ValidationError("a bar -> 0 message", path=["bar", 0]),
+ ]
+ tree = exceptions.ErrorTree(errors)
+ self.assertIn(0, tree["bar"])
+ self.assertNotIn(1, tree["bar"])
+
+ def test_children_have_their_errors_dicts_built(self):
+ e1, e2 = (
+ exceptions.ValidationError("1", validator="foo", path=["bar", 0]),
+ exceptions.ValidationError("2", validator="quux", path=["bar", 0]),
+ )
+ tree = exceptions.ErrorTree([e1, e2])
+ self.assertEqual(tree["bar"][0].errors, {"foo": e1, "quux": e2})
+
+ def test_multiple_errors_with_instance(self):
+ e1, e2 = (
+ exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1"),
+ exceptions.ValidationError(
+ "2",
+ validator="quux",
+ path=["foobar", 2],
+ instance="i2"),
+ )
+ exceptions.ErrorTree([e1, e2])
+
+ def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self):
+ error = exceptions.ValidationError("123", validator="foo", instance=[])
+ tree = exceptions.ErrorTree([error])
+
+ with self.assertRaises(IndexError):
+ tree[0]
+
+ def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self):
+ """
+ If a keyword refers to a path that isn't in the instance, the
+ tree still properly returns a subtree for that path.
+ """
+
+ error = exceptions.ValidationError(
+ "a message", validator="foo", instance={}, path=["foo"],
+ )
+ tree = exceptions.ErrorTree([error])
+ self.assertIsInstance(tree["foo"], exceptions.ErrorTree)
+
+ def test_repr_single(self):
+ error = exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1",
+ )
+ tree = exceptions.ErrorTree([error])
+ self.assertEqual(repr(tree), "")
+
+ def test_repr_multiple(self):
+ e1, e2 = (
+ exceptions.ValidationError(
+ "1",
+ validator="foo",
+ path=["bar", "bar2"],
+ instance="i1"),
+ exceptions.ValidationError(
+ "2",
+ validator="quux",
+ path=["foobar", 2],
+ instance="i2"),
+ )
+ tree = exceptions.ErrorTree([e1, e2])
+ self.assertEqual(repr(tree), "")
+
+ def test_repr_empty(self):
+ tree = exceptions.ErrorTree([])
+ self.assertEqual(repr(tree), "")
+
+
+class TestErrorInitReprStr(TestCase):
+ def make_error(self, **kwargs):
+ defaults = dict(
+ message="hello",
+ validator="type",
+ validator_value="string",
+ instance=5,
+ schema={"type": "string"},
+ )
+ defaults.update(kwargs)
+ return exceptions.ValidationError(**defaults)
+
+ def assertShows(self, expected, **kwargs):
+ expected = textwrap.dedent(expected).rstrip("\n")
+
+ error = self.make_error(**kwargs)
+ message_line, _, rest = str(error).partition("\n")
+ self.assertEqual(message_line, error.message)
+ self.assertEqual(rest, expected)
+
+ def test_it_calls_super_and_sets_args(self):
+ error = self.make_error()
+ self.assertGreater(len(error.args), 1)
+
+ def test_repr(self):
+ self.assertEqual(
+ repr(exceptions.ValidationError(message="Hello!")),
+ "",
+ )
+
+ def test_unset_error(self):
+ error = exceptions.ValidationError("message")
+ self.assertEqual(str(error), "message")
+
+ kwargs = {
+ "validator": "type",
+ "validator_value": "string",
+ "instance": 5,
+ "schema": {"type": "string"},
+ }
+ # Just the message should show if any of the attributes are unset
+ for attr in kwargs:
+ k = dict(kwargs)
+ del k[attr]
+ error = exceptions.ValidationError("message", **k)
+ self.assertEqual(str(error), "message")
+
+ def test_empty_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema:
+ {'type': 'string'}
+
+ On instance:
+ 5
+ """,
+ path=[],
+ schema_path=[],
+ )
+
+ def test_one_item_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema:
+ {'type': 'string'}
+
+ On instance[0]:
+ 5
+ """,
+ path=[0],
+ schema_path=["items"],
+ )
+
+ def test_multiple_item_paths(self):
+ self.assertShows(
+ """
+ Failed validating 'type' in schema['items'][0]:
+ {'type': 'string'}
+
+ On instance[0]['a']:
+ 5
+ """,
+ path=[0, "a"],
+ schema_path=["items", 0, 1],
+ )
+
+ def test_uses_pprint(self):
+ self.assertShows(
+ """
+ Failed validating 'maxLength' in schema:
+ {0: 0,
+ 1: 1,
+ 2: 2,
+ 3: 3,
+ 4: 4,
+ 5: 5,
+ 6: 6,
+ 7: 7,
+ 8: 8,
+ 9: 9,
+ 10: 10,
+ 11: 11,
+ 12: 12,
+ 13: 13,
+ 14: 14,
+ 15: 15,
+ 16: 16,
+ 17: 17,
+ 18: 18,
+ 19: 19}
+
+ On instance:
+ [0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8,
+ 9,
+ 10,
+ 11,
+ 12,
+ 13,
+ 14,
+ 15,
+ 16,
+ 17,
+ 18,
+ 19,
+ 20,
+ 21,
+ 22,
+ 23,
+ 24]
+ """,
+ instance=list(range(25)),
+ schema=dict(zip(range(20), range(20))),
+ validator="maxLength",
+ )
+
+ def test_str_works_with_instances_having_overriden_eq_operator(self):
+ """
+ Check for #164 which rendered exceptions unusable when a
+ `ValidationError` involved instances with an `__eq__` method
+ that returned truthy values.
+ """
+
+ class DontEQMeBro:
+ def __eq__(this, other): # pragma: no cover
+ self.fail("Don't!")
+
+ def __ne__(this, other): # pragma: no cover
+ self.fail("Don't!")
+
+ instance = DontEQMeBro()
+ error = exceptions.ValidationError(
+ "a message",
+ validator="foo",
+ instance=instance,
+ validator_value="some",
+ schema="schema",
+ )
+ self.assertIn(repr(instance), str(error))
+
+
+class TestHashable(TestCase):
+ def test_hashable(self):
+ set([exceptions.ValidationError("")])
+ set([exceptions.SchemaError("")])
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_format.py b/runtime/Lib/site-packages/jsonschema/tests/test_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dd06cfaf95759765113f79d405a9f34ce52161a
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_format.py
@@ -0,0 +1,108 @@
+"""
+Tests for the parts of jsonschema related to the :kw:`format` keyword.
+"""
+
+from unittest import TestCase
+
+from jsonschema import FormatChecker, FormatError, ValidationError
+from jsonschema.validators import Draft4Validator
+
+BOOM = ValueError("Boom!")
+BANG = ZeroDivisionError("Bang!")
+
+
+def boom(thing):
+ if thing == "bang":
+ raise BANG
+ raise BOOM
+
+
+class TestFormatChecker(TestCase):
+ def test_it_can_validate_no_formats(self):
+ checker = FormatChecker(formats=())
+ self.assertFalse(checker.checkers)
+
+ def test_it_raises_a_key_error_for_unknown_formats(self):
+ with self.assertRaises(KeyError):
+ FormatChecker(formats=["o noes"])
+
+ def test_it_can_register_cls_checkers(self):
+ original = dict(FormatChecker.checkers)
+ self.addCleanup(FormatChecker.checkers.pop, "boom")
+ with self.assertWarns(DeprecationWarning):
+ FormatChecker.cls_checks("boom")(boom)
+ self.assertEqual(
+ FormatChecker.checkers,
+ dict(original, boom=(boom, ())),
+ )
+
+ def test_it_can_register_checkers(self):
+ checker = FormatChecker()
+ checker.checks("boom")(boom)
+ self.assertEqual(
+ checker.checkers,
+ dict(FormatChecker.checkers, boom=(boom, ())),
+ )
+
+ def test_it_catches_registered_errors(self):
+ checker = FormatChecker()
+ checker.checks("boom", raises=type(BOOM))(boom)
+
+ with self.assertRaises(FormatError) as cm:
+ checker.check(instance=12, format="boom")
+
+ self.assertIs(cm.exception.cause, BOOM)
+ self.assertIs(cm.exception.__cause__, BOOM)
+
+ # Unregistered errors should not be caught
+ with self.assertRaises(type(BANG)):
+ checker.check(instance="bang", format="boom")
+
+ def test_format_error_causes_become_validation_error_causes(self):
+ checker = FormatChecker()
+ checker.checks("boom", raises=ValueError)(boom)
+ validator = Draft4Validator({"format": "boom"}, format_checker=checker)
+
+ with self.assertRaises(ValidationError) as cm:
+ validator.validate("BOOM")
+
+ self.assertIs(cm.exception.cause, BOOM)
+ self.assertIs(cm.exception.__cause__, BOOM)
+
+ def test_format_checkers_come_with_defaults(self):
+ # This is bad :/ but relied upon.
+ # The docs for quite awhile recommended people do things like
+ # validate(..., format_checker=FormatChecker())
+ # We should change that, but we can't without deprecation...
+ checker = FormatChecker()
+ with self.assertRaises(FormatError):
+ checker.check(instance="not-an-ipv4", format="ipv4")
+
+ def test_repr(self):
+ checker = FormatChecker(formats=())
+ checker.checks("foo")(lambda thing: True) # pragma: no cover
+ checker.checks("bar")(lambda thing: True) # pragma: no cover
+ checker.checks("baz")(lambda thing: True) # pragma: no cover
+ self.assertEqual(
+ repr(checker),
+ "",
+ )
+
+ def test_duration_format(self):
+ try:
+ from jsonschema._format import is_duration # noqa: F401
+ except ImportError: # pragma: no cover
+ pass
+ else:
+ checker = FormatChecker()
+ self.assertTrue(checker.conforms(1, "duration"))
+ self.assertTrue(checker.conforms("P4Y", "duration"))
+ self.assertFalse(checker.conforms("test", "duration"))
+
+ def test_uuid_format(self):
+ checker = FormatChecker()
+ self.assertTrue(checker.conforms(1, "uuid"))
+ self.assertTrue(
+ checker.conforms("6e6659ec-4503-4428-9f03-2e2ea4d6c278", "uuid"),
+ )
+ self.assertFalse(checker.conforms("test", "uuid"))
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_jsonschema_test_suite.py b/runtime/Lib/site-packages/jsonschema/tests/test_jsonschema_test_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..42337ed488e71f8b886ec51b5d7cfbfc6ac52111
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_jsonschema_test_suite.py
@@ -0,0 +1,546 @@
+"""
+Test runner for the JSON Schema official test suite
+
+Tests comprehensive correctness of each draft's validator.
+
+See https://github.com/json-schema-org/JSON-Schema-Test-Suite for details.
+"""
+
+import sys
+
+from jsonschema.tests._helpers import bug
+from jsonschema.tests._suite import Suite
+import jsonschema
+
+SUITE = Suite()
+DRAFT3 = SUITE.version(name="draft3")
+DRAFT4 = SUITE.version(name="draft4")
+DRAFT6 = SUITE.version(name="draft6")
+DRAFT7 = SUITE.version(name="draft7")
+DRAFT201909 = SUITE.version(name="draft2019-09")
+DRAFT202012 = SUITE.version(name="draft2020-12")
+
+
+def skip(message, **kwargs):
+ def skipper(test):
+ if all(value == getattr(test, attr) for attr, value in kwargs.items()):
+ return message
+ return skipper
+
+
+def missing_format(Validator):
+ def missing_format(test): # pragma: no cover
+ schema = test.schema
+ if (
+ schema is True
+ or schema is False
+ or "format" not in schema
+ or schema["format"] in Validator.FORMAT_CHECKER.checkers
+ or test.valid
+ ):
+ return
+
+ return "Format checker {0!r} not found.".format(schema["format"])
+ return missing_format
+
+
+def complex_email_validation(test):
+ if test.subject != "email":
+ return
+
+ message = "Complex email validation is (intentionally) unsupported."
+ return skip(
+ message=message,
+ description="an invalid domain",
+ )(test) or skip(
+ message=message,
+ description="an invalid IPv4-address-literal",
+ )(test) or skip(
+ message=message,
+ description="dot after local part is not valid",
+ )(test) or skip(
+ message=message,
+ description="dot before local part is not valid",
+ )(test) or skip(
+ message=message,
+ description="two subsequent dots inside local part are not valid",
+ )(test)
+
+
+is_narrow_build = sys.maxunicode == 2 ** 16 - 1
+if is_narrow_build: # pragma: no cover
+ message = "Not running surrogate Unicode case, this Python is narrow."
+
+ def narrow_unicode_build(test): # pragma: no cover
+ return skip(
+ message=message,
+ description=(
+ "one supplementary Unicode code point is not long enough"
+ ),
+ )(test) or skip(
+ message=message,
+ description="two supplementary Unicode code points is long enough",
+ )(test)
+else:
+ def narrow_unicode_build(test): # pragma: no cover
+ return
+
+
+if sys.version_info < (3, 9): # pragma: no cover
+ message = "Rejecting leading zeros is 3.9+"
+ allowed_leading_zeros = skip(
+ message=message,
+ subject="ipv4",
+ description="invalid leading zeroes, as they are treated as octals",
+ )
+else:
+ def allowed_leading_zeros(test): # pragma: no cover
+ return
+
+
+def leap_second(test):
+ message = "Leap seconds are unsupported."
+ return skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second, Zulu",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="a valid time string with leap second with offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, positive time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, negative time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, large positive time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, large negative time-offset",
+ )(test) or skip(
+ message=message,
+ subject="time",
+ description="valid leap second, zero time-offset",
+ )(test) or skip(
+ message=message,
+ subject="date-time",
+ description="a valid date-time with a leap second, UTC",
+ )(test) or skip(
+ message=message,
+ subject="date-time",
+ description="a valid date-time with a leap second, with minus offset",
+ )(test)
+
+
+TestDraft3 = DRAFT3.to_unittest_testcase(
+ DRAFT3.tests(),
+ DRAFT3.format_tests(),
+ DRAFT3.optional_tests_of(name="bignum"),
+ DRAFT3.optional_tests_of(name="non-bmp-regex"),
+ DRAFT3.optional_tests_of(name="zeroTerminatedFloats"),
+ Validator=jsonschema.Draft3Validator,
+ format_checker=jsonschema.Draft3Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ narrow_unicode_build(test)
+ or missing_format(jsonschema.Draft3Validator)(test)
+ or complex_email_validation(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ valid=False,
+ case_description=(
+ "$ref prevents a sibling id from changing the base uri"
+ ),
+ )(test)
+ ),
+)
+
+
+TestDraft4 = DRAFT4.to_unittest_testcase(
+ DRAFT4.tests(),
+ DRAFT4.format_tests(),
+ DRAFT4.optional_tests_of(name="bignum"),
+ DRAFT4.optional_tests_of(name="float-overflow"),
+ DRAFT4.optional_tests_of(name="non-bmp-regex"),
+ DRAFT4.optional_tests_of(name="zeroTerminatedFloats"),
+ Validator=jsonschema.Draft4Validator,
+ format_checker=jsonschema.Draft4Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ narrow_unicode_build(test)
+ or allowed_leading_zeros(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft4Validator)(test)
+ or complex_email_validation(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description="Recursive references between schemas",
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "Location-independent identifier with "
+ "base URI change in subschema"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "$ref prevents a sibling id from changing the base uri"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="id",
+ description="match $ref to id",
+ )(test)
+ or skip(
+ message=bug(),
+ subject="id",
+ description="no match on enum or $ref to id",
+ )(test)
+ or skip(
+ message=bug(),
+ subject="refRemote",
+ case_description="base URI change - change folder in subschema",
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "id must be resolved against nearest parent, "
+ "not just immediate parent"
+ ),
+ )(test)
+ ),
+)
+
+
+TestDraft6 = DRAFT6.to_unittest_testcase(
+ DRAFT6.tests(),
+ DRAFT6.format_tests(),
+ DRAFT6.optional_tests_of(name="bignum"),
+ DRAFT6.optional_tests_of(name="float-overflow"),
+ DRAFT6.optional_tests_of(name="non-bmp-regex"),
+ Validator=jsonschema.Draft6Validator,
+ format_checker=jsonschema.Draft6Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ narrow_unicode_build(test)
+ or allowed_leading_zeros(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft6Validator)(test)
+ or complex_email_validation(test)
+ or skip(
+ message=bug(),
+ subject="refRemote",
+ case_description="base URI change - change folder in subschema",
+ )(test)
+ ),
+)
+
+
+TestDraft7 = DRAFT7.to_unittest_testcase(
+ DRAFT7.tests(),
+ DRAFT7.format_tests(),
+ DRAFT7.optional_tests_of(name="bignum"),
+ DRAFT7.optional_tests_of(name="cross-draft"),
+ DRAFT7.optional_tests_of(name="float-overflow"),
+ DRAFT7.optional_tests_of(name="non-bmp-regex"),
+ Validator=jsonschema.Draft7Validator,
+ format_checker=jsonschema.Draft7Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ narrow_unicode_build(test)
+ or allowed_leading_zeros(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft7Validator)(test)
+ or complex_email_validation(test)
+ or skip(
+ message=bug(),
+ subject="refRemote",
+ case_description="base URI change - change folder in subschema",
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "$id must be resolved against nearest parent, "
+ "not just immediate parent"
+ ),
+ )(test)
+ ),
+)
+
+
+TestDraft201909 = DRAFT201909.to_unittest_testcase(
+ DRAFT201909.tests(),
+ DRAFT201909.optional_tests_of(name="bignum"),
+ DRAFT201909.optional_tests_of(name="cross-draft"),
+ DRAFT201909.optional_tests_of(name="float-overflow"),
+ DRAFT201909.optional_tests_of(name="non-bmp-regex"),
+ DRAFT201909.optional_tests_of(name="refOfUnknownKeyword"),
+ Validator=jsonschema.Draft201909Validator,
+ skip=lambda test: (
+ skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ case_description=(
+ "$recursiveRef with no $recursiveAnchor in "
+ "the initial target schema resource"
+ ),
+ description=(
+ "leaf node does not match: recursion uses the inner schema"
+ ),
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description="leaf node matches: recursion uses the inner schema",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ case_description=(
+ "dynamic $recursiveRef destination (not predictable "
+ "at schema compile time)"
+ ),
+ description="integer node",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ case_description=(
+ "multiple dynamic paths to the $recursiveRef keyword"
+ ),
+ description="recurse to integerNode - floats are not allowed",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description="integer does not match as a property value",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description=(
+ "leaf node does not match: "
+ "recursion only uses inner schema"
+ ),
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description=(
+ "leaf node matches: "
+ "recursion only uses inner schema"
+ ),
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description=(
+ "two levels, integer does not match as a property value"
+ ),
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description="recursive mismatch",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="recursiveRef",
+ description="two levels, no match",
+ )(test)
+ or skip(
+ message="recursiveRef support isn't working yet.",
+ subject="id",
+ case_description=(
+ "Invalid use of fragments in location-independent $id"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="defs",
+ description="invalid definition schema",
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="anchor",
+ case_description="same $anchor with different base uri",
+ )(test)
+ or skip(
+ message="Vocabulary support is still in-progress.",
+ subject="vocabulary",
+ description=(
+ "no validation: invalid number, but it still validates"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "$id must be resolved against nearest parent, "
+ "not just immediate parent"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="refRemote",
+ case_description="remote HTTP ref with nested absolute ref",
+ )(test)
+ ),
+)
+
+
+TestDraft201909Format = DRAFT201909.to_unittest_testcase(
+ DRAFT201909.format_tests(),
+ name="TestDraft201909Format",
+ Validator=jsonschema.Draft201909Validator,
+ format_checker=jsonschema.Draft201909Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ complex_email_validation(test)
+ or allowed_leading_zeros(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft201909Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
+
+
+TestDraft202012 = DRAFT202012.to_unittest_testcase(
+ DRAFT202012.tests(),
+ DRAFT202012.optional_tests_of(name="bignum"),
+ DRAFT202012.optional_tests_of(name="cross-draft"),
+ DRAFT202012.optional_tests_of(name="float-overflow"),
+ DRAFT202012.optional_tests_of(name="non-bmp-regex"),
+ DRAFT202012.optional_tests_of(name="refOfUnknownKeyword"),
+ Validator=jsonschema.Draft202012Validator,
+ skip=lambda test: (
+ narrow_unicode_build(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="The recursive part is not valid against the root",
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="incorrect extended schema",
+ case_description=(
+ "$ref and $dynamicAnchor are independent of order - "
+ "$defs first"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="correct extended schema",
+ case_description=(
+ "$ref and $dynamicAnchor are independent of order - "
+ "$defs first"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="correct extended schema",
+ case_description=(
+ "$ref and $dynamicAnchor are independent of order - $ref first"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="incorrect extended schema",
+ case_description=(
+ "$ref and $dynamicAnchor are independent of order - $ref first"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description=(
+ "/then/$defs/thingy is the final stop for the $dynamicRef"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description=(
+ "string matches /$defs/thingy, but the $dynamicRef "
+ "does not stop here"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description=(
+ "string matches /$defs/thingy, but the $dynamicRef "
+ "does not stop here"
+ ),
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="dynamicRef",
+ description="recurse to integerNode - floats are not allowed",
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="defs",
+ description="invalid definition schema",
+ )(test)
+ or skip(
+ message="dynamicRef support isn't fully working yet.",
+ subject="anchor",
+ case_description="same $anchor with different base uri",
+ )(test)
+ or skip(
+ message="Vocabulary support is still in-progress.",
+ subject="vocabulary",
+ description=(
+ "no validation: invalid number, but it still validates"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="ref",
+ case_description=(
+ "$id must be resolved against nearest parent, "
+ "not just immediate parent"
+ ),
+ )(test)
+ or skip(
+ message=bug(),
+ subject="refRemote",
+ case_description="remote HTTP ref with nested absolute ref",
+ )(test)
+ ),
+)
+
+
+TestDraft202012Format = DRAFT202012.to_unittest_testcase(
+ DRAFT202012.format_tests(),
+ name="TestDraft202012Format",
+ Validator=jsonschema.Draft202012Validator,
+ format_checker=jsonschema.Draft202012Validator.FORMAT_CHECKER,
+ skip=lambda test: (
+ complex_email_validation(test)
+ or allowed_leading_zeros(test)
+ or leap_second(test)
+ or missing_format(jsonschema.Draft202012Validator)(test)
+ or complex_email_validation(test)
+ ),
+)
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_types.py b/runtime/Lib/site-packages/jsonschema/tests/test_types.py
new file mode 100644
index 0000000000000000000000000000000000000000..3eacc7235a7980234bae72c5e340688005ba626b
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_types.py
@@ -0,0 +1,221 @@
+"""
+Tests for the `TypeChecker`-based type interface.
+
+The actual correctness of the type checking is handled in
+`test_jsonschema_test_suite`; these tests check that TypeChecker
+functions correctly at a more granular level.
+"""
+from collections import namedtuple
+from unittest import TestCase
+
+from jsonschema import ValidationError, _validators
+from jsonschema._types import TypeChecker
+from jsonschema.exceptions import UndefinedTypeCheck, UnknownType
+from jsonschema.validators import Draft202012Validator, extend
+
+
+def equals_2(checker, instance):
+ return instance == 2
+
+
+def is_namedtuple(instance):
+ return isinstance(instance, tuple) and getattr(instance, "_fields", None)
+
+
+def is_object_or_named_tuple(checker, instance):
+ if Draft202012Validator.TYPE_CHECKER.is_type(instance, "object"):
+ return True
+ return is_namedtuple(instance)
+
+
+class TestTypeChecker(TestCase):
+ def test_is_type(self):
+ checker = TypeChecker({"two": equals_2})
+ self.assertEqual(
+ (
+ checker.is_type(instance=2, type="two"),
+ checker.is_type(instance="bar", type="two"),
+ ),
+ (True, False),
+ )
+
+ def test_is_unknown_type(self):
+ with self.assertRaises(UndefinedTypeCheck) as e:
+ TypeChecker().is_type(4, "foobar")
+ self.assertIn(
+ "'foobar' is unknown to this type checker",
+ str(e.exception),
+ )
+ self.assertTrue(
+ e.exception.__suppress_context__,
+ msg="Expected the internal KeyError to be hidden.",
+ )
+
+ def test_checks_can_be_added_at_init(self):
+ checker = TypeChecker({"two": equals_2})
+ self.assertEqual(checker, TypeChecker().redefine("two", equals_2))
+
+ def test_redefine_existing_type(self):
+ self.assertEqual(
+ TypeChecker().redefine("two", object()).redefine("two", equals_2),
+ TypeChecker().redefine("two", equals_2),
+ )
+
+ def test_remove(self):
+ self.assertEqual(
+ TypeChecker({"two": equals_2}).remove("two"),
+ TypeChecker(),
+ )
+
+ def test_remove_unknown_type(self):
+ with self.assertRaises(UndefinedTypeCheck) as context:
+ TypeChecker().remove("foobar")
+ self.assertIn("foobar", str(context.exception))
+
+ def test_redefine_many(self):
+ self.assertEqual(
+ TypeChecker().redefine_many({"foo": int, "bar": str}),
+ TypeChecker().redefine("foo", int).redefine("bar", str),
+ )
+
+ def test_remove_multiple(self):
+ self.assertEqual(
+ TypeChecker({"foo": int, "bar": str}).remove("foo", "bar"),
+ TypeChecker(),
+ )
+
+ def test_type_check_can_raise_key_error(self):
+ """
+ Make sure no one writes:
+
+ try:
+ self._type_checkers[type](...)
+ except KeyError:
+
+ ignoring the fact that the function itself can raise that.
+ """
+
+ error = KeyError("Stuff")
+
+ def raises_keyerror(checker, instance):
+ raise error
+
+ with self.assertRaises(KeyError) as context:
+ TypeChecker({"foo": raises_keyerror}).is_type(4, "foo")
+
+ self.assertIs(context.exception, error)
+
+ def test_repr(self):
+ checker = TypeChecker({"foo": is_namedtuple, "bar": is_namedtuple})
+ self.assertEqual(repr(checker), "")
+
+
+class TestCustomTypes(TestCase):
+ def test_simple_type_can_be_extended(self):
+ def int_or_str_int(checker, instance):
+ if not isinstance(instance, (int, str)):
+ return False
+ try:
+ int(instance)
+ except ValueError:
+ return False
+ return True
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=Draft202012Validator.TYPE_CHECKER.redefine(
+ "integer", int_or_str_int,
+ ),
+ )
+ validator = CustomValidator({"type": "integer"})
+
+ validator.validate(4)
+ validator.validate("4")
+
+ with self.assertRaises(ValidationError):
+ validator.validate(4.4)
+
+ with self.assertRaises(ValidationError):
+ validator.validate("foo")
+
+ def test_object_can_be_extended(self):
+ schema = {"type": "object"}
+
+ Point = namedtuple("Point", ["x", "y"])
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ )
+ validator = CustomValidator(schema)
+
+ validator.validate(Point(x=4, y=5))
+
+ def test_object_extensions_require_custom_validators(self):
+ schema = {"type": "object", "required": ["x"]}
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ )
+ validator = CustomValidator(schema)
+
+ Point = namedtuple("Point", ["x", "y"])
+ # Cannot handle required
+ with self.assertRaises(ValidationError):
+ validator.validate(Point(x=4, y=5))
+
+ def test_object_extensions_can_handle_custom_validators(self):
+ schema = {
+ "type": "object",
+ "required": ["x"],
+ "properties": {"x": {"type": "integer"}},
+ }
+
+ type_checker = Draft202012Validator.TYPE_CHECKER.redefine(
+ "object", is_object_or_named_tuple,
+ )
+
+ def coerce_named_tuple(fn):
+ def coerced(validator, value, instance, schema):
+ if is_namedtuple(instance):
+ instance = instance._asdict()
+ return fn(validator, value, instance, schema)
+ return coerced
+
+ required = coerce_named_tuple(_validators.required)
+ properties = coerce_named_tuple(_validators.properties)
+
+ CustomValidator = extend(
+ Draft202012Validator,
+ type_checker=type_checker,
+ validators={"required": required, "properties": properties},
+ )
+
+ validator = CustomValidator(schema)
+
+ Point = namedtuple("Point", ["x", "y"])
+ # Can now process required and properties
+ validator.validate(Point(x=4, y=5))
+
+ with self.assertRaises(ValidationError):
+ validator.validate(Point(x="not an integer", y=5))
+
+ # As well as still handle objects.
+ validator.validate({"x": 4, "y": 5})
+
+ with self.assertRaises(ValidationError):
+ validator.validate({"x": "not an integer", "y": 5})
+
+ def test_unknown_type(self):
+ with self.assertRaises(UnknownType) as e:
+ Draft202012Validator({}).is_type(12, "some unknown type")
+ self.assertIn("'some unknown type'", str(e.exception))
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_utils.py b/runtime/Lib/site-packages/jsonschema/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e542b9628d2572c3f43da40c46b2a0b13ac7421
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_utils.py
@@ -0,0 +1,124 @@
+from unittest import TestCase
+
+from jsonschema._utils import equal
+
+
+class TestEqual(TestCase):
+ def test_none(self):
+ self.assertTrue(equal(None, None))
+
+
+class TestDictEqual(TestCase):
+ def test_equal_dictionaries(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "b"}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_missing_key(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "x": "b"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_additional_key(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "b", "x": "x"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_missing_value(self):
+ dict_1 = {"a": "b", "c": "d"}
+ dict_2 = {"c": "d", "a": "x"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_empty_dictionaries(self):
+ dict_1 = {}
+ dict_2 = {}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_one_none(self):
+ dict_1 = None
+ dict_2 = {"a": "b", "c": "d"}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_same_item(self):
+ dict_1 = {"a": "b", "c": "d"}
+ self.assertTrue(equal(dict_1, dict_1))
+
+ def test_nested_equal(self):
+ dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
+ dict_2 = {"c": "d", "a": {"a": "b", "c": "d"}}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_nested_dict_unequal(self):
+ dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"}
+ dict_2 = {"c": "d", "a": {"a": "b", "c": "x"}}
+ self.assertFalse(equal(dict_1, dict_2))
+
+ def test_mixed_nested_equal(self):
+ dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
+ dict_2 = {"c": "d", "a": ["a", "b", "c", "d"]}
+ self.assertTrue(equal(dict_1, dict_2))
+
+ def test_nested_list_unequal(self):
+ dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"}
+ dict_2 = {"c": "d", "a": ["b", "c", "d", "a"]}
+ self.assertFalse(equal(dict_1, dict_2))
+
+
+class TestListEqual(TestCase):
+ def test_equal_lists(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["a", "b", "c"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_unsorted_lists(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["b", "b", "a"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_first_list_larger(self):
+ list_1 = ["a", "b", "c"]
+ list_2 = ["a", "b"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_second_list_larger(self):
+ list_1 = ["a", "b"]
+ list_2 = ["a", "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_list_with_none_unequal(self):
+ list_1 = ["a", "b", None]
+ list_2 = ["a", "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ list_1 = ["a", "b", None]
+ list_2 = [None, "b", "c"]
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_list_with_none_equal(self):
+ list_1 = ["a", None, "c"]
+ list_2 = ["a", None, "c"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_empty_list(self):
+ list_1 = []
+ list_2 = []
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_one_none(self):
+ list_1 = None
+ list_2 = []
+ self.assertFalse(equal(list_1, list_2))
+
+ def test_same_list(self):
+ list_1 = ["a", "b", "c"]
+ self.assertTrue(equal(list_1, list_1))
+
+ def test_equal_nested_lists(self):
+ list_1 = ["a", ["b", "c"], "d"]
+ list_2 = ["a", ["b", "c"], "d"]
+ self.assertTrue(equal(list_1, list_2))
+
+ def test_unequal_nested_lists(self):
+ list_1 = ["a", ["b", "c"], "d"]
+ list_2 = ["a", [], "c"]
+ self.assertFalse(equal(list_1, list_2))
diff --git a/runtime/Lib/site-packages/jsonschema/tests/test_validators.py b/runtime/Lib/site-packages/jsonschema/tests/test_validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec76a3e323e450eeb6f54fd7ff262c657e22c8e8
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/tests/test_validators.py
@@ -0,0 +1,2316 @@
+from __future__ import annotations
+
+from collections import deque, namedtuple
+from contextlib import contextmanager
+from decimal import Decimal
+from io import BytesIO
+from unittest import TestCase, mock
+from urllib.request import pathname2url
+import json
+import os
+import sys
+import tempfile
+import unittest
+import warnings
+
+import attr
+
+from jsonschema import (
+ FormatChecker,
+ TypeChecker,
+ exceptions,
+ protocols,
+ validators,
+)
+from jsonschema.tests._helpers import bug
+
+
+def fail(validator, errors, instance, schema):
+ for each in errors:
+ each.setdefault("message", "You told me to fail!")
+ yield exceptions.ValidationError(**each)
+
+
+class TestCreateAndExtend(TestCase):
+ def setUp(self):
+ self.addCleanup(
+ self.assertEqual,
+ validators._META_SCHEMAS,
+ dict(validators._META_SCHEMAS),
+ )
+
+ self.meta_schema = {"$id": "some://meta/schema"}
+ self.validators = {"fail": fail}
+ self.type_checker = TypeChecker()
+ self.Validator = validators.create(
+ meta_schema=self.meta_schema,
+ validators=self.validators,
+ type_checker=self.type_checker,
+ )
+
+ def test_attrs(self):
+ self.assertEqual(
+ (
+ self.Validator.VALIDATORS,
+ self.Validator.META_SCHEMA,
+ self.Validator.TYPE_CHECKER,
+ ), (
+ self.validators,
+ self.meta_schema,
+ self.type_checker,
+ ),
+ )
+
+ def test_init(self):
+ schema = {"fail": []}
+ self.assertEqual(self.Validator(schema).schema, schema)
+
+ def test_iter_errors_successful(self):
+ schema = {"fail": []}
+ validator = self.Validator(schema)
+
+ errors = list(validator.iter_errors("hello"))
+ self.assertEqual(errors, [])
+
+ def test_iter_errors_one_error(self):
+ schema = {"fail": [{"message": "Whoops!"}]}
+ validator = self.Validator(schema)
+
+ expected_error = exceptions.ValidationError(
+ "Whoops!",
+ instance="goodbye",
+ schema=schema,
+ validator="fail",
+ validator_value=[{"message": "Whoops!"}],
+ schema_path=deque(["fail"]),
+ )
+
+ errors = list(validator.iter_errors("goodbye"))
+ self.assertEqual(len(errors), 1)
+ self.assertEqual(errors[0]._contents(), expected_error._contents())
+
+ def test_iter_errors_multiple_errors(self):
+ schema = {
+ "fail": [
+ {"message": "First"},
+ {"message": "Second!", "validator": "asdf"},
+ {"message": "Third"},
+ ],
+ }
+ validator = self.Validator(schema)
+
+ errors = list(validator.iter_errors("goodbye"))
+ self.assertEqual(len(errors), 3)
+
+ def test_if_a_version_is_provided_it_is_registered(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.assertEqual(Validator.__name__, "MyVersionValidator")
+ self.assertEqual(Validator.__qualname__, "MyVersionValidator")
+
+ def test_repr(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.assertEqual(
+ repr(Validator({})),
+ "MyVersionValidator(schema={}, format_checker=None)",
+ )
+
+ def test_long_repr(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.assertEqual(
+ repr(Validator({"a": list(range(1000))})), (
+ "MyVersionValidator(schema={'a': [0, 1, 2, 3, 4, 5, ...]}, "
+ "format_checker=None)"
+ ),
+ )
+
+ def test_repr_no_version(self):
+ Validator = validators.create(meta_schema={})
+ self.assertEqual(
+ repr(Validator({})),
+ "Validator(schema={}, format_checker=None)",
+ )
+
+ def test_dashes_are_stripped_from_validator_names(self):
+ Validator = validators.create(
+ meta_schema={"$id": "something"},
+ version="foo-bar",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, "something")
+ self.assertEqual(Validator.__qualname__, "FooBarValidator")
+
+ def test_if_a_version_is_not_provided_it_is_not_registered(self):
+ original = dict(validators._META_SCHEMAS)
+ validators.create(meta_schema={"id": "id"})
+ self.assertEqual(validators._META_SCHEMAS, original)
+
+ def test_validates_registers_meta_schema_id(self):
+ meta_schema_key = "meta schema id"
+ my_meta_schema = {"id": meta_schema_key}
+
+ validators.create(
+ meta_schema=my_meta_schema,
+ version="my version",
+ id_of=lambda s: s.get("id", ""),
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
+
+ self.assertIn(meta_schema_key, validators._META_SCHEMAS)
+
+ def test_validates_registers_meta_schema_draft6_id(self):
+ meta_schema_key = "meta schema $id"
+ my_meta_schema = {"$id": meta_schema_key}
+
+ validators.create(
+ meta_schema=my_meta_schema,
+ version="my version",
+ )
+ self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key)
+
+ self.assertIn(meta_schema_key, validators._META_SCHEMAS)
+
+ def test_create_default_types(self):
+ Validator = validators.create(meta_schema={}, validators=())
+ self.assertTrue(
+ all(
+ Validator({}).is_type(instance=instance, type=type)
+ for type, instance in [
+ ("array", []),
+ ("boolean", True),
+ ("integer", 12),
+ ("null", None),
+ ("number", 12.0),
+ ("object", {}),
+ ("string", "foo"),
+ ]
+ ),
+ )
+
+ def test_check_schema_with_different_metaschema(self):
+ """
+ One can create a validator class whose metaschema uses a different
+ dialect than itself.
+ """
+
+ NoEmptySchemasValidator = validators.create(
+ meta_schema={
+ "$schema": validators.Draft202012Validator.META_SCHEMA["$id"],
+ "not": {"const": {}},
+ },
+ )
+ NoEmptySchemasValidator.check_schema({"foo": "bar"})
+
+ with self.assertRaises(exceptions.SchemaError):
+ NoEmptySchemasValidator.check_schema({})
+
+ NoEmptySchemasValidator({"foo": "bar"}).validate("foo")
+
+ def test_check_schema_with_different_metaschema_defaults_to_self(self):
+ """
+ A validator whose metaschema doesn't declare $schema defaults to its
+ own validation behavior, not the latest "normal" specification.
+ """
+
+ NoEmptySchemasValidator = validators.create(
+ meta_schema={"fail": [{"message": "Meta schema whoops!"}]},
+ validators={"fail": fail},
+ )
+ with self.assertRaises(exceptions.SchemaError):
+ NoEmptySchemasValidator.check_schema({})
+
+ def test_extend(self):
+ original = dict(self.Validator.VALIDATORS)
+ new = object()
+
+ Extended = validators.extend(
+ self.Validator,
+ validators={"new": new},
+ )
+ self.assertEqual(
+ (
+ Extended.VALIDATORS,
+ Extended.META_SCHEMA,
+ Extended.TYPE_CHECKER,
+ self.Validator.VALIDATORS,
+ ), (
+ dict(original, new=new),
+ self.Validator.META_SCHEMA,
+ self.Validator.TYPE_CHECKER,
+ original,
+ ),
+ )
+
+ def test_extend_idof(self):
+ """
+ Extending a validator preserves its notion of schema IDs.
+ """
+ def id_of(schema):
+ return schema.get("__test__", self.Validator.ID_OF(schema))
+ correct_id = "the://correct/id/"
+ meta_schema = {
+ "$id": "the://wrong/id/",
+ "__test__": correct_id,
+ }
+ Original = validators.create(
+ meta_schema=meta_schema,
+ validators=self.validators,
+ type_checker=self.type_checker,
+ id_of=id_of,
+ )
+ self.assertEqual(Original.ID_OF(Original.META_SCHEMA), correct_id)
+
+ Derived = validators.extend(Original)
+ self.assertEqual(Derived.ID_OF(Derived.META_SCHEMA), correct_id)
+
+
+class TestValidationErrorMessages(TestCase):
+ def message_for(self, instance, schema, *args, **kwargs):
+ cls = kwargs.pop("cls", validators._LATEST_VERSION)
+ cls.check_schema(schema)
+ validator = cls(schema, *args, **kwargs)
+ errors = list(validator.iter_errors(instance))
+ self.assertTrue(errors, msg=f"No errors were raised for {instance!r}")
+ self.assertEqual(
+ len(errors),
+ 1,
+ msg=f"Expected exactly one error, found {errors!r}",
+ )
+ return errors[0].message
+
+ def test_single_type_failure(self):
+ message = self.message_for(instance=1, schema={"type": "string"})
+ self.assertEqual(message, "1 is not of type 'string'")
+
+ def test_single_type_list_failure(self):
+ message = self.message_for(instance=1, schema={"type": ["string"]})
+ self.assertEqual(message, "1 is not of type 'string'")
+
+ def test_multiple_type_failure(self):
+ types = "string", "object"
+ message = self.message_for(instance=1, schema={"type": list(types)})
+ self.assertEqual(message, "1 is not of type 'string', 'object'")
+
+ def test_object_with_named_type_failure(self):
+ schema = {"type": [{"name": "Foo", "minimum": 3}]}
+ message = self.message_for(
+ instance=1,
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "1 is not of type 'Foo'")
+
+ def test_minimum(self):
+ message = self.message_for(instance=1, schema={"minimum": 2})
+ self.assertEqual(message, "1 is less than the minimum of 2")
+
+ def test_maximum(self):
+ message = self.message_for(instance=1, schema={"maximum": 0})
+ self.assertEqual(message, "1 is greater than the maximum of 0")
+
+ def test_dependencies_single_element(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: on}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_object_without_title_type_failure_draft3(self):
+ type = {"type": [{"minimum": 3}]}
+ message = self.message_for(
+ instance=1,
+ schema={"type": [type]},
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(
+ message,
+ "1 is not of type {'type': [{'minimum': 3}]}",
+ )
+
+ def test_dependencies_list_draft3(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: [on]}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft3Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_dependencies_list_draft7(self):
+ depend, on = "bar", "foo"
+ schema = {"dependencies": {depend: [on]}}
+ message = self.message_for(
+ instance={"bar": 2},
+ schema=schema,
+ cls=validators.Draft7Validator,
+ )
+ self.assertEqual(message, "'foo' is a dependency of 'bar'")
+
+ def test_additionalItems_single_failure(self):
+ message = self.message_for(
+ instance=[2],
+ schema={"items": [], "additionalItems": False},
+ cls=validators.Draft3Validator,
+ )
+ self.assertIn("(2 was unexpected)", message)
+
+ def test_additionalItems_multiple_failures(self):
+ message = self.message_for(
+ instance=[1, 2, 3],
+ schema={"items": [], "additionalItems": False},
+ cls=validators.Draft3Validator,
+ )
+ self.assertIn("(1, 2, 3 were unexpected)", message)
+
+ def test_additionalProperties_single_failure(self):
+ additional = "foo"
+ schema = {"additionalProperties": False}
+ message = self.message_for(instance={additional: 2}, schema=schema)
+ self.assertIn("('foo' was unexpected)", message)
+
+ def test_additionalProperties_multiple_failures(self):
+ schema = {"additionalProperties": False}
+ message = self.message_for(
+ instance=dict.fromkeys(["foo", "bar"]),
+ schema=schema,
+ )
+
+ self.assertIn(repr("foo"), message)
+ self.assertIn(repr("bar"), message)
+ self.assertIn("were unexpected)", message)
+
+ def test_const(self):
+ schema = {"const": 12}
+ message = self.message_for(
+ instance={"foo": "bar"},
+ schema=schema,
+ )
+ self.assertIn("12 was expected", message)
+
+ def test_contains_draft_6(self):
+ schema = {"contains": {"const": 12}}
+ message = self.message_for(
+ instance=[2, {}, []],
+ schema=schema,
+ cls=validators.Draft6Validator,
+ )
+ self.assertEqual(
+ message,
+ "None of [2, {}, []] are valid under the given schema",
+ )
+
+ def test_invalid_format_default_message(self):
+ checker = FormatChecker(formats=())
+ checker.checks("thing")(lambda value: False)
+
+ schema = {"format": "thing"}
+ message = self.message_for(
+ instance="bla",
+ schema=schema,
+ format_checker=checker,
+ )
+
+ self.assertIn(repr("bla"), message)
+ self.assertIn(repr("thing"), message)
+ self.assertIn("is not a", message)
+
+ def test_additionalProperties_false_patternProperties(self):
+ schema = {"type": "object",
+ "additionalProperties": False,
+ "patternProperties": {
+ "^abc$": {"type": "string"},
+ "^def$": {"type": "string"},
+ }}
+ message = self.message_for(
+ instance={"zebra": 123},
+ schema=schema,
+ cls=validators.Draft4Validator,
+ )
+ self.assertEqual(
+ message,
+ "{} does not match any of the regexes: {}, {}".format(
+ repr("zebra"), repr("^abc$"), repr("^def$"),
+ ),
+ )
+ message = self.message_for(
+ instance={"zebra": 123, "fish": 456},
+ schema=schema,
+ cls=validators.Draft4Validator,
+ )
+ self.assertEqual(
+ message,
+ "{}, {} do not match any of the regexes: {}, {}".format(
+ repr("fish"), repr("zebra"), repr("^abc$"), repr("^def$"),
+ ),
+ )
+
+ def test_False_schema(self):
+ message = self.message_for(
+ instance="something",
+ schema=False,
+ )
+ self.assertEqual(message, "False schema does not allow 'something'")
+
+ def test_multipleOf(self):
+ message = self.message_for(
+ instance=3,
+ schema={"multipleOf": 2},
+ )
+ self.assertEqual(message, "3 is not a multiple of 2")
+
+ def test_minItems(self):
+ message = self.message_for(instance=[], schema={"minItems": 2})
+ self.assertEqual(message, "[] is too short")
+
+ def test_maxItems(self):
+ message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 2})
+ self.assertEqual(message, "[1, 2, 3] is too long")
+
+ def test_prefixItems_with_items(self):
+ message = self.message_for(
+ instance=[1, 2, "foo", 5],
+ schema={"items": False, "prefixItems": [{}, {}]},
+ )
+ self.assertEqual(message, "Expected at most 2 items, but found 4")
+
+ def test_minLength(self):
+ message = self.message_for(
+ instance="",
+ schema={"minLength": 2},
+ )
+ self.assertEqual(message, "'' is too short")
+
+ def test_maxLength(self):
+ message = self.message_for(
+ instance="abc",
+ schema={"maxLength": 2},
+ )
+ self.assertEqual(message, "'abc' is too long")
+
+ def test_pattern(self):
+ message = self.message_for(
+ instance="bbb",
+ schema={"pattern": "^a*$"},
+ )
+ self.assertEqual(message, "'bbb' does not match '^a*$'")
+
+ def test_does_not_contain(self):
+ message = self.message_for(
+ instance=[],
+ schema={"contains": {"type": "string"}},
+ )
+ self.assertEqual(
+ message,
+ "[] does not contain items matching the given schema",
+ )
+
+ def test_contains_too_few(self):
+ message = self.message_for(
+ instance=["foo", 1],
+ schema={"contains": {"type": "string"}, "minContains": 2},
+ )
+ self.assertEqual(
+ message,
+ "Too few items match the given schema "
+ "(expected at least 2 but only 1 matched)",
+ )
+
+ def test_contains_too_few_both_constrained(self):
+ message = self.message_for(
+ instance=["foo", 1],
+ schema={
+ "contains": {"type": "string"},
+ "minContains": 2,
+ "maxContains": 4,
+ },
+ )
+ self.assertEqual(
+ message,
+ "Too few items match the given schema (expected at least 2 but "
+ "only 1 matched)",
+ )
+
+ def test_contains_too_many(self):
+ message = self.message_for(
+ instance=["foo", "bar", "baz"],
+ schema={"contains": {"type": "string"}, "maxContains": 2},
+ )
+ self.assertEqual(
+ message,
+ "Too many items match the given schema (expected at most 2)",
+ )
+
+ def test_contains_too_many_both_constrained(self):
+ message = self.message_for(
+ instance=["foo"] * 5,
+ schema={
+ "contains": {"type": "string"},
+ "minContains": 2,
+ "maxContains": 4,
+ },
+ )
+ self.assertEqual(
+ message,
+ "Too many items match the given schema (expected at most 4)",
+ )
+
+ def test_exclusiveMinimum(self):
+ message = self.message_for(
+ instance=3,
+ schema={"exclusiveMinimum": 5},
+ )
+ self.assertEqual(
+ message,
+ "3 is less than or equal to the minimum of 5",
+ )
+
+ def test_exclusiveMaximum(self):
+ message = self.message_for(instance=3, schema={"exclusiveMaximum": 2})
+ self.assertEqual(
+ message,
+ "3 is greater than or equal to the maximum of 2",
+ )
+
+ def test_required(self):
+ message = self.message_for(instance={}, schema={"required": ["foo"]})
+ self.assertEqual(message, "'foo' is a required property")
+
+ def test_dependentRequired(self):
+ message = self.message_for(
+ instance={"foo": {}},
+ schema={"dependentRequired": {"foo": ["bar"]}},
+ )
+ self.assertEqual(message, "'bar' is a dependency of 'foo'")
+
+ def test_minProperties(self):
+ message = self.message_for(instance={}, schema={"minProperties": 2})
+ self.assertEqual(message, "{} does not have enough properties")
+
+ def test_maxProperties(self):
+ message = self.message_for(
+ instance={"a": {}, "b": {}, "c": {}},
+ schema={"maxProperties": 2},
+ )
+ self.assertEqual(
+ message,
+ "{'a': {}, 'b': {}, 'c': {}} has too many properties",
+ )
+
+ def test_oneOf_matches_none(self):
+ message = self.message_for(instance={}, schema={"oneOf": [False]})
+ self.assertEqual(
+ message,
+ "{} is not valid under any of the given schemas",
+ )
+
+ def test_oneOf_matches_too_many(self):
+ message = self.message_for(instance={}, schema={"oneOf": [True, True]})
+ self.assertEqual(message, "{} is valid under each of True, True")
+
+ def test_unevaluated_items(self):
+ schema = {"type": "array", "unevaluatedItems": False}
+ message = self.message_for(instance=["foo", "bar"], schema=schema)
+ self.assertIn(
+ message,
+ "Unevaluated items are not allowed ('bar', 'foo' were unexpected)",
+ )
+
+ def test_unevaluated_items_on_invalid_type(self):
+ schema = {"type": "array", "unevaluatedItems": False}
+ message = self.message_for(instance="foo", schema=schema)
+ self.assertEqual(message, "'foo' is not of type 'array'")
+
+ def test_unevaluated_properties_invalid_against_subschema(self):
+ schema = {
+ "properties": {"foo": {"type": "string"}},
+ "unevaluatedProperties": {"const": 12},
+ }
+ message = self.message_for(
+ instance={
+ "foo": "foo",
+ "bar": "bar",
+ "baz": 12,
+ },
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated properties are not valid under the given schema "
+ "('bar' was unevaluated and invalid)",
+ )
+
+ def test_unevaluated_properties_disallowed(self):
+ schema = {"type": "object", "unevaluatedProperties": False}
+ message = self.message_for(
+ instance={
+ "foo": "foo",
+ "bar": "bar",
+ },
+ schema=schema,
+ )
+ self.assertEqual(
+ message,
+ "Unevaluated properties are not allowed "
+ "('bar', 'foo' were unexpected)",
+ )
+
+ def test_unevaluated_properties_on_invalid_type(self):
+ schema = {"type": "object", "unevaluatedProperties": False}
+ message = self.message_for(instance="foo", schema=schema)
+ self.assertEqual(message, "'foo' is not of type 'object'")
+
+
+class TestValidationErrorDetails(TestCase):
+ # TODO: These really need unit tests for each individual keyword, rather
+ # than just these higher level tests.
+ def test_anyOf(self):
+ instance = 5
+ schema = {
+ "anyOf": [
+ {"minimum": 20},
+ {"type": "string"},
+ ],
+ }
+
+ validator = validators.Draft4Validator(schema)
+ errors = list(validator.iter_errors(instance))
+ self.assertEqual(len(errors), 1)
+ e = errors[0]
+
+ self.assertEqual(e.validator, "anyOf")
+ self.assertEqual(e.validator_value, schema["anyOf"])
+ self.assertEqual(e.instance, instance)
+ self.assertEqual(e.schema, schema)
+ self.assertIsNone(e.parent)
+
+ self.assertEqual(e.path, deque([]))
+ self.assertEqual(e.relative_path, deque([]))
+ self.assertEqual(e.absolute_path, deque([]))
+ self.assertEqual(e.json_path, "$")
+
+ self.assertEqual(e.schema_path, deque(["anyOf"]))
+ self.assertEqual(e.relative_schema_path, deque(["anyOf"]))
+ self.assertEqual(e.absolute_schema_path, deque(["anyOf"]))
+
+ self.assertEqual(len(e.context), 2)
+
+ e1, e2 = sorted_errors(e.context)
+
+ self.assertEqual(e1.validator, "minimum")
+ self.assertEqual(e1.validator_value, schema["anyOf"][0]["minimum"])
+ self.assertEqual(e1.instance, instance)
+ self.assertEqual(e1.schema, schema["anyOf"][0])
+ self.assertIs(e1.parent, e)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e1.absolute_path, deque([]))
+ self.assertEqual(e1.relative_path, deque([]))
+ self.assertEqual(e1.json_path, "$")
+
+ self.assertEqual(e1.schema_path, deque([0, "minimum"]))
+ self.assertEqual(e1.relative_schema_path, deque([0, "minimum"]))
+ self.assertEqual(
+ e1.absolute_schema_path, deque(["anyOf", 0, "minimum"]),
+ )
+
+ self.assertFalse(e1.context)
+
+ self.assertEqual(e2.validator, "type")
+ self.assertEqual(e2.validator_value, schema["anyOf"][1]["type"])
+ self.assertEqual(e2.instance, instance)
+ self.assertEqual(e2.schema, schema["anyOf"][1])
+ self.assertIs(e2.parent, e)
+
+ self.assertEqual(e2.path, deque([]))
+ self.assertEqual(e2.relative_path, deque([]))
+ self.assertEqual(e2.absolute_path, deque([]))
+ self.assertEqual(e2.json_path, "$")
+
+ self.assertEqual(e2.schema_path, deque([1, "type"]))
+ self.assertEqual(e2.relative_schema_path, deque([1, "type"]))
+ self.assertEqual(e2.absolute_schema_path, deque(["anyOf", 1, "type"]))
+
+ self.assertEqual(len(e2.context), 0)
+
+ def test_type(self):
+ instance = {"foo": 1}
+ schema = {
+ "type": [
+ {"type": "integer"},
+ {
+ "type": "object",
+ "properties": {"foo": {"enum": [2]}},
+ },
+ ],
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = list(validator.iter_errors(instance))
+ self.assertEqual(len(errors), 1)
+ e = errors[0]
+
+ self.assertEqual(e.validator, "type")
+ self.assertEqual(e.validator_value, schema["type"])
+ self.assertEqual(e.instance, instance)
+ self.assertEqual(e.schema, schema)
+ self.assertIsNone(e.parent)
+
+ self.assertEqual(e.path, deque([]))
+ self.assertEqual(e.relative_path, deque([]))
+ self.assertEqual(e.absolute_path, deque([]))
+ self.assertEqual(e.json_path, "$")
+
+ self.assertEqual(e.schema_path, deque(["type"]))
+ self.assertEqual(e.relative_schema_path, deque(["type"]))
+ self.assertEqual(e.absolute_schema_path, deque(["type"]))
+
+ self.assertEqual(len(e.context), 2)
+
+ e1, e2 = sorted_errors(e.context)
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e1.validator_value, schema["type"][0]["type"])
+ self.assertEqual(e1.instance, instance)
+ self.assertEqual(e1.schema, schema["type"][0])
+ self.assertIs(e1.parent, e)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e1.relative_path, deque([]))
+ self.assertEqual(e1.absolute_path, deque([]))
+ self.assertEqual(e1.json_path, "$")
+
+ self.assertEqual(e1.schema_path, deque([0, "type"]))
+ self.assertEqual(e1.relative_schema_path, deque([0, "type"]))
+ self.assertEqual(e1.absolute_schema_path, deque(["type", 0, "type"]))
+
+ self.assertFalse(e1.context)
+
+ self.assertEqual(e2.validator, "enum")
+ self.assertEqual(e2.validator_value, [2])
+ self.assertEqual(e2.instance, 1)
+ self.assertEqual(e2.schema, {"enum": [2]})
+ self.assertIs(e2.parent, e)
+
+ self.assertEqual(e2.path, deque(["foo"]))
+ self.assertEqual(e2.relative_path, deque(["foo"]))
+ self.assertEqual(e2.absolute_path, deque(["foo"]))
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(
+ e2.schema_path, deque([1, "properties", "foo", "enum"]),
+ )
+ self.assertEqual(
+ e2.relative_schema_path, deque([1, "properties", "foo", "enum"]),
+ )
+ self.assertEqual(
+ e2.absolute_schema_path,
+ deque(["type", 1, "properties", "foo", "enum"]),
+ )
+
+ self.assertFalse(e2.context)
+
+ def test_single_nesting(self):
+ instance = {"foo": 2, "bar": [1], "baz": 15, "quux": "spam"}
+ schema = {
+ "properties": {
+ "foo": {"type": "string"},
+ "bar": {"minItems": 2},
+ "baz": {"maximum": 10, "enum": [2, 4, 6, 8]},
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2, e3, e4 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["baz"]))
+ self.assertEqual(e3.path, deque(["baz"]))
+ self.assertEqual(e4.path, deque(["foo"]))
+
+ self.assertEqual(e1.relative_path, deque(["bar"]))
+ self.assertEqual(e2.relative_path, deque(["baz"]))
+ self.assertEqual(e3.relative_path, deque(["baz"]))
+ self.assertEqual(e4.relative_path, deque(["foo"]))
+
+ self.assertEqual(e1.absolute_path, deque(["bar"]))
+ self.assertEqual(e2.absolute_path, deque(["baz"]))
+ self.assertEqual(e3.absolute_path, deque(["baz"]))
+ self.assertEqual(e4.absolute_path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.baz")
+ self.assertEqual(e3.json_path, "$.baz")
+ self.assertEqual(e4.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "minItems")
+ self.assertEqual(e2.validator, "enum")
+ self.assertEqual(e3.validator, "maximum")
+ self.assertEqual(e4.validator, "type")
+
+ def test_multiple_nesting(self):
+ instance = [1, {"foo": 2, "bar": {"baz": [1]}}, "quux"]
+ schema = {
+ "type": "string",
+ "items": {
+ "type": ["string", "object"],
+ "properties": {
+ "foo": {"enum": [1, 3]},
+ "bar": {
+ "type": "array",
+ "properties": {
+ "bar": {"required": True},
+ "baz": {"minItems": 2},
+ },
+ },
+ },
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2, e3, e4, e5, e6 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([]))
+ self.assertEqual(e2.path, deque([0]))
+ self.assertEqual(e3.path, deque([1, "bar"]))
+ self.assertEqual(e4.path, deque([1, "bar", "bar"]))
+ self.assertEqual(e5.path, deque([1, "bar", "baz"]))
+ self.assertEqual(e6.path, deque([1, "foo"]))
+
+ self.assertEqual(e1.json_path, "$")
+ self.assertEqual(e2.json_path, "$[0]")
+ self.assertEqual(e3.json_path, "$[1].bar")
+ self.assertEqual(e4.json_path, "$[1].bar.bar")
+ self.assertEqual(e5.json_path, "$[1].bar.baz")
+ self.assertEqual(e6.json_path, "$[1].foo")
+
+ self.assertEqual(e1.schema_path, deque(["type"]))
+ self.assertEqual(e2.schema_path, deque(["items", "type"]))
+ self.assertEqual(
+ list(e3.schema_path), ["items", "properties", "bar", "type"],
+ )
+ self.assertEqual(
+ list(e4.schema_path),
+ ["items", "properties", "bar", "properties", "bar", "required"],
+ )
+ self.assertEqual(
+ list(e5.schema_path),
+ ["items", "properties", "bar", "properties", "baz", "minItems"],
+ )
+ self.assertEqual(
+ list(e6.schema_path), ["items", "properties", "foo", "enum"],
+ )
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "type")
+ self.assertEqual(e3.validator, "type")
+ self.assertEqual(e4.validator, "required")
+ self.assertEqual(e5.validator, "minItems")
+ self.assertEqual(e6.validator, "enum")
+
+ def test_recursive(self):
+ schema = {
+ "definitions": {
+ "node": {
+ "anyOf": [{
+ "type": "object",
+ "required": ["name", "children"],
+ "properties": {
+ "name": {
+ "type": "string",
+ },
+ "children": {
+ "type": "object",
+ "patternProperties": {
+ "^.*$": {
+ "$ref": "#/definitions/node",
+ },
+ },
+ },
+ },
+ }],
+ },
+ },
+ "type": "object",
+ "required": ["root"],
+ "properties": {"root": {"$ref": "#/definitions/node"}},
+ }
+
+ instance = {
+ "root": {
+ "name": "root",
+ "children": {
+ "a": {
+ "name": "a",
+ "children": {
+ "ab": {
+ "name": "ab",
+ # missing "children"
+ },
+ },
+ },
+ },
+ },
+ }
+ validator = validators.Draft4Validator(schema)
+
+ e, = validator.iter_errors(instance)
+ self.assertEqual(e.absolute_path, deque(["root"]))
+ self.assertEqual(
+ e.absolute_schema_path, deque(["properties", "root", "anyOf"]),
+ )
+ self.assertEqual(e.json_path, "$.root")
+
+ e1, = e.context
+ self.assertEqual(e1.absolute_path, deque(["root", "children", "a"]))
+ self.assertEqual(
+ e1.absolute_schema_path, deque(
+ [
+ "properties",
+ "root",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ ],
+ ),
+ )
+ self.assertEqual(e1.json_path, "$.root.children.a")
+
+ e2, = e1.context
+ self.assertEqual(
+ e2.absolute_path, deque(
+ ["root", "children", "a", "children", "ab"],
+ ),
+ )
+ self.assertEqual(
+ e2.absolute_schema_path, deque(
+ [
+ "properties",
+ "root",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ 0,
+ "properties",
+ "children",
+ "patternProperties",
+ "^.*$",
+ "anyOf",
+ ],
+ ),
+ )
+ self.assertEqual(e2.json_path, "$.root.children.a.children.ab")
+
+ def test_additionalProperties(self):
+ instance = {"bar": "bar", "foo": 2}
+ schema = {"additionalProperties": {"type": "integer", "minimum": 5}}
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_patternProperties(self):
+ instance = {"bar": 1, "foo": 2}
+ schema = {
+ "patternProperties": {
+ "bar": {"type": "string"},
+ "foo": {"minimum": 5},
+ },
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque(["bar"]))
+ self.assertEqual(e2.path, deque(["foo"]))
+
+ self.assertEqual(e1.json_path, "$.bar")
+ self.assertEqual(e2.json_path, "$.foo")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_additionalItems(self):
+ instance = ["foo", 1]
+ schema = {
+ "items": [],
+ "additionalItems": {"type": "integer", "minimum": 5},
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([0]))
+ self.assertEqual(e2.path, deque([1]))
+
+ self.assertEqual(e1.json_path, "$[0]")
+ self.assertEqual(e2.json_path, "$[1]")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_additionalItems_with_items(self):
+ instance = ["foo", "bar", 1]
+ schema = {
+ "items": [{}],
+ "additionalItems": {"type": "integer", "minimum": 5},
+ }
+
+ validator = validators.Draft3Validator(schema)
+ errors = validator.iter_errors(instance)
+ e1, e2 = sorted_errors(errors)
+
+ self.assertEqual(e1.path, deque([1]))
+ self.assertEqual(e2.path, deque([2]))
+
+ self.assertEqual(e1.json_path, "$[1]")
+ self.assertEqual(e2.json_path, "$[2]")
+
+ self.assertEqual(e1.validator, "type")
+ self.assertEqual(e2.validator, "minimum")
+
+ def test_propertyNames(self):
+ instance = {"foo": 12}
+ schema = {"propertyNames": {"not": {"const": "foo"}}}
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(instance)
+
+ self.assertEqual(error.validator, "not")
+ self.assertEqual(
+ error.message,
+ "'foo' should not be valid under {'const': 'foo'}",
+ )
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["propertyNames", "not"]))
+
+ def test_if_then(self):
+ schema = {
+ "if": {"const": 12},
+ "then": {"const": 13},
+ }
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(12)
+
+ self.assertEqual(error.validator, "const")
+ self.assertEqual(error.message, "13 was expected")
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["then", "const"]))
+
+ def test_if_else(self):
+ schema = {
+ "if": {"const": 12},
+ "else": {"const": 13},
+ }
+
+ validator = validators.Draft7Validator(schema)
+ error, = validator.iter_errors(15)
+
+ self.assertEqual(error.validator, "const")
+ self.assertEqual(error.message, "13 was expected")
+ self.assertEqual(error.path, deque([]))
+ self.assertEqual(error.json_path, "$")
+ self.assertEqual(error.schema_path, deque(["else", "const"]))
+
+ def test_boolean_schema_False(self):
+ validator = validators.Draft7Validator(False)
+ error, = validator.iter_errors(12)
+
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "False schema does not allow 12",
+ None,
+ None,
+ 12,
+ False,
+ deque([]),
+ "$",
+ ),
+ )
+
+ def test_ref(self):
+ ref, schema = "someRef", {"additionalProperties": {"type": "integer"}}
+ validator = validators.Draft7Validator(
+ {"$ref": ref},
+ resolver=validators.RefResolver("", {}, store={ref: schema}),
+ )
+ error, = validator.iter_errors({"foo": "notAnInteger"})
+
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "'notAnInteger' is not of type 'integer'",
+ "type",
+ "integer",
+ "notAnInteger",
+ deque(["foo"]),
+ {"type": "integer"},
+ deque(["additionalProperties", "type"]),
+ "$.foo",
+ ),
+ )
+
+ def test_prefixItems(self):
+ schema = {"prefixItems": [{"type": "string"}, {}, {}, {"maximum": 3}]}
+ validator = validators.Draft202012Validator(schema)
+ type_error, min_error = validator.iter_errors([1, 2, "foo", 5])
+ self.assertEqual(
+ (
+ type_error.message,
+ type_error.validator,
+ type_error.validator_value,
+ type_error.instance,
+ type_error.absolute_path,
+ type_error.schema,
+ type_error.schema_path,
+ type_error.json_path,
+ ),
+ (
+ "1 is not of type 'string'",
+ "type",
+ "string",
+ 1,
+ deque([0]),
+ {"type": "string"},
+ deque(["prefixItems", 0, "type"]),
+ "$[0]",
+ ),
+ )
+ self.assertEqual(
+ (
+ min_error.message,
+ min_error.validator,
+ min_error.validator_value,
+ min_error.instance,
+ min_error.absolute_path,
+ min_error.schema,
+ min_error.schema_path,
+ min_error.json_path,
+ ),
+ (
+ "5 is greater than the maximum of 3",
+ "maximum",
+ 3,
+ 5,
+ deque([3]),
+ {"maximum": 3},
+ deque(["prefixItems", 3, "maximum"]),
+ "$[3]",
+ ),
+ )
+
+ def test_prefixItems_with_items(self):
+ schema = {
+ "items": {"type": "string"},
+ "prefixItems": [{}],
+ }
+ validator = validators.Draft202012Validator(schema)
+ e1, e2 = validator.iter_errors(["foo", 2, "bar", 4, "baz"])
+ self.assertEqual(
+ (
+ e1.message,
+ e1.validator,
+ e1.validator_value,
+ e1.instance,
+ e1.absolute_path,
+ e1.schema,
+ e1.schema_path,
+ e1.json_path,
+ ),
+ (
+ "2 is not of type 'string'",
+ "type",
+ "string",
+ 2,
+ deque([1]),
+ {"type": "string"},
+ deque(["items", "type"]),
+ "$[1]",
+ ),
+ )
+ self.assertEqual(
+ (
+ e2.message,
+ e2.validator,
+ e2.validator_value,
+ e2.instance,
+ e2.absolute_path,
+ e2.schema,
+ e2.schema_path,
+ e2.json_path,
+ ),
+ (
+ "4 is not of type 'string'",
+ "type",
+ "string",
+ 4,
+ deque([3]),
+ {"type": "string"},
+ deque(["items", "type"]),
+ "$[3]",
+ ),
+ )
+
+ def test_contains_too_many(self):
+ """
+ `contains` + `maxContains` produces only one error, even if there are
+ many more incorrectly matching elements.
+ """
+ schema = {"contains": {"type": "string"}, "maxContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors(["foo", 2, "bar", 4, "baz", "quux"])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "Too many items match the given schema (expected at most 2)",
+ "maxContains",
+ 2,
+ ["foo", 2, "bar", 4, "baz", "quux"],
+ deque([]),
+ {"contains": {"type": "string"}, "maxContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_contains_too_few(self):
+ schema = {"contains": {"type": "string"}, "minContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors(["foo", 2, 4])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ (
+ "Too few items match the given schema "
+ "(expected at least 2 but only 1 matched)"
+ ),
+ "minContains",
+ 2,
+ ["foo", 2, 4],
+ deque([]),
+ {"contains": {"type": "string"}, "minContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_contains_none(self):
+ schema = {"contains": {"type": "string"}, "minContains": 2}
+ validator = validators.Draft202012Validator(schema)
+ error, = validator.iter_errors([2, 4])
+ self.assertEqual(
+ (
+ error.message,
+ error.validator,
+ error.validator_value,
+ error.instance,
+ error.absolute_path,
+ error.schema,
+ error.schema_path,
+ error.json_path,
+ ),
+ (
+ "[2, 4] does not contain items matching the given schema",
+ "contains",
+ {"type": "string"},
+ [2, 4],
+ deque([]),
+ {"contains": {"type": "string"}, "minContains": 2},
+ deque(["contains"]),
+ "$",
+ ),
+ )
+
+ def test_ref_sibling(self):
+ schema = {
+ "$defs": {"foo": {"required": ["bar"]}},
+ "properties": {
+ "aprop": {
+ "$ref": "#/$defs/foo",
+ "required": ["baz"],
+ },
+ },
+ }
+
+ validator = validators.Draft202012Validator(schema)
+ e1, e2 = validator.iter_errors({"aprop": {}})
+ self.assertEqual(
+ (
+ e1.message,
+ e1.validator,
+ e1.validator_value,
+ e1.instance,
+ e1.absolute_path,
+ e1.schema,
+ e1.schema_path,
+ e1.relative_schema_path,
+ e1.json_path,
+ ),
+ (
+ "'bar' is a required property",
+ "required",
+ ["bar"],
+ {},
+ deque(["aprop"]),
+ {"required": ["bar"]},
+ deque(["properties", "aprop", "required"]),
+ deque(["properties", "aprop", "required"]),
+ "$.aprop",
+ ),
+ )
+ self.assertEqual(
+ (
+ e2.message,
+ e2.validator,
+ e2.validator_value,
+ e2.instance,
+ e2.absolute_path,
+ e2.schema,
+ e2.schema_path,
+ e2.relative_schema_path,
+ e2.json_path,
+ ),
+ (
+ "'baz' is a required property",
+ "required",
+ ["baz"],
+ {},
+ deque(["aprop"]),
+ {"$ref": "#/$defs/foo", "required": ["baz"]},
+ deque(["properties", "aprop", "required"]),
+ deque(["properties", "aprop", "required"]),
+ "$.aprop",
+ ),
+ )
+
+
+class MetaSchemaTestsMixin:
+ # TODO: These all belong upstream
+ def test_invalid_properties(self):
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"properties": 12})
+
+ def test_minItems_invalid_string(self):
+ with self.assertRaises(exceptions.SchemaError):
+ # needs to be an integer
+ self.Validator.check_schema({"minItems": "1"})
+
+ def test_enum_allows_empty_arrays(self):
+ """
+ Technically, all the spec says is they SHOULD have elements, not MUST.
+
+ (As of Draft 6. Previous drafts do say MUST).
+
+ See #529.
+ """
+ if self.Validator in {
+ validators.Draft3Validator,
+ validators.Draft4Validator,
+ }:
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"enum": []})
+ else:
+ self.Validator.check_schema({"enum": []})
+
+ def test_enum_allows_non_unique_items(self):
+ """
+ Technically, all the spec says is they SHOULD be unique, not MUST.
+
+ (As of Draft 6. Previous drafts do say MUST).
+
+ See #529.
+ """
+ if self.Validator in {
+ validators.Draft3Validator,
+ validators.Draft4Validator,
+ }:
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"enum": [12, 12]})
+ else:
+ self.Validator.check_schema({"enum": [12, 12]})
+
+ def test_schema_with_invalid_regex(self):
+ with self.assertRaises(exceptions.SchemaError):
+ self.Validator.check_schema({"pattern": "*notaregex"})
+
+ def test_schema_with_invalid_regex_with_disabled_format_validation(self):
+ self.Validator.check_schema(
+ {"pattern": "*notaregex"},
+ format_checker=None,
+ )
+
+
+class ValidatorTestMixin(MetaSchemaTestsMixin, object):
+ def test_it_implements_the_validator_protocol(self):
+ self.assertIsInstance(self.Validator({}), protocols.Validator)
+
+ def test_valid_instances_are_valid(self):
+ schema, instance = self.valid
+ self.assertTrue(self.Validator(schema).is_valid(instance))
+
+ def test_invalid_instances_are_not_valid(self):
+ schema, instance = self.invalid
+ self.assertFalse(self.Validator(schema).is_valid(instance))
+
+ def test_non_existent_properties_are_ignored(self):
+ self.Validator({object(): object()}).validate(instance=object())
+
+ def test_it_creates_a_ref_resolver_if_not_provided(self):
+ self.assertIsInstance(
+ self.Validator({}).resolver,
+ validators.RefResolver,
+ )
+
+ def test_it_delegates_to_a_ref_resolver(self):
+ ref, schema = "someCoolRef", {"type": "integer"}
+ resolver = validators.RefResolver("", {}, store={ref: schema})
+ validator = self.Validator({"$ref": ref}, resolver=resolver)
+
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(None)
+
+ def test_evolve(self):
+ ref, schema = "someCoolRef", {"type": "integer"}
+ resolver = validators.RefResolver("", {}, store={ref: schema})
+
+ validator = self.Validator(schema, resolver=resolver)
+ new = validator.evolve(schema={"type": "string"})
+
+ expected = self.Validator({"type": "string"}, resolver=resolver)
+
+ self.assertEqual(new, expected)
+ self.assertNotEqual(new, validator)
+
+ def test_evolve_with_subclass(self):
+ """
+ Subclassing validators isn't supported public API, but some users have
+ done it, because we don't actually error entirely when it's done :/
+
+ We need to deprecate doing so first to help as many of these users
+ ensure they can move to supported APIs, but this test ensures that in
+ the interim, we haven't broken those users.
+ """
+
+ with self.assertWarns(DeprecationWarning):
+ @attr.s
+ class OhNo(self.Validator):
+ foo = attr.ib(factory=lambda: [1, 2, 3])
+ _bar = attr.ib(default=37)
+
+ validator = OhNo({}, bar=12)
+ self.assertEqual(validator.foo, [1, 2, 3])
+
+ new = validator.evolve(schema={"type": "integer"})
+ self.assertEqual(new.foo, [1, 2, 3])
+ self.assertEqual(new._bar, 12)
+
+ def test_it_delegates_to_a_legacy_ref_resolver(self):
+ """
+ Legacy RefResolvers support only the context manager form of
+ resolution.
+ """
+
+ class LegacyRefResolver:
+ @contextmanager
+ def resolving(this, ref):
+ self.assertEqual(ref, "the ref")
+ yield {"type": "integer"}
+
+ resolver = LegacyRefResolver()
+ schema = {"$ref": "the ref"}
+
+ with self.assertRaises(exceptions.ValidationError):
+ self.Validator(schema, resolver=resolver).validate(None)
+
+ def test_is_type_is_true_for_valid_type(self):
+ self.assertTrue(self.Validator({}).is_type("foo", "string"))
+
+ def test_is_type_is_false_for_invalid_type(self):
+ self.assertFalse(self.Validator({}).is_type("foo", "array"))
+
+ def test_is_type_evades_bool_inheriting_from_int(self):
+ self.assertFalse(self.Validator({}).is_type(True, "integer"))
+ self.assertFalse(self.Validator({}).is_type(True, "number"))
+
+ def test_it_can_validate_with_decimals(self):
+ schema = {"items": {"type": "number"}}
+ Validator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "number",
+ lambda checker, thing: isinstance(
+ thing, (int, float, Decimal),
+ ) and not isinstance(thing, bool),
+ ),
+ )
+
+ validator = Validator(schema)
+ validator.validate([1, 1.1, Decimal(1) / Decimal(8)])
+
+ invalid = ["foo", {}, [], True, None]
+ self.assertEqual(
+ [error.instance for error in validator.iter_errors(invalid)],
+ invalid,
+ )
+
+ def test_it_returns_true_for_formats_it_does_not_know_about(self):
+ validator = self.Validator(
+ {"format": "carrot"}, format_checker=FormatChecker(),
+ )
+ validator.validate("bugs")
+
+ def test_it_does_not_validate_formats_by_default(self):
+ validator = self.Validator({})
+ self.assertIsNone(validator.format_checker)
+
+ def test_it_validates_formats_if_a_checker_is_provided(self):
+ checker = FormatChecker()
+ bad = ValueError("Bad!")
+
+ @checker.checks("foo", raises=ValueError)
+ def check(value):
+ if value == "good":
+ return True
+ elif value == "bad":
+ raise bad
+ else: # pragma: no cover
+ self.fail("What is {}? [Baby Don't Hurt Me]".format(value))
+
+ validator = self.Validator(
+ {"format": "foo"}, format_checker=checker,
+ )
+
+ validator.validate("good")
+ with self.assertRaises(exceptions.ValidationError) as cm:
+ validator.validate("bad")
+
+ # Make sure original cause is attached
+ self.assertIs(cm.exception.cause, bad)
+
+ def test_non_string_custom_type(self):
+ non_string_type = object()
+ schema = {"type": [non_string_type]}
+ Crazy = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ non_string_type,
+ lambda checker, thing: isinstance(thing, int),
+ ),
+ )
+ Crazy(schema).validate(15)
+
+ def test_it_properly_formats_tuples_in_errors(self):
+ """
+ A tuple instance properly formats validation errors for uniqueItems.
+
+ See #224
+ """
+ TupleValidator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "array",
+ lambda checker, thing: isinstance(thing, tuple),
+ ),
+ )
+ with self.assertRaises(exceptions.ValidationError) as e:
+ TupleValidator({"uniqueItems": True}).validate((1, 1))
+ self.assertIn("(1, 1) has non-unique elements", str(e.exception))
+
+ def test_check_redefined_sequence(self):
+ """
+ Allow array to validate against another defined sequence type
+ """
+ schema = {"type": "array", "uniqueItems": True}
+ MyMapping = namedtuple("MyMapping", "a, b")
+ Validator = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine_many(
+ {
+ "array": lambda checker, thing: isinstance(
+ thing, (list, deque),
+ ),
+ "object": lambda checker, thing: isinstance(
+ thing, (dict, MyMapping),
+ ),
+ },
+ ),
+ )
+ validator = Validator(schema)
+
+ valid_instances = [
+ deque(["a", None, "1", "", True]),
+ deque([[False], [0]]),
+ [deque([False]), deque([0])],
+ [[deque([False])], [deque([0])]],
+ [[[[[deque([False])]]]], [[[[deque([0])]]]]],
+ [deque([deque([False])]), deque([deque([0])])],
+ [MyMapping("a", 0), MyMapping("a", False)],
+ [
+ MyMapping("a", [deque([0])]),
+ MyMapping("a", [deque([False])]),
+ ],
+ [
+ MyMapping("a", [MyMapping("a", deque([0]))]),
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ ],
+ [deque(deque(deque([False]))), deque(deque(deque([0])))],
+ ]
+
+ for instance in valid_instances:
+ validator.validate(instance)
+
+ invalid_instances = [
+ deque(["a", "b", "a"]),
+ deque([[False], [False]]),
+ [deque([False]), deque([False])],
+ [[deque([False])], [deque([False])]],
+ [[[[[deque([False])]]]], [[[[deque([False])]]]]],
+ [deque([deque([False])]), deque([deque([False])])],
+ [MyMapping("a", False), MyMapping("a", False)],
+ [
+ MyMapping("a", [deque([False])]),
+ MyMapping("a", [deque([False])]),
+ ],
+ [
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ MyMapping("a", [MyMapping("a", deque([False]))]),
+ ],
+ [deque(deque(deque([False]))), deque(deque(deque([False])))],
+ ]
+
+ for instance in invalid_instances:
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(instance)
+
+
+class AntiDraft6LeakMixin:
+ """
+ Make sure functionality from draft 6 doesn't leak backwards in time.
+ """
+
+ def test_True_is_not_a_schema(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ self.Validator.check_schema(True)
+ self.assertIn("True is not of type", str(e.exception))
+
+ def test_False_is_not_a_schema(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ self.Validator.check_schema(False)
+ self.assertIn("False is not of type", str(e.exception))
+
+ @unittest.skip(bug(523))
+ def test_True_is_not_a_schema_even_if_you_forget_to_check(self):
+ resolver = validators.RefResolver("", {})
+ with self.assertRaises(Exception) as e:
+ self.Validator(True, resolver=resolver).validate(12)
+ self.assertNotIsInstance(e.exception, exceptions.ValidationError)
+
+ @unittest.skip(bug(523))
+ def test_False_is_not_a_schema_even_if_you_forget_to_check(self):
+ resolver = validators.RefResolver("", {})
+ with self.assertRaises(Exception) as e:
+ self.Validator(False, resolver=resolver).validate(12)
+ self.assertNotIsInstance(e.exception, exceptions.ValidationError)
+
+
+class TestDraft3Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
+ Validator = validators.Draft3Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+ def test_any_type_is_valid_for_type_any(self):
+ validator = self.Validator({"type": "any"})
+ validator.validate(object())
+
+ def test_any_type_is_redefinable(self):
+ """
+ Sigh, because why not.
+ """
+ Crazy = validators.extend(
+ self.Validator,
+ type_checker=self.Validator.TYPE_CHECKER.redefine(
+ "any", lambda checker, thing: isinstance(thing, int),
+ ),
+ )
+ validator = Crazy({"type": "any"})
+ validator.validate(12)
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate("foo")
+
+ def test_is_type_is_true_for_any_type(self):
+ self.assertTrue(self.Validator({"type": "any"}).is_valid(object()))
+
+ def test_is_type_does_not_evade_bool_if_it_is_being_tested(self):
+ self.assertTrue(self.Validator({}).is_type(True, "boolean"))
+ self.assertTrue(self.Validator({"type": "any"}).is_valid(True))
+
+
+class TestDraft4Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase):
+ Validator = validators.Draft4Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft6Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft6Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft7Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft7Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft201909Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft201909Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestDraft202012Validator(ValidatorTestMixin, TestCase):
+ Validator = validators.Draft202012Validator
+ valid: tuple[dict, dict] = ({}, {})
+ invalid = {"type": "integer"}, "foo"
+
+
+class TestLatestValidator(TestCase):
+ """
+ These really apply to multiple versions but are easiest to test on one.
+ """
+
+ def test_ref_resolvers_may_have_boolean_schemas_stored(self):
+ ref = "someCoolRef"
+ schema = {"$ref": ref}
+ resolver = validators.RefResolver("", {}, store={ref: False})
+ validator = validators._LATEST_VERSION(schema, resolver=resolver)
+
+ with self.assertRaises(exceptions.ValidationError):
+ validator.validate(None)
+
+
+class TestValidatorFor(TestCase):
+ def test_draft_3(self):
+ schema = {"$schema": "http://json-schema.org/draft-03/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft3Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-03/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft3Validator,
+ )
+
+ def test_draft_4(self):
+ schema = {"$schema": "http://json-schema.org/draft-04/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft4Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft4Validator,
+ )
+
+ def test_draft_6(self):
+ schema = {"$schema": "http://json-schema.org/draft-06/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft6Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-06/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft6Validator,
+ )
+
+ def test_draft_7(self):
+ schema = {"$schema": "http://json-schema.org/draft-07/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft7Validator,
+ )
+
+ schema = {"$schema": "http://json-schema.org/draft-07/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft7Validator,
+ )
+
+ def test_draft_201909(self):
+ schema = {"$schema": "https://json-schema.org/draft/2019-09/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft201909Validator,
+ )
+
+ schema = {"$schema": "https://json-schema.org/draft/2019-09/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft201909Validator,
+ )
+
+ def test_draft_202012(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft202012Validator,
+ )
+
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema#"}
+ self.assertIs(
+ validators.validator_for(schema),
+ validators.Draft202012Validator,
+ )
+
+ def test_True(self):
+ self.assertIs(
+ validators.validator_for(True),
+ validators._LATEST_VERSION,
+ )
+
+ def test_False(self):
+ self.assertIs(
+ validators.validator_for(False),
+ validators._LATEST_VERSION,
+ )
+
+ def test_custom_validator(self):
+ Validator = validators.create(
+ meta_schema={"id": "meta schema id"},
+ version="12",
+ id_of=lambda s: s.get("id", ""),
+ )
+ schema = {"$schema": "meta schema id"}
+ self.assertIs(
+ validators.validator_for(schema),
+ Validator,
+ )
+
+ def test_custom_validator_draft6(self):
+ Validator = validators.create(
+ meta_schema={"$id": "meta schema $id"},
+ version="13",
+ )
+ schema = {"$schema": "meta schema $id"}
+ self.assertIs(
+ validators.validator_for(schema),
+ Validator,
+ )
+
+ def test_validator_for_jsonschema_default(self):
+ self.assertIs(validators.validator_for({}), validators._LATEST_VERSION)
+
+ def test_validator_for_custom_default(self):
+ self.assertIs(validators.validator_for({}, default=None), None)
+
+ def test_warns_if_meta_schema_specified_was_not_found(self):
+ with self.assertWarns(DeprecationWarning) as cm:
+ validators.validator_for(schema={"$schema": "unknownSchema"})
+
+ self.assertEqual(cm.filename, __file__)
+ self.assertEqual(
+ str(cm.warning),
+ "The metaschema specified by $schema was not found. "
+ "Using the latest draft to validate, but this will raise "
+ "an error in the future.",
+ )
+
+ def test_does_not_warn_if_meta_schema_is_unspecified(self):
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ validators.validator_for(schema={}, default={})
+ self.assertFalse(w)
+
+ def test_validator_for_custom_default_with_schema(self):
+ schema, default = {"$schema": "mailto:foo@example.com"}, object()
+ self.assertIs(validators.validator_for(schema, default), default)
+
+
+class TestValidate(TestCase):
+ def assertUses(self, schema, Validator):
+ result = []
+ with mock.patch.object(Validator, "check_schema", result.append):
+ validators.validate({}, schema)
+ self.assertEqual(result, [schema])
+
+ def test_draft3_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-03/schema#"},
+ Validator=validators.Draft3Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-03/schema"},
+ Validator=validators.Draft3Validator,
+ )
+
+ def test_draft4_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-04/schema#"},
+ Validator=validators.Draft4Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-04/schema"},
+ Validator=validators.Draft4Validator,
+ )
+
+ def test_draft6_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-06/schema#"},
+ Validator=validators.Draft6Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-06/schema"},
+ Validator=validators.Draft6Validator,
+ )
+
+ def test_draft7_validator_is_chosen(self):
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-07/schema#"},
+ Validator=validators.Draft7Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={"$schema": "http://json-schema.org/draft-07/schema"},
+ Validator=validators.Draft7Validator,
+ )
+
+ def test_draft202012_validator_is_chosen(self):
+ self.assertUses(
+ schema={
+ "$schema": "https://json-schema.org/draft/2020-12/schema#",
+ },
+ Validator=validators.Draft202012Validator,
+ )
+ # Make sure it works without the empty fragment
+ self.assertUses(
+ schema={
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ },
+ Validator=validators.Draft202012Validator,
+ )
+
+ def test_draft202012_validator_is_the_default(self):
+ self.assertUses(schema={}, Validator=validators.Draft202012Validator)
+
+ def test_validation_error_message(self):
+ with self.assertRaises(exceptions.ValidationError) as e:
+ validators.validate(12, {"type": "string"})
+ self.assertRegex(
+ str(e.exception),
+ "(?s)Failed validating '.*' in schema.*On instance",
+ )
+
+ def test_schema_error_message(self):
+ with self.assertRaises(exceptions.SchemaError) as e:
+ validators.validate(12, {"type": 12})
+ self.assertRegex(
+ str(e.exception),
+ "(?s)Failed validating '.*' in metaschema.*On schema",
+ )
+
+ def test_it_uses_best_match(self):
+ schema = {
+ "oneOf": [
+ {"type": "number", "minimum": 20},
+ {"type": "array"},
+ ],
+ }
+ with self.assertRaises(exceptions.ValidationError) as e:
+ validators.validate(12, schema)
+ self.assertIn("12 is less than the minimum of 20", str(e.exception))
+
+
+class TestRefResolver(TestCase):
+
+ base_uri = ""
+ stored_uri = "foo://stored"
+ stored_schema = {"stored": "schema"}
+
+ def setUp(self):
+ self.referrer = {}
+ self.store = {self.stored_uri: self.stored_schema}
+ self.resolver = validators.RefResolver(
+ self.base_uri, self.referrer, self.store,
+ )
+
+ def test_it_does_not_retrieve_schema_urls_from_the_network(self):
+ ref = validators.Draft3Validator.META_SCHEMA["id"]
+ with mock.patch.object(self.resolver, "resolve_remote") as patched:
+ with self.resolver.resolving(ref) as resolved:
+ pass
+ self.assertEqual(resolved, validators.Draft3Validator.META_SCHEMA)
+ self.assertFalse(patched.called)
+
+ def test_it_resolves_local_refs(self):
+ ref = "#/properties/foo"
+ self.referrer["properties"] = {"foo": object()}
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, self.referrer["properties"]["foo"])
+
+ def test_it_resolves_local_refs_with_id(self):
+ schema = {"id": "http://bar/schema#", "a": {"foo": "bar"}}
+ resolver = validators.RefResolver.from_schema(
+ schema,
+ id_of=lambda schema: schema.get("id", ""),
+ )
+ with resolver.resolving("#/a") as resolved:
+ self.assertEqual(resolved, schema["a"])
+ with resolver.resolving("http://bar/schema#/a") as resolved:
+ self.assertEqual(resolved, schema["a"])
+
+ def test_it_retrieves_stored_refs(self):
+ with self.resolver.resolving(self.stored_uri) as resolved:
+ self.assertIs(resolved, self.stored_schema)
+
+ self.resolver.store["cached_ref"] = {"foo": 12}
+ with self.resolver.resolving("cached_ref#/foo") as resolved:
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_unstored_refs_via_requests(self):
+ ref = "http://bar#baz"
+ schema = {"baz": 12}
+
+ if "requests" in sys.modules:
+ self.addCleanup(
+ sys.modules.__setitem__, "requests", sys.modules["requests"],
+ )
+ sys.modules["requests"] = ReallyFakeRequests({"http://bar": schema})
+
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_unstored_refs_via_urlopen(self):
+ ref = "http://bar#baz"
+ schema = {"baz": 12}
+
+ if "requests" in sys.modules:
+ self.addCleanup(
+ sys.modules.__setitem__, "requests", sys.modules["requests"],
+ )
+ sys.modules["requests"] = None
+
+ @contextmanager
+ def fake_urlopen(url):
+ self.assertEqual(url, "http://bar")
+ yield BytesIO(json.dumps(schema).encode("utf8"))
+
+ self.addCleanup(setattr, validators, "urlopen", validators.urlopen)
+ validators.urlopen = fake_urlopen
+
+ with self.resolver.resolving(ref) as resolved:
+ pass
+ self.assertEqual(resolved, 12)
+
+ def test_it_retrieves_local_refs_via_urlopen(self):
+ with tempfile.NamedTemporaryFile(delete=False, mode="wt") as tempf:
+ self.addCleanup(os.remove, tempf.name)
+ json.dump({"foo": "bar"}, tempf)
+
+ ref = "file://{}#foo".format(pathname2url(tempf.name))
+ with self.resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, "bar")
+
+ def test_it_can_construct_a_base_uri_from_a_schema(self):
+ schema = {"id": "foo"}
+ resolver = validators.RefResolver.from_schema(
+ schema,
+ id_of=lambda schema: schema.get("id", ""),
+ )
+ self.assertEqual(resolver.base_uri, "foo")
+ self.assertEqual(resolver.resolution_scope, "foo")
+ with resolver.resolving("") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("#") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("foo") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("foo#") as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_it_can_construct_a_base_uri_from_a_schema_without_id(self):
+ schema = {}
+ resolver = validators.RefResolver.from_schema(schema)
+ self.assertEqual(resolver.base_uri, "")
+ self.assertEqual(resolver.resolution_scope, "")
+ with resolver.resolving("") as resolved:
+ self.assertEqual(resolved, schema)
+ with resolver.resolving("#") as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_custom_uri_scheme_handlers(self):
+ def handler(url):
+ self.assertEqual(url, ref)
+ return schema
+
+ schema = {"foo": "bar"}
+ ref = "foo://bar"
+ resolver = validators.RefResolver("", {}, handlers={"foo": handler})
+ with resolver.resolving(ref) as resolved:
+ self.assertEqual(resolved, schema)
+
+ def test_cache_remote_on(self):
+ response = [object()]
+
+ def handler(url):
+ try:
+ return response.pop()
+ except IndexError: # pragma: no cover
+ self.fail("Response must not have been cached!")
+
+ ref = "foo://bar"
+ resolver = validators.RefResolver(
+ "", {}, cache_remote=True, handlers={"foo": handler},
+ )
+ with resolver.resolving(ref):
+ pass
+ with resolver.resolving(ref):
+ pass
+
+ def test_cache_remote_off(self):
+ response = [object()]
+
+ def handler(url):
+ try:
+ return response.pop()
+ except IndexError: # pragma: no cover
+ self.fail("Handler called twice!")
+
+ ref = "foo://bar"
+ resolver = validators.RefResolver(
+ "", {}, cache_remote=False, handlers={"foo": handler},
+ )
+ with resolver.resolving(ref):
+ pass
+
+ def test_if_you_give_it_junk_you_get_a_resolution_error(self):
+ error = ValueError("Oh no! What's this?")
+
+ def handler(url):
+ raise error
+
+ ref = "foo://bar"
+ resolver = validators.RefResolver("", {}, handlers={"foo": handler})
+ with self.assertRaises(exceptions.RefResolutionError) as err:
+ with resolver.resolving(ref):
+ self.fail("Shouldn't get this far!") # pragma: no cover
+ self.assertEqual(err.exception, exceptions.RefResolutionError(error))
+
+ def test_helpful_error_message_on_failed_pop_scope(self):
+ resolver = validators.RefResolver("", {})
+ resolver.pop_scope()
+ with self.assertRaises(exceptions.RefResolutionError) as exc:
+ resolver.pop_scope()
+ self.assertIn("Failed to pop the scope", str(exc.exception))
+
+
+def sorted_errors(errors):
+ def key(error):
+ return (
+ [str(e) for e in error.path],
+ [str(e) for e in error.schema_path],
+ )
+ return sorted(errors, key=key)
+
+
+@attr.s
+class ReallyFakeRequests:
+
+ _responses = attr.ib()
+
+ def get(self, url):
+ response = self._responses.get(url)
+ if url is None: # pragma: no cover
+ raise ValueError("Unknown URL: " + repr(url))
+ return _ReallyFakeJSONResponse(json.dumps(response))
+
+
+@attr.s
+class _ReallyFakeJSONResponse:
+
+ _response = attr.ib()
+
+ def json(self):
+ return json.loads(self._response)
diff --git a/runtime/Lib/site-packages/jsonschema/validators.py b/runtime/Lib/site-packages/jsonschema/validators.py
new file mode 100644
index 0000000000000000000000000000000000000000..66e803ea2d0bf32395744d00ccd5e4c5e71e59ff
--- /dev/null
+++ b/runtime/Lib/site-packages/jsonschema/validators.py
@@ -0,0 +1,1161 @@
+"""
+Creation and extension of validators, with implementations for existing drafts.
+"""
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Mapping, Sequence
+from functools import lru_cache
+from operator import methodcaller
+from urllib.parse import unquote, urldefrag, urljoin, urlsplit
+from urllib.request import urlopen
+from warnings import warn
+import contextlib
+import json
+import reprlib
+import typing
+import warnings
+
+from pyrsistent import m
+import attr
+
+from jsonschema import (
+ _format,
+ _legacy_validators,
+ _types,
+ _utils,
+ _validators,
+ exceptions,
+)
+
+_UNSET = _utils.Unset()
+
+_VALIDATORS: dict[str, typing.Any] = {}
+_META_SCHEMAS = _utils.URIDict()
+_VOCABULARIES: list[tuple[str, typing.Any]] = []
+
+
+def __getattr__(name):
+ if name == "ErrorTree":
+ warnings.warn(
+ "Importing ErrorTree from jsonschema.validators is deprecated. "
+ "Instead import it from jsonschema.exceptions.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ from jsonschema.exceptions import ErrorTree
+ return ErrorTree
+ elif name == "validators":
+ warnings.warn(
+ "Accessing jsonschema.validators.validators is deprecated. "
+ "Use jsonschema.validators.validator_for with a given schema.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _VALIDATORS
+ elif name == "meta_schemas":
+ warnings.warn(
+ "Accessing jsonschema.validators.meta_schemas is deprecated. "
+ "Use jsonschema.validators.validator_for with a given schema.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _META_SCHEMAS
+ raise AttributeError(f"module {__name__} has no attribute {name}")
+
+
+def validates(version):
+ """
+ Register the decorated validator for a ``version`` of the specification.
+
+ Registered validators and their meta schemas will be considered when
+ parsing :kw:`$schema` keywords' URIs.
+
+ Arguments:
+
+ version (str):
+
+ An identifier to use as the version's name
+
+ Returns:
+
+ collections.abc.Callable:
+
+ a class decorator to decorate the validator with the version
+ """
+
+ def _validates(cls):
+ _VALIDATORS[version] = cls
+ meta_schema_id = cls.ID_OF(cls.META_SCHEMA)
+ _META_SCHEMAS[meta_schema_id] = cls
+ return cls
+ return _validates
+
+
+def _id_of(schema):
+ """
+ Return the ID of a schema for recent JSON Schema drafts.
+ """
+ if schema is True or schema is False:
+ return ""
+ return schema.get("$id", "")
+
+
+def _store_schema_list():
+ if not _VOCABULARIES:
+ package = _utils.resources.files(__package__)
+ for version in package.joinpath("schemas", "vocabularies").iterdir():
+ for path in version.iterdir():
+ vocabulary = json.loads(path.read_text())
+ _VOCABULARIES.append((vocabulary["$id"], vocabulary))
+ return [
+ (id, validator.META_SCHEMA) for id, validator in _META_SCHEMAS.items()
+ ] + _VOCABULARIES
+
+
+def create(
+ meta_schema,
+ validators=(),
+ version=None,
+ type_checker=_types.draft202012_type_checker,
+ format_checker=_format.draft202012_format_checker,
+ id_of=_id_of,
+ applicable_validators=methodcaller("items"),
+):
+ """
+ Create a new validator class.
+
+ Arguments:
+
+ meta_schema (collections.abc.Mapping):
+
+ the meta schema for the new validator class
+
+ validators (collections.abc.Mapping):
+
+ a mapping from names to callables, where each callable will
+ validate the schema property with the given name.
+
+ Each callable should take 4 arguments:
+
+ 1. a validator instance,
+ 2. the value of the property being validated within the
+ instance
+ 3. the instance
+ 4. the schema
+
+ version (str):
+
+ an identifier for the version that this validator class will
+ validate. If provided, the returned validator class will
+ have its ``__name__`` set to include the version, and also
+ will have `jsonschema.validators.validates` automatically
+ called for the given version.
+
+ type_checker (jsonschema.TypeChecker):
+
+ a type checker, used when applying the :kw:`type` keyword.
+
+ If unprovided, a `jsonschema.TypeChecker` will be created
+ with a set of default types typical of JSON Schema drafts.
+
+ format_checker (jsonschema.FormatChecker):
+
+ a format checker, used when applying the :kw:`format` keyword.
+
+ If unprovided, a `jsonschema.FormatChecker` will be created
+ with a set of default formats typical of JSON Schema drafts.
+
+ id_of (collections.abc.Callable):
+
+ A function that given a schema, returns its ID.
+
+ applicable_validators (collections.abc.Callable):
+
+ A function that given a schema, returns the list of
+ applicable validators (validation keywords and callables)
+ which will be used to validate the instance.
+
+ Returns:
+
+ a new `jsonschema.protocols.Validator` class
+ """
+ # preemptively don't shadow the `Validator.format_checker` local
+ format_checker_arg = format_checker
+
+ @attr.s
+ class Validator:
+
+ VALIDATORS = dict(validators)
+ META_SCHEMA = dict(meta_schema)
+ TYPE_CHECKER = type_checker
+ FORMAT_CHECKER = format_checker_arg
+ ID_OF = staticmethod(id_of)
+
+ schema = attr.ib(repr=reprlib.repr)
+ resolver = attr.ib(default=None, repr=False)
+ format_checker = attr.ib(default=None)
+
+ def __init_subclass__(cls):
+ warnings.warn(
+ (
+ "Subclassing validator classes is not intended to "
+ "be part of their public API. A future version "
+ "will make doing so an error, as the behavior of "
+ "subclasses isn't guaranteed to stay the same "
+ "between releases of jsonschema. Instead, prefer "
+ "composition of validators, wrapping them in an object "
+ "owned entirely by the downstream library."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ def __attrs_post_init__(self):
+ if self.resolver is None:
+ self.resolver = RefResolver.from_schema(
+ self.schema,
+ id_of=id_of,
+ )
+
+ @classmethod
+ def check_schema(cls, schema, format_checker=_UNSET):
+ Validator = validator_for(cls.META_SCHEMA, default=cls)
+ if format_checker is _UNSET:
+ format_checker = Validator.FORMAT_CHECKER
+ validator = Validator(
+ schema=cls.META_SCHEMA,
+ format_checker=format_checker,
+ )
+ for error in validator.iter_errors(schema):
+ raise exceptions.SchemaError.create_from(error)
+
+ def evolve(self, **changes):
+ # Essentially reproduces attr.evolve, but may involve instantiating
+ # a different class than this one.
+ cls = self.__class__
+
+ schema = changes.setdefault("schema", self.schema)
+ NewValidator = validator_for(schema, default=cls)
+
+ for field in attr.fields(cls):
+ if not field.init:
+ continue
+ attr_name = field.name # To deal with private attributes.
+ init_name = attr_name if attr_name[0] != "_" else attr_name[1:]
+ if init_name not in changes:
+ changes[init_name] = getattr(self, attr_name)
+
+ return NewValidator(**changes)
+
+ def iter_errors(self, instance, _schema=None):
+ if _schema is not None:
+ warnings.warn(
+ (
+ "Passing a schema to Validator.iter_errors "
+ "is deprecated and will be removed in a future "
+ "release. Call validator.evolve(schema=new_schema)."
+ "iter_errors(...) instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ else:
+ _schema = self.schema
+
+ if _schema is True:
+ return
+ elif _schema is False:
+ yield exceptions.ValidationError(
+ f"False schema does not allow {instance!r}",
+ validator=None,
+ validator_value=None,
+ instance=instance,
+ schema=_schema,
+ )
+ return
+
+ scope = id_of(_schema)
+ if scope:
+ self.resolver.push_scope(scope)
+ try:
+ for k, v in applicable_validators(_schema):
+ validator = self.VALIDATORS.get(k)
+ if validator is None:
+ continue
+
+ errors = validator(self, v, instance, _schema) or ()
+ for error in errors:
+ # set details if not already set by the called fn
+ error._set(
+ validator=k,
+ validator_value=v,
+ instance=instance,
+ schema=_schema,
+ type_checker=self.TYPE_CHECKER,
+ )
+ if k not in {"if", "$ref"}:
+ error.schema_path.appendleft(k)
+ yield error
+ finally:
+ if scope:
+ self.resolver.pop_scope()
+
+ def descend(self, instance, schema, path=None, schema_path=None):
+ for error in self.evolve(schema=schema).iter_errors(instance):
+ if path is not None:
+ error.path.appendleft(path)
+ if schema_path is not None:
+ error.schema_path.appendleft(schema_path)
+ yield error
+
+ def validate(self, *args, **kwargs):
+ for error in self.iter_errors(*args, **kwargs):
+ raise error
+
+ def is_type(self, instance, type):
+ try:
+ return self.TYPE_CHECKER.is_type(instance, type)
+ except exceptions.UndefinedTypeCheck:
+ raise exceptions.UnknownType(type, instance, self.schema)
+
+ def is_valid(self, instance, _schema=None):
+ if _schema is not None:
+ warnings.warn(
+ (
+ "Passing a schema to Validator.is_valid is deprecated "
+ "and will be removed in a future release. Call "
+ "validator.evolve(schema=new_schema).is_valid(...) "
+ "instead."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self = self.evolve(schema=_schema)
+
+ error = next(self.iter_errors(instance), None)
+ return error is None
+
+ if version is not None:
+ safe = version.title().replace(" ", "").replace("-", "")
+ Validator.__name__ = Validator.__qualname__ = f"{safe}Validator"
+ Validator = validates(version)(Validator)
+
+ return Validator
+
+
+def extend(
+ validator,
+ validators=(),
+ version=None,
+ type_checker=None,
+ format_checker=None,
+):
+ """
+ Create a new validator class by extending an existing one.
+
+ Arguments:
+
+ validator (jsonschema.protocols.Validator):
+
+ an existing validator class
+
+ validators (collections.abc.Mapping):
+
+ a mapping of new validator callables to extend with, whose
+ structure is as in `create`.
+
+ .. note::
+
+ Any validator callables with the same name as an
+ existing one will (silently) replace the old validator
+ callable entirely, effectively overriding any validation
+ done in the "parent" validator class.
+
+ If you wish to instead extend the behavior of a parent's
+ validator callable, delegate and call it directly in
+ the new validator function by retrieving it using
+ ``OldValidator.VALIDATORS["validation_keyword_name"]``.
+
+ version (str):
+
+ a version for the new validator class
+
+ type_checker (jsonschema.TypeChecker):
+
+ a type checker, used when applying the :kw:`type` keyword.
+
+ If unprovided, the type checker of the extended
+ `jsonschema.protocols.Validator` will be carried along.
+
+ format_checker (jsonschema.FormatChecker):
+
+ a format checker, used when applying the :kw:`format` keyword.
+
+ If unprovided, the format checker of the extended
+ `jsonschema.protocols.Validator` will be carried along.
+
+ Returns:
+
+ a new `jsonschema.protocols.Validator` class extending the one
+ provided
+
+ .. note:: Meta Schemas
+
+ The new validator class will have its parent's meta schema.
+
+ If you wish to change or extend the meta schema in the new
+ validator class, modify ``META_SCHEMA`` directly on the returned
+ class. Note that no implicit copying is done, so a copy should
+ likely be made before modifying it, in order to not affect the
+ old validator.
+ """
+
+ all_validators = dict(validator.VALIDATORS)
+ all_validators.update(validators)
+
+ if type_checker is None:
+ type_checker = validator.TYPE_CHECKER
+ if format_checker is None:
+ format_checker = validator.FORMAT_CHECKER
+ return create(
+ meta_schema=validator.META_SCHEMA,
+ validators=all_validators,
+ version=version,
+ type_checker=type_checker,
+ format_checker=format_checker,
+ id_of=validator.ID_OF,
+ )
+
+
+Draft3Validator = create(
+ meta_schema=_utils.load_schema("draft3"),
+ validators={
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "dependencies": _legacy_validators.dependencies_draft3,
+ "disallow": _legacy_validators.disallow_draft3,
+ "divisibleBy": _validators.multipleOf,
+ "enum": _validators.enum,
+ "extends": _legacy_validators.extends_draft3,
+ "format": _validators.format,
+ "items": _legacy_validators.items_draft3_draft4,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maximum": _legacy_validators.maximum_draft3_draft4,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minimum": _legacy_validators.minimum_draft3_draft4,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "properties": _legacy_validators.properties_draft3,
+ "type": _legacy_validators.type_draft3,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft3_type_checker,
+ format_checker=_format.draft3_format_checker,
+ version="draft3",
+ id_of=_legacy_validators.id_of_ignore_ref(property="id"),
+ applicable_validators=_legacy_validators.ignore_ref_siblings,
+)
+
+Draft4Validator = create(
+ meta_schema=_utils.load_schema("draft4"),
+ validators={
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "allOf": _validators.allOf,
+ "anyOf": _validators.anyOf,
+ "dependencies": _legacy_validators.dependencies_draft4_draft6_draft7,
+ "enum": _validators.enum,
+ "format": _validators.format,
+ "items": _legacy_validators.items_draft3_draft4,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maxProperties": _validators.maxProperties,
+ "maximum": _legacy_validators.maximum_draft3_draft4,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minProperties": _validators.minProperties,
+ "minimum": _legacy_validators.minimum_draft3_draft4,
+ "multipleOf": _validators.multipleOf,
+ "not": _validators.not_,
+ "oneOf": _validators.oneOf,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "properties": _validators.properties,
+ "required": _validators.required,
+ "type": _validators.type,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft4_type_checker,
+ format_checker=_format.draft4_format_checker,
+ version="draft4",
+ id_of=_legacy_validators.id_of_ignore_ref(property="id"),
+ applicable_validators=_legacy_validators.ignore_ref_siblings,
+)
+
+Draft6Validator = create(
+ meta_schema=_utils.load_schema("draft6"),
+ validators={
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "allOf": _validators.allOf,
+ "anyOf": _validators.anyOf,
+ "const": _validators.const,
+ "contains": _legacy_validators.contains_draft6_draft7,
+ "dependencies": _legacy_validators.dependencies_draft4_draft6_draft7,
+ "enum": _validators.enum,
+ "exclusiveMaximum": _validators.exclusiveMaximum,
+ "exclusiveMinimum": _validators.exclusiveMinimum,
+ "format": _validators.format,
+ "items": _legacy_validators.items_draft6_draft7_draft201909,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maxProperties": _validators.maxProperties,
+ "maximum": _validators.maximum,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minProperties": _validators.minProperties,
+ "minimum": _validators.minimum,
+ "multipleOf": _validators.multipleOf,
+ "not": _validators.not_,
+ "oneOf": _validators.oneOf,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "properties": _validators.properties,
+ "propertyNames": _validators.propertyNames,
+ "required": _validators.required,
+ "type": _validators.type,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft6_type_checker,
+ format_checker=_format.draft6_format_checker,
+ version="draft6",
+ id_of=_legacy_validators.id_of_ignore_ref(),
+ applicable_validators=_legacy_validators.ignore_ref_siblings,
+)
+
+Draft7Validator = create(
+ meta_schema=_utils.load_schema("draft7"),
+ validators={
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "allOf": _validators.allOf,
+ "anyOf": _validators.anyOf,
+ "const": _validators.const,
+ "contains": _legacy_validators.contains_draft6_draft7,
+ "dependencies": _legacy_validators.dependencies_draft4_draft6_draft7,
+ "enum": _validators.enum,
+ "exclusiveMaximum": _validators.exclusiveMaximum,
+ "exclusiveMinimum": _validators.exclusiveMinimum,
+ "format": _validators.format,
+ "if": _validators.if_,
+ "items": _legacy_validators.items_draft6_draft7_draft201909,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maxProperties": _validators.maxProperties,
+ "maximum": _validators.maximum,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minProperties": _validators.minProperties,
+ "minimum": _validators.minimum,
+ "multipleOf": _validators.multipleOf,
+ "not": _validators.not_,
+ "oneOf": _validators.oneOf,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "properties": _validators.properties,
+ "propertyNames": _validators.propertyNames,
+ "required": _validators.required,
+ "type": _validators.type,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft7_type_checker,
+ format_checker=_format.draft7_format_checker,
+ version="draft7",
+ id_of=_legacy_validators.id_of_ignore_ref(),
+ applicable_validators=_legacy_validators.ignore_ref_siblings,
+)
+
+Draft201909Validator = create(
+ meta_schema=_utils.load_schema("draft2019-09"),
+ validators={
+ "$recursiveRef": _legacy_validators.recursiveRef,
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "allOf": _validators.allOf,
+ "anyOf": _validators.anyOf,
+ "const": _validators.const,
+ "contains": _validators.contains,
+ "dependentRequired": _validators.dependentRequired,
+ "dependentSchemas": _validators.dependentSchemas,
+ "enum": _validators.enum,
+ "exclusiveMaximum": _validators.exclusiveMaximum,
+ "exclusiveMinimum": _validators.exclusiveMinimum,
+ "format": _validators.format,
+ "if": _validators.if_,
+ "items": _legacy_validators.items_draft6_draft7_draft201909,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maxProperties": _validators.maxProperties,
+ "maximum": _validators.maximum,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minProperties": _validators.minProperties,
+ "minimum": _validators.minimum,
+ "multipleOf": _validators.multipleOf,
+ "not": _validators.not_,
+ "oneOf": _validators.oneOf,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "properties": _validators.properties,
+ "propertyNames": _validators.propertyNames,
+ "required": _validators.required,
+ "type": _validators.type,
+ "unevaluatedItems": _legacy_validators.unevaluatedItems_draft2019,
+ "unevaluatedProperties": _validators.unevaluatedProperties,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft201909_type_checker,
+ format_checker=_format.draft201909_format_checker,
+ version="draft2019-09",
+)
+
+Draft202012Validator = create(
+ meta_schema=_utils.load_schema("draft2020-12"),
+ validators={
+ "$dynamicRef": _validators.dynamicRef,
+ "$ref": _validators.ref,
+ "additionalItems": _validators.additionalItems,
+ "additionalProperties": _validators.additionalProperties,
+ "allOf": _validators.allOf,
+ "anyOf": _validators.anyOf,
+ "const": _validators.const,
+ "contains": _validators.contains,
+ "dependentRequired": _validators.dependentRequired,
+ "dependentSchemas": _validators.dependentSchemas,
+ "enum": _validators.enum,
+ "exclusiveMaximum": _validators.exclusiveMaximum,
+ "exclusiveMinimum": _validators.exclusiveMinimum,
+ "format": _validators.format,
+ "if": _validators.if_,
+ "items": _validators.items,
+ "maxItems": _validators.maxItems,
+ "maxLength": _validators.maxLength,
+ "maxProperties": _validators.maxProperties,
+ "maximum": _validators.maximum,
+ "minItems": _validators.minItems,
+ "minLength": _validators.minLength,
+ "minProperties": _validators.minProperties,
+ "minimum": _validators.minimum,
+ "multipleOf": _validators.multipleOf,
+ "not": _validators.not_,
+ "oneOf": _validators.oneOf,
+ "pattern": _validators.pattern,
+ "patternProperties": _validators.patternProperties,
+ "prefixItems": _validators.prefixItems,
+ "properties": _validators.properties,
+ "propertyNames": _validators.propertyNames,
+ "required": _validators.required,
+ "type": _validators.type,
+ "unevaluatedItems": _validators.unevaluatedItems,
+ "unevaluatedProperties": _validators.unevaluatedProperties,
+ "uniqueItems": _validators.uniqueItems,
+ },
+ type_checker=_types.draft202012_type_checker,
+ format_checker=_format.draft202012_format_checker,
+ version="draft2020-12",
+)
+
+_LATEST_VERSION = Draft202012Validator
+
+
+class RefResolver:
+ """
+ Resolve JSON References.
+
+ Arguments:
+
+ base_uri (str):
+
+ The URI of the referring document
+
+ referrer:
+
+ The actual referring document
+
+ store (dict):
+
+ A mapping from URIs to documents to cache
+
+ cache_remote (bool):
+
+ Whether remote refs should be cached after first resolution
+
+ handlers (dict):
+
+ A mapping from URI schemes to functions that should be used
+ to retrieve them
+
+ urljoin_cache (:func:`functools.lru_cache`):
+
+ A cache that will be used for caching the results of joining
+ the resolution scope to subscopes.
+
+ remote_cache (:func:`functools.lru_cache`):
+
+ A cache that will be used for caching the results of
+ resolved remote URLs.
+
+ Attributes:
+
+ cache_remote (bool):
+
+ Whether remote refs should be cached after first resolution
+ """
+
+ def __init__(
+ self,
+ base_uri,
+ referrer,
+ store=m(),
+ cache_remote=True,
+ handlers=(),
+ urljoin_cache=None,
+ remote_cache=None,
+ ):
+ if urljoin_cache is None:
+ urljoin_cache = lru_cache(1024)(urljoin)
+ if remote_cache is None:
+ remote_cache = lru_cache(1024)(self.resolve_from_url)
+
+ self.referrer = referrer
+ self.cache_remote = cache_remote
+ self.handlers = dict(handlers)
+
+ self._scopes_stack = [base_uri]
+
+ self.store = _utils.URIDict(_store_schema_list())
+ self.store.update(store)
+ self.store.update(
+ (schema["$id"], schema)
+ for schema in store.values()
+ if isinstance(schema, Mapping) and "$id" in schema
+ )
+ self.store[base_uri] = referrer
+
+ self._urljoin_cache = urljoin_cache
+ self._remote_cache = remote_cache
+
+ @classmethod
+ def from_schema(cls, schema, id_of=_id_of, *args, **kwargs):
+ """
+ Construct a resolver from a JSON schema object.
+
+ Arguments:
+
+ schema:
+
+ the referring schema
+
+ Returns:
+
+ `RefResolver`
+ """
+
+ return cls(base_uri=id_of(schema), referrer=schema, *args, **kwargs) # noqa: B026, E501
+
+ def push_scope(self, scope):
+ """
+ Enter a given sub-scope.
+
+ Treats further dereferences as being performed underneath the
+ given scope.
+ """
+ self._scopes_stack.append(
+ self._urljoin_cache(self.resolution_scope, scope),
+ )
+
+ def pop_scope(self):
+ """
+ Exit the most recent entered scope.
+
+ Treats further dereferences as being performed underneath the
+ original scope.
+
+ Don't call this method more times than `push_scope` has been
+ called.
+ """
+ try:
+ self._scopes_stack.pop()
+ except IndexError:
+ raise exceptions.RefResolutionError(
+ "Failed to pop the scope from an empty stack. "
+ "`pop_scope()` should only be called once for every "
+ "`push_scope()`",
+ )
+
+ @property
+ def resolution_scope(self):
+ """
+ Retrieve the current resolution scope.
+ """
+ return self._scopes_stack[-1]
+
+ @property
+ def base_uri(self):
+ """
+ Retrieve the current base URI, not including any fragment.
+ """
+ uri, _ = urldefrag(self.resolution_scope)
+ return uri
+
+ @contextlib.contextmanager
+ def in_scope(self, scope):
+ """
+ Temporarily enter the given scope for the duration of the context.
+
+ .. deprecated:: v4.0.0
+ """
+ warnings.warn(
+ "jsonschema.RefResolver.in_scope is deprecated and will be "
+ "removed in a future release.",
+ DeprecationWarning,
+ stacklevel=3,
+ )
+ self.push_scope(scope)
+ try:
+ yield
+ finally:
+ self.pop_scope()
+
+ @contextlib.contextmanager
+ def resolving(self, ref):
+ """
+ Resolve the given ``ref`` and enter its resolution scope.
+
+ Exits the scope on exit of this context manager.
+
+ Arguments:
+
+ ref (str):
+
+ The reference to resolve
+ """
+
+ url, resolved = self.resolve(ref)
+ self.push_scope(url)
+ try:
+ yield resolved
+ finally:
+ self.pop_scope()
+
+ def _find_in_referrer(self, key):
+ return self._get_subschemas_cache()[key]
+
+ @lru_cache() # noqa: B019
+ def _get_subschemas_cache(self):
+ cache = {key: [] for key in _SUBSCHEMAS_KEYWORDS}
+ for keyword, subschema in _search_schema(
+ self.referrer, _match_subschema_keywords,
+ ):
+ cache[keyword].append(subschema)
+ return cache
+
+ @lru_cache() # noqa: B019
+ def _find_in_subschemas(self, url):
+ subschemas = self._get_subschemas_cache()["$id"]
+ if not subschemas:
+ return None
+ uri, fragment = urldefrag(url)
+ for subschema in subschemas:
+ target_uri = self._urljoin_cache(
+ self.resolution_scope, subschema["$id"],
+ )
+ if target_uri.rstrip("/") == uri.rstrip("/"):
+ if fragment:
+ subschema = self.resolve_fragment(subschema, fragment)
+ self.store[url] = subschema
+ return url, subschema
+ return None
+
+ def resolve(self, ref):
+ """
+ Resolve the given reference.
+ """
+ url = self._urljoin_cache(self.resolution_scope, ref).rstrip("/")
+
+ match = self._find_in_subschemas(url)
+ if match is not None:
+ return match
+
+ return url, self._remote_cache(url)
+
+ def resolve_from_url(self, url):
+ """
+ Resolve the given URL.
+ """
+ url, fragment = urldefrag(url)
+ if not url:
+ url = self.base_uri
+
+ try:
+ document = self.store[url]
+ except KeyError:
+ try:
+ document = self.resolve_remote(url)
+ except Exception as exc:
+ raise exceptions.RefResolutionError(exc)
+
+ return self.resolve_fragment(document, fragment)
+
+ def resolve_fragment(self, document, fragment):
+ """
+ Resolve a ``fragment`` within the referenced ``document``.
+
+ Arguments:
+
+ document:
+
+ The referent document
+
+ fragment (str):
+
+ a URI fragment to resolve within it
+ """
+
+ fragment = fragment.lstrip("/")
+
+ if not fragment:
+ return document
+
+ if document is self.referrer:
+ find = self._find_in_referrer
+ else:
+
+ def find(key):
+ yield from _search_schema(document, _match_keyword(key))
+
+ for keyword in ["$anchor", "$dynamicAnchor"]:
+ for subschema in find(keyword):
+ if fragment == subschema[keyword]:
+ return subschema
+ for keyword in ["id", "$id"]:
+ for subschema in find(keyword):
+ if "#" + fragment == subschema[keyword]:
+ return subschema
+
+ # Resolve via path
+ parts = unquote(fragment).split("/") if fragment else []
+ for part in parts:
+ part = part.replace("~1", "/").replace("~0", "~")
+
+ if isinstance(document, Sequence):
+ # Array indexes should be turned into integers
+ try:
+ part = int(part)
+ except ValueError:
+ pass
+ try:
+ document = document[part]
+ except (TypeError, LookupError):
+ raise exceptions.RefResolutionError(
+ f"Unresolvable JSON pointer: {fragment!r}",
+ )
+
+ return document
+
+ def resolve_remote(self, uri):
+ """
+ Resolve a remote ``uri``.
+
+ If called directly, does not check the store first, but after
+ retrieving the document at the specified URI it will be saved in
+ the store if :attr:`cache_remote` is True.
+
+ .. note::
+
+ If the requests_ library is present, ``jsonschema`` will use it to
+ request the remote ``uri``, so that the correct encoding is
+ detected and used.
+
+ If it isn't, or if the scheme of the ``uri`` is not ``http`` or
+ ``https``, UTF-8 is assumed.
+
+ Arguments:
+
+ uri (str):
+
+ The URI to resolve
+
+ Returns:
+
+ The retrieved document
+
+ .. _requests: https://pypi.org/project/requests/
+ """
+ try:
+ import requests
+ except ImportError:
+ requests = None
+
+ scheme = urlsplit(uri).scheme
+
+ if scheme in self.handlers:
+ result = self.handlers[scheme](uri)
+ elif scheme in ["http", "https"] and requests:
+ # Requests has support for detecting the correct encoding of
+ # json over http
+ result = requests.get(uri).json()
+ else:
+ # Otherwise, pass off to urllib and assume utf-8
+ with urlopen(uri) as url:
+ result = json.loads(url.read().decode("utf-8"))
+
+ if self.cache_remote:
+ self.store[uri] = result
+ return result
+
+
+_SUBSCHEMAS_KEYWORDS = ("$id", "id", "$anchor", "$dynamicAnchor")
+
+
+def _match_keyword(keyword):
+
+ def matcher(value):
+ if keyword in value:
+ yield value
+
+ return matcher
+
+
+def _match_subschema_keywords(value):
+ for keyword in _SUBSCHEMAS_KEYWORDS:
+ if keyword in value:
+ yield keyword, value
+
+
+def _search_schema(schema, matcher):
+ """Breadth-first search routine."""
+ values = deque([schema])
+ while values:
+ value = values.pop()
+ if not isinstance(value, dict):
+ continue
+ yield from matcher(value)
+ values.extendleft(value.values())
+
+
+def validate(instance, schema, cls=None, *args, **kwargs):
+ """
+ Validate an instance under the given schema.
+
+ >>> validate([2, 3, 4], {"maxItems": 2})
+ Traceback (most recent call last):
+ ...
+ ValidationError: [2, 3, 4] is too long
+
+ :func:`~jsonschema.validators.validate` will first verify that the
+ provided schema is itself valid, since not doing so can lead to less
+ obvious error messages and fail in less obvious or consistent ways.
+
+ If you know you have a valid schema already, especially
+ if you intend to validate multiple instances with
+ the same schema, you likely would prefer using the
+ `jsonschema.protocols.Validator.validate` method directly on a
+ specific validator (e.g. ``Draft20212Validator.validate``).
+
+
+ Arguments:
+
+ instance:
+
+ The instance to validate
+
+ schema:
+
+ The schema to validate with
+
+ cls (jsonschema.protocols.Validator):
+
+ The class that will be used to validate the instance.
+
+ If the ``cls`` argument is not provided, two things will happen
+ in accordance with the specification. First, if the schema has a
+ :kw:`$schema` keyword containing a known meta-schema [#]_ then the
+ proper validator will be used. The specification recommends that
+ all schemas contain :kw:`$schema` properties for this reason. If no
+ :kw:`$schema` property is found, the default validator class is the
+ latest released draft.
+
+ Any other provided positional and keyword arguments will be passed
+ on when instantiating the ``cls``.
+
+ Raises:
+
+ `jsonschema.exceptions.ValidationError`:
+
+ if the instance is invalid
+
+ `jsonschema.exceptions.SchemaError`:
+
+ if the schema itself is invalid
+
+ .. rubric:: Footnotes
+ .. [#] known by a validator registered with
+ `jsonschema.validators.validates`
+ """
+ if cls is None:
+ cls = validator_for(schema)
+
+ cls.check_schema(schema)
+ validator = cls(schema, *args, **kwargs)
+ error = exceptions.best_match(validator.iter_errors(instance))
+ if error is not None:
+ raise error
+
+
+def validator_for(schema, default=_UNSET):
+ """
+ Retrieve the validator class appropriate for validating the given schema.
+
+ Uses the :kw:`$schema` keyword that should be present in the given
+ schema to look up the appropriate validator class.
+
+ Arguments:
+
+ schema (collections.abc.Mapping or bool):
+
+ the schema to look at
+
+ default:
+
+ the default to return if the appropriate validator class
+ cannot be determined.
+
+ If unprovided, the default is to return the latest supported
+ draft.
+ """
+
+ DefaultValidator = _LATEST_VERSION if default is _UNSET else default
+
+ if schema is True or schema is False or "$schema" not in schema:
+ return DefaultValidator
+ if schema["$schema"] not in _META_SCHEMAS:
+ if default is _UNSET:
+ warn(
+ (
+ "The metaschema specified by $schema was not found. "
+ "Using the latest draft to validate, but this will raise "
+ "an error in the future."
+ ),
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return _META_SCHEMAS.get(schema["$schema"], DefaultValidator)
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/INSTALLER b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/LICENSE b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..da96fec5d333f372813aea6af813564fd6c553f2
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/LICENSE
@@ -0,0 +1,32 @@
+SOFTWARE LICENSE AGREEMENT FOR EVALUATION
+
+This SOFTWARE EVALUATION LICENSE AGREEMENT (this "Agreement") is a legal contract between a person who uses or otherwise accesses or installs the Software (“User(s)”), and Nippon Telegraph and Telephone corporation ("NTT").
+READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY BEFORE INSTALLING OR OTHERWISE ACCESSING OR USING NTT'S PROPRIETARY SOFTWARE ACCOMPANIED BY THIS AGREEMENT (the "SOFTWARE"). THE SOFTWARE IS COPYRIGHTED AND IT IS LICENSED TO USER UNDER THIS AGREEMENT, NOT SOLD TO USER. BY INSTALLING OR OTHERWISE ACCESSING OR USING THE SOFTWARE, USER ACKNOWLEDGES THAT USER HAS READ THIS AGREEMENT, THAT USER UNDERSTANDS IT, AND THAT USER ACCEPTS AND AGREES TO BE BOUND BY ITS TERMS. IF AT ANY TIME USER IS NOT WILLING TO BE BOUND BY THE TERMS OF THIS AGREEMENT, USER SHOULD TERMINATE THE INSTALLATION PROCESS, IMMEDIATELY CEASE AND REFRAIN FROM ACCESSING OR USING THE SOFTWARE AND DELETE ANY COPIES USER MAY HAVE. THIS AGREEMENT REPRESENTS THE ENTIRE AGREEMENT BETWEEN USER AND NTT CONCERNING THE SOFTWARE.
+
+
+BACKGROUND
+A. NTT is the owner of all rights, including all patent rights, and copyrights in and to the Software and related documentation listed in Exhibit A to this Agreement.
+B. User wishes to obtain a royalty free license to use the Software to enable User to evaluate, and NTT wishes to grant such a license to User, pursuant and subject to the terms and conditions of this Agreement.
+C. As a condition to NTT's provision of the Software to User, NTT has required User to execute this Agreement.
+In consideration of these premises, and the mutual promises and conditions in this Agreement, the parties hereby agree as follows:
+1. Grant of Evaluation License. NTT hereby grants to User, and User hereby accepts, under the terms and conditions of this Agreement, a royalty free, nontransferable and nonexclusive license to use the Software internally for the purposes of testing, analyzing, and evaluating the methods or mechanisms as shown in "NTT Neural Machine Translation Systems at WAT 2017, Morishita et al., WAT 2017". User may make a reasonable number of backup copies of the Software solely for User's internal use pursuant to the license granted in this Section 1.
+2. Shipment and Installation. NTT will ship or deliver the Software by any method that NTT deems appropriate. User shall be solely responsible for proper installation of the Software.
+3. Term. This Agreement is effective whichever is earlier (i) upon User’s acceptance of the Agreement, or (ii) upon User’s installing, accessing, and using the Software, even if User has not expressly accepted this Agreement. Without prejudice to any other rights, NTT may terminate this Agreement without notice to User. User may terminate this Agreement at any time by User’s decision to terminate the Agreement to NTT and ceasing use of the Software. Upon any termination or expiration of this Agreement for any reason, User agrees to uninstall the Software and destroy all copies of the Software.
+4. Proprietary Rights
+(a) The Software is the valuable and proprietary property of NTT, and NTT shall retain exclusive title to this property both during the term and after the termination of this Agreement. Without limitation, User acknowledges that all patent rights and copyrights in the Software shall remain the exclusive property of NTT at all times. User shall use not less than reasonable care in safeguarding the confidentiality of the Software.
+(b) USER SHALL NOT, IN WHOLE OR IN PART, AT ANY TIME DURING THE TERM OF OR AFTER THE TERMINATION OF THIS AGREEMENT: (i) SELL, ASSIGN, LEASE, DISTRIBUTE, OR OTHERWISE TRANSFER THE SOFTWARE TO ANY THIRD PARTY; (ii) EXCEPT AS OTHERWISE PROVIDED HEREIN, COPY OR REPRODUCE THE SOFTWARE IN ANY MANNER; OR (iii) ALLOW ANY PERSON OR ENTITY TO COMMIT ANY OF THE ACTIONS DESCRIBED IN (i) THROUGH (ii) ABOVE.
+(c) User shall take appropriate action, by instruction, agreement, or otherwise, with respect to its employees permitted under this Agreement to have access to the Software to ensure that all of User's obligations under this Section 4 shall be satisfied.
+5. Indemnity. User shall defend, indemnify and hold harmless NTT, its agents and employees, from any loss, damage, or liability arising in connection with User's improper or unauthorized use of the Software. NTT SHALL HAVE THE SOLE RIGHT TO CONDUCT DEFEND ANY ACTTION RELATING TO THE SOFTWARE.
+6. Disclaimer. THE SOFTWARE IS LICENSED TO USER "AS IS," WITHOUT ANY TRAINING, MAINTENANCE, OR SERVICE OBLIGATIONS WHATSOEVER ON THE PART OF NTT. NTT MAKES NO EXPRESS OR IMPLIED WARRANTIES OF ANY TYPE WHATSOEVER, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR PURPOSE AND OF NON-INFRINGEMENT ON COPYRIGHT OR ANY OTHER RIGHT OF THIRD PARTIES. USER ASSUMES ALL RISKS ASSOCIATED WITH ITS USE OF THE SOFTWARE, INCLUDING WITHOUT LIMITATION RISKS RELATING TO QUALITY, PERFORMANCE, DATA LOSS, AND UTILITY IN A PRODUCTION ENVIRONMENT.
+7. Limitation of Liability. IN NO EVENT SHALL NTT BE LIABLE TO USER OR TO ANY THIRD PARTY FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING BUT NOT LIMITED TO DAMAGES FOR PERSONAL INJURY, PROPERTY DAMAGE, LOST PROFITS, OR OTHER ECONOMIC LOSS, ARISING IN CONNECTION WITH USER'S USE OF OR INABILITY TO USE THE SOFTWARE, IN CONNECTION WITH NTT'S PROVISION OF OR FAILURE TO PROVIDE SERVICES PERTAINING TO THE SOFTWARE, OR AS A RESULT OF ANY DEFECT IN THE SOFTWARE. THIS DISCLAIMER OF LIABILITY SHALL APPLY REGARD¬LESS OF THE FORM OF ACTION THAT MAY BE BROUGHT AGAINST NTT, WHETHER IN CONTRACT OR TORT, INCLUDING WITHOUT LIMITATION ANY ACTION FOR NEGLIGENCE. USER'S SOLE REMEDY IN THE EVENT OF ANY BREACH OF THIS AGREEMENT BY NTT SHALL BE TERMINATION PURSUANT TO SECTION 3.
+8. No Assignment or Sublicense. Neither this Agreement nor any right or license under this Agreement, nor the Software, may be sublicensed, assigned, or otherwise transferred by User without NTT's prior written consent.
+9. General
+(a) If any provision, or part of a provision, of this Agreement is or becomes illegal, unenforceable, or invalidated, by operation of law or otherwise, that provision or part shall to that extent be deemed omitted, and the remainder of this Agreement shall remain in full force and effect.
+(b) This Agreement is the complete and exclusive statement of the agreement between the parties with respect to the subject matter hereof, and supersedes all written and oral contracts, proposals, and other communications between the parties relating to that subject matter.
+(c) Subject to Section 8, this Agreement shall be binding on, and shall inure to the benefit of, the respective successors and assigns of NTT and User.
+(d) If either party to this Agreement initiates a legal action or proceeding to enforce or interpret any part of this Agreement, the prevailing party in such action shall be entitled to recover, as an element of the costs of such action and not as damages, its attorneys' fees and other costs associated with such action or proceeding.
+(e) This Agreement shall be governed by and interpreted under the laws of Japan, without reference to conflicts of law principles. All disputes arising out of or in connection with this Agreement shall be finally settled by arbitration in Tokyo in accordance with the Commercial Arbitration Rules of the Japan Commercial Arbitration Association. The arbitration shall be conducted by three (3) arbitrators and in Japanese. The award rendered by the arbitrators shall be final and binding upon the parties. Judgment upon the award may be entered in any court having jurisdiction thereof.
+(f) NTT shall not be liable to the User or to any third party for any delay or failure to perform NTT’s obligation set forth under this Agreement due to any cause beyond NTT’s reasonable control.
+
+EXHIBIT A
+
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/METADATA b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..fb776090f5da0f58e8961043402c699b3cfd0b06
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/METADATA
@@ -0,0 +1,468 @@
+Metadata-Version: 2.1
+Name: kaldiio
+Version: 2.18.0
+Summary: Kaldi-ark loading and writing module
+Home-page: https://github.com/nttcslab-sp/kaldiio
+Author: nttcslab-sp
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Science/Research
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.5
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Topic :: Multimedia :: Sound/Audio :: Analysis
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: numpy
+
+# Kaldiio
+[](https://pypi.python.org/pypi/kaldiio)
+[](https://pypi.python.org/pypi/kaldiio)
+[](https://codecov.io/gh/nttcslab-sp/kaldiio)
+
+A pure python module for reading and writing kaldi ark files
+
+- [Introduction](#introduction)
+ - [What is this? What are `ark` and `scp`?](#what-is-this-what-are-ark-and-scp)
+ - [Features](#features)
+ - [Similar projects](#similar-projects)
+- [Install](#install)
+- [Usage](#usage)
+ - [ReadHelper](#readhelper)
+ - [WriteHelper](#writehelper)
+- [More low level API](#more-low-level-api)
+
+## Introduction
+### What are `ark` and `scp`?
+`kaldiio` is an IO utility implemented in pure Python language for several file formats used in [kaldi](https://github.com/kaldi-asr/kaldi), which are named as`ark` and `scp`. `ark` and `scp` are used in in order to archive some objects defined in Kaldi, typically it is Matrix object of Kaldi.
+
+In this section, we describe the basic concept of `ark` and `scp`. More detail about the File-IO in `Kaldi-asr`: http://kaldi-asr.org/doc/io.html
+
+
+#### Basic of File IO in kaldi: Ark and copy-feats
+`ark` is an archive format to save any `Kaldi objects`. This library mainly support `KaldiMatrix/KaldiVector`.
+This ia an example of ark file of KaldiMatrix: [ark file](tests/arks/test.ark)
+
+If you have `Kaldi`, you can convert it to text format as following
+
+```bash
+# copy-feats
+copy-feats ark:test.ark ark,t:text.ark
+```
+
+
+`copy-feats` is designed to have high affinity with unix command line:
+
+1. `ark` can be flushed to and from unix pipe.
+
+ cat test.ark | copy-feats ark:- ark,t:- | less # Show the contents in the ark
+ `-` indicates standard input stream or output stream.
+1. Unix command can be used as `read-specifier` and `wspecifier`
+
+ copy-feats ark:'gunzip -c some.ark.gz |' ark:some.ark
+
+#### Scp file
+`scp` is a text file such as,
+
+```
+uttid1 /some/where/feats.ark:123
+uttid2 /some/where/feats.ark:156
+uttid3 /some/where/feats.ark:245
+```
+The first column, `uttid1`, indicates the utterance id and the second, `/some/where/feats.ark:123`, is the file path of matrix/vector of kaldi formats. The number after colon is a starting addressof the object of the file.
+
+`scp` looks very simple format, but has several powerful features.
+
+1. Mutual conversion between`ark` and `scp`
+
+ copy-feats scp:foo.scp ark:foo.ark # scp -> ark
+ copy-feats ark:foo.ark ark,scp:bar.ark,bar.scp # ark -> ark,scp
+
+1. Unix command can be used insead of direct file path
+
+ For example, the following scp file can be also used.
+
+ uttid1 cat /some/where/feats1.mat |
+ uttid2 cat /some/where/feats2.mat |
+ uttid3 cat /some/where/feats3.mat |
+
+#### wav.scp
+`wav.scp` is a `scp` to describe wave file paths.
+
+```
+uttid1 /some/path/a.wav
+uttid2 /some/path/b.wav
+uttid3 /some/path/c.wav
+```
+
+`wav.scp` is also can be embeded unix command as normal scp file. This is often used for converting file format in kaldi recipes.
+
+```
+uttid1 sph2pipe -f wav /some/path/a.wv1 |
+uttid2 sph2pipe -f wav /some/path/b.wv1 |
+uttid3 sph2pipe -f wav /some/path/c.wv1 |
+```
+
+### Features
+Kaldiio supports:
+
+- Read/Write for archive formats: ark, scp
+ - Binary/Text - Float/Double Matrix: DM, FM
+ - Binary/Text - Float/Double Vector: DV, FV
+ - Compressed Matrix for loading: CM, CM2, CM3
+ - Compressed Matrix for writing: All compressoin_method are supported: 1,2,3,4,5,6,7
+ - Binary/Text for Int-vector, typically used for `ali` files.
+- Read/Write via a pipe: e.g. "ark: cat feats.ark |"
+- Read wav.scp / wav.ark
+- (New!) Some extended ark format **not supported** in Kaldi originally.
+ - The ark file for numpy, pickle, wav, flac files.
+
+The followings are **not supported**
+
+- Write in existing scp file
+- NNet2/NNet3 egs
+- Lattice file
+
+### Similar projects
+- Python-C++ binding
+ - https://github.com/pykaldi/pykaldi
+ - Looks great. I recommend pykaldi if you aren't particular about pure python.
+ - https://github.com/janchorowski/kaldi-python/
+ - Maybe not enough maintained now.
+ - https://github.com/t13m/kaldi-readers-for-tensorflow
+ - Ark reader for tensorflow
+ - https://github.com/csukuangfj/kaldi_native_io
+ - Implemented in C++
+ - Have interface for Python
+ - Support all types of `rspecifier` and `wspecifier`
+ - Have a uniform interface for writing, sequential reading, and random access reading
+ - `pip install kaldi_native_io`
+- Pure Python
+ - https://github.com/vesis84/kaldi-io-for-python
+ - `kaldiio` is based on this module, but `kaldiio` supports more features than it.
+ - https://github.com/funcwj/kaldi-python-io
+ - Python>=3.6. `nnet3-egs`is also supported.
+
+## Install
+
+```bash
+pip install kaldiio
+```
+
+## Usage
+`kaldiio` doesn't distinguish the API for each kaldi-objects, i.e.
+`Kaldi-Matrix`, `Kaldi-Vector`, not depending on whether it is binary or text, or compressed or not,
+can be handled by the same API.
+
+### ReadHelper
+`ReadHelper` supports sequential accessing for `scp` or `ark`. If you need to access randomly, then use `kaldiio.load_scp`.
+
+
+- Read matrix-scp
+
+```python
+from kaldiio import ReadHelper
+with ReadHelper('scp:file.scp') as reader:
+ for key, numpy_array in reader:
+ ...
+```
+
+
+- Read gziped ark
+
+```python
+from kaldiio import ReadHelper
+with ReadHelper('ark: gunzip -c file.ark.gz |') as reader:
+ for key, numpy_array in reader:
+ ...
+
+# Ali file
+with ReadHelper('ark: gunzip -c exp/tri3_ali/ali.*.gz |') as reader:
+ for key, numpy_array in reader:
+ ...
+```
+
+
+- Read wav.scp
+
+```python
+from kaldiio import ReadHelper
+with ReadHelper('scp:wav.scp') as reader:
+ for key, (rate, numpy_array) in reader:
+ ...
+```
+
+ - v2.11.0: Removed `wav` option. You can load `wav.scp` without any addtional argument.
+
+- Read wav.scp with segments
+
+```python
+from kaldiio import ReadHelper
+with ReadHelper('scp:wav.scp', segments='segments') as reader
+ for key, (rate, numpy_array) in reader:
+ ...
+```
+
+- Read from stdin
+
+```python
+from kaldiio import ReadHelper
+with ReadHelper('ark:-') as reader:
+ for key, numpy_array in reader:
+ ...
+```
+
+### WriteHelper
+- Write matrices and vectors in a ark with scp
+
+```python
+import numpy
+from kaldiio import WriteHelper
+with WriteHelper('ark,scp:file.ark,file.scp') as writer:
+ for i in range(10):
+ writer(str(i), numpy.random.randn(10, 10))
+ # The following is equivalent
+ # writer[str(i)] = numpy.random.randn(10, 10)
+```
+
+- Write in compressed matrix
+
+```python
+import numpy
+from kaldiio import WriteHelper
+with WriteHelper('ark:file.ark', compression_method=2) as writer:
+ for i in range(10):
+ writer(str(i), numpy.random.randn(10, 10))
+```
+
+- Write matrices in text
+
+```python
+import numpy
+from kaldiio import WriteHelper
+with WriteHelper('ark,t:file.ark') as writer:
+ for i in range(10):
+ writer(str(i), numpy.random.randn(10, 10))
+```
+
+- Write in gziped ark
+
+```python
+import numpy
+from kaldiio import WriteHelper
+with WriteHelper('ark:| gzip -c > file.ark.gz') as writer:
+ for i in range(10):
+ writer(str(i), numpy.random.randn(10, 10))
+```
+- Write matrice to stdout
+
+```python
+import numpy
+from kaldiio import WriteHelper
+with WriteHelper('ark:-') as writer:
+ for i in range(10):
+ writer(str(i), numpy.random.randn(10, 10))
+```
+
+
+- (New!) Extended ark format using numpy, pickle, soundfile
+
+```python
+import numpy
+from kaldiio import WriteHelper
+
+# NPY ARK
+with WriteHelper('ark:-', write_function="numpy") as writer:
+ writer("foo", numpy.random.randn(10, 10))
+
+# PICKLE ARK
+with WriteHelper('ark:-', write_function="pickle") as writer:
+ writer("foo", numpy.random.randn(10, 10))
+
+# FLAC ARK
+with WriteHelper('ark:-', write_function="soundfile_flac") as writer:
+ writer("foo", numpy.random.randn(1000))
+```
+
+Note that `soundfile` is an optional module and you need to install it to use this feature.
+
+```sh
+pip install soundfile
+```
+
+## More low level API
+`WriteHelper` and `ReadHelper` are high level wrapper of the following API to support kaldi style arguments.
+
+### load_ark
+
+```python
+import kaldiio
+
+d = kaldiio.load_ark('a.ark') # d is a generator object
+for key, numpy_array in d:
+ ...
+
+# === load_ark can accepts file descriptor, too
+with open('a.ark') as fd:
+ for key, numpy_array in kaldiio.load_ark(fd):
+ ...
+
+# === Use with open_like_kaldi
+from kaldiio import open_like_kaldi
+with open_like_kaldi('gunzip -c file.ark.gz |', 'r') as f:
+ for key, numpy_array in kaldiio.load_ark(fd):
+ ...
+```
+
+- `load_ark` can load both matrices of ark and vectors of ark and also, it can be both text and binary.
+
+### load_scp
+`load_scp` creates "lazy dict", i.e.
+The data are loaded in memory when accessing the element.
+
+```python
+import kaldiio
+
+d = kaldiio.load_scp('a.scp')
+for key in d:
+ numpy_array = d[key]
+
+
+with open('a.scp') as fd:
+ kaldiio.load_scp(fd)
+
+d = kaldiio.load_scp('data/train/wav.scp', segments='data/train/segments')
+for key in d:
+ rate, numpy_array = d[key]
+```
+
+The object created by `load_scp` is a dict-like object, thus it has methods of `dict`.
+
+```python
+import kaldiio
+d = kaldiio.load_scp('a.scp')
+d.keys()
+d.items()
+d.values()
+'uttid' in d
+d.get('uttid')
+```
+
+### load_scp_sequential (from v2.13.0)
+
+`load_scp_sequential` creates "generator" as same as `load_ark`.
+If you don't need random-accessing for each elements
+and use it just to iterate for whole data,
+then this method possibly performs faster than `load_scp`.
+
+```python
+import kaldiio
+d = kaldiio.load_scp_sequential('a.scp')
+for key, numpy_array in d:
+ ...
+```
+
+### load_wav_scp
+```python
+d = kaldiio.load_scp('wav.scp')
+for key in d:
+ rate, numpy_array = d[key]
+
+# Supporting "segments"
+d = kaldiio.load_scp('data/train/wav.scp', segments='data/train/segments')
+for key in d:
+ rate, numpy_array = d[key]
+```
+
+- v2.11.0: `load_wav_scp` is deprecated now. Use `load_scp`.
+
+### load_mat
+```python
+numpy_array = kaldiio.load_mat('a.mat')
+numpy_array = kaldiio.load_mat('a.ark:1134') # Seek and load
+
+# If the file is wav, gets Tuple[int, numpy.ndarray]
+rate, numpy_array = kaldiio.load_mat('a.wav')
+```
+- `load_mat` can load kaldi-matrix, kaldi-vector, and wave
+
+### save_ark
+```python
+
+# === Create ark file from numpy
+kaldiio.save_ark('b.ark', {'key': numpy_array, 'key2': numpy_array2})
+# Create ark with scp _file, too
+kaldiio.save_ark('b.ark', {'key': numpy_array, 'key2': numpy_array2},
+ scp='b.scp')
+
+# === Writes arrays to sys.stdout
+import sys
+kaldiio.save_ark(sys.stdout, {'key': numpy_array})
+
+# === Writes arrays for each keys
+# generate a.ark
+kaldiio.save_ark('a.ark', {'key': numpy_array, 'key2': numpy_array2})
+# After here, a.ark is opened with 'a' (append) mode.
+kaldiio.save_ark('a.ark', {'key3': numpy_array3}, append=True)
+
+
+# === Use with open_like_kaldi
+from kaldiio import open_like_kaldi
+with open_like_kaldi('| gzip a.ark.gz', 'w') as f:
+ kaldiio.save_ark(f, {'key': numpy_array})
+ kaldiio.save_ark(f, {'key2': numpy_array2})
+```
+### save_mat
+```python
+# array.ndim must be 1 or 2
+kaldiio.save_mat('a.mat', numpy_array)
+```
+- `save_mat` can save both kaldi-matrix and kaldi-vector
+
+
+### open_like_kaldi
+
+``kaldiio.open_like_kaldi`` is a useful tool if you are familiar with Kaldi. This function can performs as following,
+
+```python
+from kaldiio import open_like_kaldi
+with open_like_kaldi('echo -n hello |', 'r') as f:
+ assert f.read() == 'hello'
+with open_like_kaldi('| cat > out.txt', 'w') as f:
+ f.write('hello')
+with open('out.txt', 'r') as f:
+ assert f.read() == 'hello'
+
+import sys
+with open_like_kaldi('-', 'r') as f:
+ assert f is sys.stdin
+with open_like_kaldi('-', 'w') as f:
+ assert f is sys.stdout
+```
+
+For example, if there are gziped alignment file, then you can load it as:
+
+```python
+from kaldiio import open_like_kaldi, load_ark
+with open_like_kaldi('gunzip -c exp/tri3_ali/ali.*.gz |', 'rb') as f:
+ # Alignment format equals ark of IntVector
+ g = load_ark(f)
+ for k, numpy_array in g:
+ ...
+```
+
+### parse_specifier
+
+```python
+from kaldiio import parse_specifier, open_like_kaldi, load_ark
+rspecifier = 'ark:gunzip -c file.ark.gz |'
+spec_dict = parse_specifier(rspecifier)
+# spec_dict = {'ark': 'gunzip -c file.ark.gz |'}
+
+with open_like_kaldi(spec_dict['ark'], 'rb') as fark:
+ for key, numpy_array in load_ark(fark):
+ ...
+```
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/RECORD b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5f99e1d0f6f3943d60f8ee80ceac548f9368ccab
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/RECORD
@@ -0,0 +1,20 @@
+kaldiio-2.18.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+kaldiio-2.18.0.dist-info/LICENSE,sha256=7y6649nyH1UMbblsuR3jYFDUoDw3gxxa8JHEgUtr-Yo,7931
+kaldiio-2.18.0.dist-info/METADATA,sha256=T-7fzfx0BzeI892PfJlVo6UE2L4TbSr7nuf1pLHiEk8,13385
+kaldiio-2.18.0.dist-info/RECORD,,
+kaldiio-2.18.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
+kaldiio-2.18.0.dist-info/top_level.txt,sha256=2XjElXhcJ6-aFuwhGvzA3GaziQRO-YTKyTaSwgPCtA4,8
+kaldiio/__init__.py,sha256=IYJT3d4O-E_1KmzrSFnCTnuiPyzEX7dSLeKcRXTG_Xo,602
+kaldiio/__pycache__/__init__.cpython-39.pyc,,
+kaldiio/__pycache__/compression_header.cpython-39.pyc,,
+kaldiio/__pycache__/highlevel.cpython-39.pyc,,
+kaldiio/__pycache__/matio.cpython-39.pyc,,
+kaldiio/__pycache__/python_wave.cpython-39.pyc,,
+kaldiio/__pycache__/utils.cpython-39.pyc,,
+kaldiio/__pycache__/wavio.cpython-39.pyc,,
+kaldiio/compression_header.py,sha256=WN0zN9nO2uvt7UlJeWQyIGhnc2q_sL17zuM0IxrNjgE,8320
+kaldiio/highlevel.py,sha256=2ogf5dAQoYC3M7nt1m6ZuoQornN8FpTw04DgnZEcczM,5495
+kaldiio/matio.py,sha256=GdQuVh-0bL3XBh-kwReISaZz4Mlb9kUMR3y3SaJxjTY,29095
+kaldiio/python_wave.py,sha256=mPMdDhKqknQCxSV9eEi0Bd2ComHRv5VbYpT4QfwznPQ,18703
+kaldiio/utils.py,sha256=Ut4XGIlNq8SZxoedpO__dzR9AmK-kDKY-0Dwxv9BQYo,14096
+kaldiio/wavio.py,sha256=GC16D0r0tKxSfu8ROo9M95Gq8sL9OBu76oKHPJgrF3s,1380
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/WHEEL b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..1f37c02f2eb2e26b306202feaccb31e522b8b169
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.40.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/top_level.txt b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..124b318fa7d55a536cdb0b896bd0de2ece857ec3
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio-2.18.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+kaldiio
diff --git a/runtime/Lib/site-packages/kaldiio/__init__.py b/runtime/Lib/site-packages/kaldiio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccd5d2b81cb99887c088d18d3de82f5f8b48de58
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio/__init__.py
@@ -0,0 +1,20 @@
+# flake8: noqa F401
+import pkg_resources
+
+from kaldiio.matio import load_ark
+from kaldiio.matio import load_mat
+from kaldiio.matio import load_scp
+from kaldiio.matio import load_scp_sequential
+from kaldiio.matio import load_wav_scp
+from kaldiio.matio import save_ark
+from kaldiio.matio import save_mat
+from kaldiio.highlevel import ReadHelper
+from kaldiio.highlevel import WriteHelper
+from kaldiio.utils import open_like_kaldi
+from kaldiio.utils import parse_specifier
+
+try:
+ __version__ = pkg_resources.get_distribution("kaldiio").version
+except Exception:
+ __version__ = None
+del pkg_resources
diff --git a/runtime/Lib/site-packages/kaldiio/compression_header.py b/runtime/Lib/site-packages/kaldiio/compression_header.py
new file mode 100644
index 0000000000000000000000000000000000000000..d08102b9e8ce3927f49d074a28dc4d26e8c6b4c8
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio/compression_header.py
@@ -0,0 +1,251 @@
+from __future__ import unicode_literals
+
+import struct
+
+import numpy as np
+
+
+kAutomaticMethod = 1
+kSpeechFeature = 2
+kTwoByteAuto = 3
+kTwoByteSignedInteger = 4
+kOneByteAuto = 5
+kOneByteUnsignedInteger = 6
+kOneByteZeroOne = 7
+
+
+class GlobalHeader(object):
+ """This is a imitation class of the structure "GlobalHeader" """
+
+ def __init__(self, type, min_value, range, rows, cols, endian="<"):
+ if type in ("CM", "CM2"):
+ c = 65535.0
+ elif type == "CM3":
+ c = 255.0
+ else:
+ raise RuntimeError("Not supported type={}".format(type))
+ self.type = type
+ self.c = c
+ self.min_value = min_value
+ self.range = range
+ self.rows = rows
+ self.cols = cols
+ self.endian = endian
+
+ @property
+ def size(self):
+ return 17 + len(self.type)
+
+ @staticmethod
+ def read(fd, type="CM", endian="<"):
+ min_value = struct.unpack(endian + "f", fd.read(4))[0]
+ range = struct.unpack(endian + "f", fd.read(4))[0]
+ rows = struct.unpack(endian + "i", fd.read(4))[0]
+ cols = struct.unpack(endian + "i", fd.read(4))[0]
+ return GlobalHeader(type, min_value, range, rows, cols, endian)
+
+ def write(self, fd, endian=None):
+ if endian is None:
+ endian = self.endian
+ fd.write(self.type.encode() + b" ")
+ fd.write(struct.pack(endian + "f", self.min_value))
+ fd.write(struct.pack(endian + "f", self.range))
+ fd.write(struct.pack(endian + "i", self.rows))
+ fd.write(struct.pack(endian + "i", self.cols))
+ return self.size
+
+ @staticmethod
+ def compute(array, compression_method, endian="<"):
+ if compression_method == kAutomaticMethod:
+ if array.shape[0] > 8:
+ compression_method = kSpeechFeature
+ else:
+ compression_method = kTwoByteAuto
+
+ if compression_method == kSpeechFeature:
+ matrix_type = "CM"
+ elif (
+ compression_method == kTwoByteAuto
+ or compression_method == kTwoByteSignedInteger
+ ):
+ matrix_type = "CM2"
+ elif (
+ compression_method == kOneByteAuto
+ or compression_method == kOneByteUnsignedInteger
+ or compression_method == kOneByteZeroOne
+ ):
+ matrix_type = "CM3"
+ else:
+ raise ValueError(
+ "Unknown compression_method: {}".format(compression_method)
+ )
+
+ if (
+ compression_method == kSpeechFeature
+ or compression_method == kTwoByteAuto
+ or compression_method == kOneByteAuto
+ ):
+ min_value = array.min()
+ max_value = array.max()
+ if min_value == max_value:
+ max_value = min_value + (1.0 + abs(min_value))
+ range_ = max_value - min_value
+ elif compression_method == kTwoByteSignedInteger:
+ min_value = -32768.0
+ range_ = 65535.0
+ elif compression_method == kOneByteUnsignedInteger:
+ min_value = 0.0
+ range_ = 255.0
+ elif compression_method == kOneByteZeroOne:
+ min_value = 0.0
+ range_ = 1.0
+ else:
+ raise ValueError(
+ "Unknown compression_method: {}".format(compression_method)
+ )
+
+ return GlobalHeader(
+ matrix_type, min_value, range_, array.shape[0], array.shape[1], endian
+ )
+
+ def float_to_uint(self, array):
+ if self.c == 65535.0:
+ dtype = np.dtype(self.endian + "u2")
+ else:
+ dtype = np.dtype(self.endian + "u1")
+ # + 0.499 is to round to closest int
+ array = (array - self.min_value) / self.range * self.c + 0.499
+ return array.astype(np.dtype(dtype))
+
+ def uint_to_float(self, array):
+ array = array.astype(np.float32)
+ return self.min_value + array * self.range / self.c
+
+
+class PerColHeader(object):
+ """This is a imitation class of the structure "PerColHeader" """
+
+ def __init__(self, p0, p25, p75, p100, endian="<"):
+ # p means percentile
+ self.p0 = p0
+ self.p25 = p25
+ self.p75 = p75
+ self.p100 = p100
+ self.endian = endian
+
+ @property
+ def size(self):
+ return 8 * self.p0.shape[0]
+
+ @staticmethod
+ def read(fd, global_header):
+ endian = global_header.endian
+ # Read PerColHeader
+ size_of_percolheader = 8
+ buf = fd.read(size_of_percolheader * global_header.cols)
+ header_array = np.frombuffer(buf, dtype=np.dtype(endian + "u2"))
+ header_array = np.asarray(header_array, np.float32)
+ # Decompress header
+ header_array = global_header.uint_to_float(header_array)
+ header_array = header_array.reshape(-1, 4, 1)
+ return PerColHeader(
+ header_array[:, 0],
+ header_array[:, 1],
+ header_array[:, 2],
+ header_array[:, 3],
+ endian,
+ )
+
+ def write(self, fd, global_header, endian=None):
+ if endian is None:
+ endian = self.endian
+ header_array = np.concatenate([self.p0, self.p25, self.p75, self.p100], axis=1)
+ header_array = global_header.float_to_uint(header_array)
+ header_array = header_array.astype(np.dtype(endian + "u2"))
+ byte_str = header_array.tobytes()
+ fd.write(byte_str)
+ return len(byte_str)
+
+ @staticmethod
+ def compute(array, global_header):
+ quarter_nr = array.shape[0] // 4
+ if array.shape[0] >= 5:
+ srows = np.partition(
+ array, [0, quarter_nr, 3 * quarter_nr, array.shape[0] - 1], axis=0
+ )
+ p0 = srows[0]
+ p25 = srows[quarter_nr]
+ p75 = srows[3 * quarter_nr]
+ p100 = srows[array.shape[0] - 1]
+ else:
+ srows = np.sort(array, axis=0)
+ p0 = srows[0]
+ if array.shape[0] > 1:
+ p25 = srows[1]
+ else:
+ p25 = p0 + 1
+ if array.shape[0] > 2:
+ p75 = srows[2]
+ else:
+ p75 = p25 + 1
+ if array.shape[0] > 3:
+ p100 = srows[3]
+ else:
+ p100 = p75 + 1
+ p0 = global_header.float_to_uint(p0)
+ p25 = global_header.float_to_uint(p25)
+ p75 = global_header.float_to_uint(p75)
+ p100 = global_header.float_to_uint(p100)
+
+ p0 = np.minimum(p0, 65532)
+ p25 = np.minimum(np.maximum(p25, p0 + 1), 65533)
+ p75 = np.minimum(np.maximum(p75, p25 + 1), 65534)
+ p100 = np.maximum(p100, p75 + 1)
+
+ p0 = global_header.uint_to_float(p0)
+ p25 = global_header.uint_to_float(p25)
+ p75 = global_header.uint_to_float(p75)
+ p100 = global_header.uint_to_float(p100)
+
+ p0 = p0[:, None]
+ p25 = p25[:, None]
+ p75 = p75[:, None]
+ p100 = p100[:, None]
+ return PerColHeader(p0, p25, p75, p100, global_header.endian)
+
+ def float_to_char(self, array):
+ p0, p25, p75, p100 = self.p0, self.p25, self.p75, self.p100
+
+ ma1 = array < p25
+ ma3 = array >= p75
+ ma2 = ~ma1 * ~ma3
+
+ # +0.5 round to the closest int
+ tmp = (array - p0) / (p25 - p0) * 64.0 + 0.5
+ tmp = np.where(tmp < 0.0, 0.0, np.where(tmp > 64.0, 64.0, tmp))
+
+ tmp2 = (array - p25) / (p75 - p25) * 128.0 + 64.5
+ tmp2 = np.where(tmp2 < 64.0, 64.0, np.where(tmp2 > 192.0, 192.0, tmp2))
+
+ tmp3 = (array - p75) / (p100 - p75) * 63.0 + 192.5
+ tmp3 = np.where(tmp3 < 192.0, 192.0, np.where(tmp3 > 255.0, 255.0, tmp3))
+ array = np.where(ma1, tmp, np.where(ma2, tmp2, tmp3))
+ return array.astype(np.dtype(self.endian + "u1"))
+
+ def char_to_float(self, array):
+ array = array.astype(np.float32)
+ p0, p25, p75, p100 = self.p0, self.p25, self.p75, self.p100
+
+ ma1 = array <= 64
+ ma3 = array > 192
+ ma2 = ~ma1 * ~ma3 # 192 >= array > 64
+
+ return np.where(
+ ma1,
+ p0 + (p25 - p0) * array * (1 / 64.0),
+ np.where(
+ ma2,
+ p25 + (p75 - p25) * (array - 64.0) * (1 / 128.0),
+ p75 + (p100 - p75) * (array - 192.0) * (1 / 63.0),
+ ),
+ )
diff --git a/runtime/Lib/site-packages/kaldiio/highlevel.py b/runtime/Lib/site-packages/kaldiio/highlevel.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5e417bad872c9a22a3cbb7e8cb48ae2c04e3bd7
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio/highlevel.py
@@ -0,0 +1,174 @@
+from __future__ import unicode_literals
+
+import warnings
+
+from kaldiio.matio import load_ark
+from kaldiio.matio import load_scp_sequential
+from kaldiio.matio import save_ark
+from kaldiio.utils import open_like_kaldi
+from kaldiio.utils import parse_specifier
+
+
+class WriteHelper(object):
+ """A heghlevel interface to write ark or/and scp
+
+ >>> helper = WriteHelper('ark,scp:a.ark,b.ark')
+ >>> helper('uttid', array)
+
+ """
+
+ def __init__(self, wspecifier, compression_method=None, write_function=None):
+ self.initialized = False
+ self.closed = False
+
+ self.compression_method = compression_method
+ self.write_function = write_function
+ spec_dict = parse_specifier(wspecifier)
+ if spec_dict["scp"] is not None and spec_dict["ark"] is None:
+ raise ValueError(
+ "Writing only in a scp file is not supported. "
+ "Please specify a ark file with a scp file."
+ )
+ for k in spec_dict:
+ if spec_dict[k] and k not in ("scp", "ark", "t", "f"):
+ warnings.warn(
+ "{} option is given, but currently it never affects".format(k)
+ )
+
+ self.text = spec_dict["t"]
+ self.flush = spec_dict["f"]
+ ark_file = spec_dict["ark"]
+ self.fark = open_like_kaldi(ark_file, "wb")
+ if spec_dict["scp"] is not None:
+ self.fscp = open_like_kaldi(spec_dict["scp"], "w")
+ else:
+ self.fscp = None
+ self.initialized = True
+
+ def __call__(self, key, array):
+ if self.closed:
+ raise RuntimeError("WriteHelper has been already closed")
+ save_ark(
+ self.fark,
+ {key: array},
+ scp=self.fscp,
+ text=self.text,
+ compression_method=self.compression_method,
+ write_function=self.write_function,
+ )
+
+ if self.flush:
+ if self.fark is not None:
+ self.fark.flush()
+ if self.fscp is not None:
+ self.fscp.flush()
+
+ def __setitem__(self, key, value):
+ self(key, value)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.close()
+
+ def close(self):
+ if self.initialized and not self.closed:
+ self.fark.close()
+ if self.fscp is not None:
+ self.fscp.close()
+ self.closed = True
+
+
+class ReadHelper(object):
+ """A highlevel interface to load ark or scp
+
+ >>> import numpy
+ >>> array_in = numpy.random.randn(10, 10)
+ >>> save_ark('feats.ark', {'foo': array_in}, scp='feats.scp')
+ >>> helper = ReadHelper('ark:cat feats.ark |')
+ >>> for uttid, array_out in helper:
+ ... assert uttid == 'foo'
+ ... numpy.testing.assert_array_equal(array_in, array_out)
+ >>> helper = ReadHelper('scp:feats.scp')
+ >>> for uttid, array_out in helper:
+ ... assert uttid == 'foo'
+ ... numpy.testing.assert_array_equal(array_in, array_out)
+
+ """
+
+ def __init__(self, wspecifier, segments=None):
+ self.initialized = False
+ self.scp = None
+ self.closed = False
+ self.generator = None
+ self.segments = segments
+
+ spec_dict = parse_specifier(wspecifier)
+ if spec_dict["scp"] is not None and spec_dict["ark"] is not None:
+ raise RuntimeError("Specify one of scp or ark in rspecifier")
+ for k in spec_dict:
+ if spec_dict[k] and k not in ("scp", "ark", "p"):
+ warnings.warn(
+ "{} option is given, but currently it never affects".format(k)
+ )
+ self.permissive = spec_dict["p"]
+
+ if spec_dict["scp"] is not None:
+ self.scp = spec_dict["scp"]
+ else:
+ self.scp = False
+
+ if self.scp:
+ self.generator = load_scp_sequential(spec_dict["scp"], segments=segments)
+
+ self.file = None
+ else:
+ if segments is not None:
+ raise ValueError('Not supporting "segments" argument with ark file')
+ self.file = open_like_kaldi(spec_dict["ark"], "rb")
+ self.initialized = True
+
+ def __iter__(self):
+ if self.scp:
+ while True:
+ try:
+ k, v = next(self.generator)
+ except StopIteration:
+ break
+ except Exception:
+ if self.permissive:
+ # Stop if error happen
+ break
+ else:
+ raise
+ yield k, v
+
+ else:
+ with self.file as f:
+ it = load_ark(f)
+ while True:
+ try:
+ k, v = next(it)
+ except StopIteration:
+ break
+ except Exception:
+ if self.permissive:
+ # Stop if error happen
+ break
+ else:
+ raise
+ yield k, v
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if not self.scp and not self.closed:
+ self.close()
+
+ def close(self):
+ if self.initialized and not self.scp and not self.closed:
+ self.file.close()
+ self.closed = True
diff --git a/runtime/Lib/site-packages/kaldiio/matio.py b/runtime/Lib/site-packages/kaldiio/matio.py
new file mode 100644
index 0000000000000000000000000000000000000000..643375b509fae64e17255c70e04a658c5da534f3
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio/matio.py
@@ -0,0 +1,947 @@
+from __future__ import division
+from __future__ import unicode_literals
+
+import codecs
+import math
+import pickle
+import re
+import struct
+import sys
+import warnings
+from functools import partial
+from io import BytesIO
+from io import StringIO
+
+import numpy as np
+
+from kaldiio.compression_header import GlobalHeader
+from kaldiio.compression_header import PerColHeader
+from kaldiio.utils import LazyLoader
+from kaldiio.utils import LimitedSizeDict
+from kaldiio.utils import MultiFileDescriptor
+from kaldiio.utils import default_encoding
+from kaldiio.utils import open_like_kaldi
+from kaldiio.utils import open_or_fd
+from kaldiio.utils import seekable
+from kaldiio.wavio import read_wav
+from kaldiio.wavio import write_wav
+
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ from collections.abc import Mapping
+
+ binary_type = bytes
+ string_types = (str,)
+
+ def to_bytes(n, length, endianess="little"):
+ return n.to_bytes(length, endianess)
+
+ def from_bytes(s, endianess="little"):
+ return int.from_bytes(s, endianess)
+
+else:
+ from collections import Mapping
+
+ binary_type = str
+ string_types = (basestring,) # noqa: F821
+
+ def to_bytes(n, length, endianess="little"):
+ assert endianess in ("big", "little"), endianess
+ h = b"%x" % n
+ s = codecs.decode((b"0" * (len(h) % 2) + h).zfill(length * 2), "hex")
+ return s if endianess == "big" else s[::-1]
+
+ def from_bytes(s, endianess="little"):
+ if endianess == "little":
+ s = s[::-1]
+ return int(codecs.encode(s, "hex"), 16)
+
+
+def load_scp(fname, endian="<", separator=None, segments=None, max_cache_fd=0):
+ """Lazy loader for kaldi scp file.
+
+ Args:
+ fname (str or file(text mode)):
+ endian (str):
+ separator (str):
+ segments (str): The path of segments
+ """
+ assert endian in ("<", ">"), endian
+
+ if max_cache_fd != 0:
+ if segments is not None:
+ raise ValueError("max_cache_fd is not supported for segments mode")
+ d = LimitedSizeDict(max_cache_fd)
+ else:
+ d = None
+
+ if segments is None:
+ load_func = partial(load_mat, endian=endian, fd_dict=d)
+ loader = LazyLoader(load_func)
+ with open_like_kaldi(fname, "r") as fd:
+ for line in fd:
+ seps = line.split(separator, 1)
+ if len(seps) != 2:
+ raise ValueError("Invalid line is found:\n> {}".format(line))
+ token, arkname = seps
+ loader[token] = arkname.rstrip()
+ return loader
+ else:
+ return SegmentsExtractor(fname, separator=separator, segments=segments)
+
+
+def load_scp_sequential(fname, endian="<", separator=None, segments=None):
+ """Lazy loader for kaldi scp file.
+
+ Args:
+ fname (str or file(text mode)):
+ endian (str):
+ separator (str):
+ segments (str): The path of segments
+ """
+ assert endian in ("<", ">"), endian
+ if segments is None:
+ with open_like_kaldi(fname, "r") as fd:
+ prev_ark = None
+ prev_arkfd = None
+
+ try:
+ for line in fd:
+ seps = line.split(separator, 1)
+ if len(seps) != 2:
+ raise ValueError("Invalid line is found:\n> {}".format(line))
+ token, arkname = seps
+ arkname = arkname.rstrip()
+
+ ark, offset, slices = _parse_arkpath(arkname)
+
+ if prev_ark == ark:
+ arkfd = prev_arkfd
+ mat = _load_mat(arkfd, offset, slices, endian=endian)
+ else:
+ if prev_arkfd is not None:
+ prev_arkfd.close()
+ arkfd = open_like_kaldi(ark, "rb")
+ mat = _load_mat(arkfd, offset, slices, endian=endian)
+
+ prev_ark = ark
+ prev_arkfd = arkfd
+ yield token, mat
+ except Exception:
+ if prev_arkfd is not None:
+ prev_arkfd.close()
+ raise
+
+ else:
+ for data in SegmentsExtractor(
+ fname, separator=separator, segments=segments
+ ).generator():
+ yield data
+
+
+def load_wav_scp(fname, segments=None, separator=None):
+ warnings.warn("Use load_scp instead of load_wav_scp", DeprecationWarning)
+ return load_scp(fname, separator=separator, segments=segments)
+
+
+class SegmentsExtractor(Mapping):
+ """Emulate the following,
+
+ https://github.com/kaldi-asr/kaldi/blob/master/src/featbin/extract-segments.cc
+
+ Args:
+ segments (str): The file format is
+ " \n"
+ "e.g. call-861225-A-0050-0065 call-861225-A 5.0 6.5\n"
+ """
+
+ def __init__(self, fname, segments=None, separator=None):
+ self.wav_scp = fname
+ self.wav_loader = load_scp(self.wav_scp, separator=separator)
+
+ self.segments = segments
+ self._segments_dict = {}
+ with open_or_fd(self.segments, "r") as f:
+ for line in f:
+ sps = line.rstrip().split(separator)
+ if len(sps) != 4:
+ raise RuntimeError("Format is invalid: {}".format(line))
+ uttid, recodeid, st, et = sps
+ self._segments_dict[uttid] = (recodeid, float(st), float(et))
+
+ if recodeid not in self.wav_loader:
+ raise RuntimeError(
+ 'Not found "{}" in {}'.format(recodeid, self.wav_scp)
+ )
+
+ def generator(self):
+ recodeid_counter = {}
+ for utt, (recodeid, st, et) in self._segments_dict.items():
+ recodeid_counter[recodeid] = recodeid_counter.get(recodeid, 0) + 1
+
+ cached = {}
+ for utt, (recodeid, st, et) in self._segments_dict.items():
+ if recodeid not in cached:
+ cached[recodeid] = self.wav_loader[recodeid]
+ array = cached[recodeid]
+
+ # Keep array until the last query
+ recodeid_counter[recodeid] -= 1
+ if recodeid_counter[recodeid] == 0:
+ cached.pop(recodeid)
+
+ yield utt, self._return(array, st, et)
+
+ def __iter__(self):
+ return iter(self._segments_dict)
+
+ def __contains__(self, item):
+ return item in self._segments_dict
+
+ def __len__(self):
+ return len(self._segments_dict)
+
+ def __getitem__(self, key):
+ recodeid, st, et = self._segments_dict[key]
+ array = self.wav_loader[recodeid]
+ return self._return(array, st, et)
+
+ def _return(self, array, st, et):
+ if isinstance(array, (tuple, list)):
+ rate, array = array
+ else:
+ raise RuntimeError("{} is not wav.scp?".format(self.wav_scp))
+
+ # Convert starting time of the segment to corresponding sample number.
+ # If end time is -1 then use the whole file starting from start time.
+ if et != -1:
+ return rate, array[int(st * rate) : int(et * rate)]
+ else:
+ return rate, array[int(st * rate) :]
+
+
+def load_mat(ark_name, endian="<", fd_dict=None):
+ assert endian in ("<", ">"), endian
+ if fd_dict is not None and not isinstance(fd_dict, Mapping):
+ raise RuntimeError(
+ "fd_dict must be dict or None, bot got {}".format(type(fd_dict))
+ )
+
+ ark, offset, slices = _parse_arkpath(ark_name)
+
+ if fd_dict is not None and not (ark.strip()[-1] == "|" or ark.strip()[0] == "|"):
+ if ark not in fd_dict:
+ fd_dict[ark] = open_like_kaldi(ark, "rb")
+ fd = fd_dict[ark]
+ return _load_mat(fd, offset, slices, endian=endian)
+ else:
+ with open_like_kaldi(ark, "rb") as fd:
+ return _load_mat(fd, offset, slices, endian=endian)
+
+
+def _parse_arkpath(ark_name):
+ """Parse arkpath
+
+ Args:
+ ark_name (str):
+ Returns:
+ Tuple[str, int, Optional[Tuple[slice, ...]]]
+ Examples:
+ >>> _parse_arkpath('a.ark')
+ 'a.ark', None, None
+ >>> _parse_arkpath('a.ark:12')
+ 'a.ark', 12, None
+ >>> _parse_arkpath('a.ark:12[3:4]')
+ 'a.ark', 12, (slice(3, 4, None),)
+ >>> _parse_arkpath('cat "fo:o.ark" |')
+ 'cat "fo:o.ark" |', None, None
+
+ """
+
+ if ark_name.strip()[-1] == "|" or ark_name.strip()[0] == "|":
+ # Something like: "| cat foo" or "cat bar|" shouldn't be parsed
+ return ark_name, None, None
+
+ slices = None
+ if "[" in ark_name and "]" in ark_name:
+ _ark_name, Range = ark_name.split("[")
+ Range = Range.replace("]", "").strip()
+ try:
+ slices = _convert_to_slice(Range)
+ except Exception:
+ pass
+ else:
+ ark_name = _ark_name
+
+ if ":" in ark_name:
+ fname, offset = ark_name.rsplit(":", 1)
+ try:
+ offset = int(offset)
+ except ValueError:
+ fname = ark_name
+ offset = None
+ else:
+ fname = ark_name
+ offset = None
+ return fname, offset, slices
+
+
+def _convert_to_slice(string):
+ """Convert slice-str to slice
+
+ Examples:
+ >>> _convert_to_slice('0:51')
+ (slice(0, 52),)
+ >>> _convert_to_slice('0:51,6:10')
+ (slice(0, 52), slice(6, 11))
+ >>> _convert_to_slice(',6:10')
+ (slice(None), slice(6, 11))
+
+ """
+
+ slices = []
+ for ele in string.split(","):
+ if ele == "" or ele == ":":
+ slices.append(slice(None))
+ else:
+ sps = []
+ for sp in ele.split(":"):
+ try:
+ sps.append(int(sp))
+ except ValueError:
+ raise ValueError("Format error: {}".format(string))
+ if len(sps) == 1:
+ sl = slice(sps[0], sps[0] + 1)
+ elif len(sps) == 2:
+ sl = slice(sps[0], sps[1] + 1)
+ elif len(sps) == 3:
+ sl = slice(sps[0], sps[1] + 1, sps[2])
+ else:
+ raise RuntimeError("Too many : {}".format(string))
+
+ slices.append(sl)
+ return tuple(slices)
+
+
+def _load_mat(fd, offset, slices=None, endian="<"):
+ if offset is not None:
+ fd.seek(offset)
+ array = read_kaldi(fd, endian)
+
+ if slices is not None:
+ if isinstance(array, (tuple, list)):
+ array = (array[0], array[1][slices])
+ else:
+ array = array[slices]
+ return array
+
+
+def load_ark(fname, endian="<"):
+ assert endian in ("<", ">"), endian
+ with open_or_fd(fname, "rb") as fd:
+ while True:
+ token = read_token(fd)
+ if token is None:
+ break
+ array = read_kaldi(fd, endian)
+ yield token, array
+
+
+def read_token(fd):
+ """Read token
+
+ Args:
+ fd (file):
+ """
+ token = []
+ # Keep the loop until finding ' ' or end of char
+ while True:
+ c = fd.read(1)
+ if c == b" " or c == b"":
+ break
+ token.append(c)
+ if len(token) == 0: # End of file
+ return None
+ decoded = b"".join(token).decode(encoding=default_encoding)
+ return decoded
+
+
+def read_kaldi(fd, endian="<", audio_loader="soundfile", load_kwargs=None):
+ """Load kaldi
+
+ Args:
+ fd (file): Binary mode file object. Cannot input string
+ endian (str):
+ audio_loader: (Union[str, callable]):
+ """
+ assert endian in ("<", ">"), endian
+ if load_kwargs is None:
+ load_kwargs = {}
+
+ max_flag_length = len(b"AUDIO")
+
+ binary_flag = fd.read(max_flag_length)
+ assert isinstance(binary_flag, binary_type), type(binary_flag)
+
+ if seekable(fd):
+ fd.seek(-max_flag_length, 1)
+ else:
+ fd = MultiFileDescriptor(BytesIO(binary_flag), fd)
+
+ if binary_flag[:4] == b"RIFF":
+ # array: Tuple[int, np.ndarray]
+ array = read_wav(fd)
+
+ elif binary_flag[:3] == b"NPY":
+ fd.read(3)
+ length_ = _read_length_header(fd)
+ buf = fd.read(length_)
+ _fd = BytesIO(buf)
+ array = np.load(_fd, **load_kwargs)
+
+ elif binary_flag[:3] == b"PKL":
+ fd.read(3)
+ array = pickle.load(fd, **load_kwargs)
+
+ elif binary_flag[:5] == b"AUDIO":
+ fd.read(5)
+ length_ = _read_length_header(fd)
+ buf = fd.read(length_)
+ _fd = BytesIO(buf)
+
+ if audio_loader == "soundfile":
+ import soundfile
+
+ audio_loader = soundfile.read
+ else:
+ raise ValueError("Not supported: audio_loader={}".format(audio_loader))
+
+ x1, x2 = audio_loader(_fd, **load_kwargs)
+
+ # array: Tuple[int, np.ndarray] according to scipy wav read
+ if isinstance(x1, int) and isinstance(x2, np.ndarray):
+ array = (x1, x2)
+ elif isinstance(x1, np.ndarray) and isinstance(x2, int):
+ array = (x2, x1)
+ else:
+ raise RuntimeError(
+ "Got unexpected type from audio_loader: ({}, {})".format(
+ type(x1), type(x2)
+ )
+ )
+
+ # Load as binary
+ elif binary_flag[:2] == b"\0B":
+ if binary_flag[2:3] == b"\4": # This is int32Vector
+ array = read_int32vector(fd, endian)
+ else:
+ array = read_matrix_or_vector(fd, endian)
+ # Load as ascii
+ else:
+ array = read_ascii_mat(fd)
+
+ return array
+
+
+def read_int32vector(fd, endian="<", return_size=False):
+ assert fd.read(2) == b"\0B"
+ assert fd.read(1) == b"\4"
+ length = struct.unpack(endian + "i", fd.read(4))[0]
+ array = np.empty(length, dtype=np.int32)
+ for i in range(length):
+ assert fd.read(1) == b"\4"
+ array[i] = struct.unpack(endian + "i", fd.read(4))[0]
+ if return_size:
+ return array, (length + 1) * 5 + 2
+ else:
+ return array
+
+
+def read_matrix_or_vector(fd, endian="<", return_size=False):
+ """Call from load_kaldi_file
+
+ Args:
+ fd (file):
+ endian (str):
+ return_size (bool):
+ """
+ size = 0
+ assert fd.read(2) == b"\0B"
+ size += 2
+
+ Type = str(read_token(fd))
+ size += len(Type) + 1
+
+ # CompressedMatrix
+ if "CM" == Type:
+ # Read GlobalHeader
+ global_header = GlobalHeader.read(fd, Type, endian)
+ size += global_header.size
+ per_col_header = PerColHeader.read(fd, global_header)
+ size += per_col_header.size
+
+ # Read data
+ buf = fd.read(global_header.rows * global_header.cols)
+ size += global_header.rows * global_header.cols
+ array = np.frombuffer(buf, dtype=np.dtype(endian + "u1"))
+ array = array.reshape((global_header.cols, global_header.rows))
+
+ # Decompress
+ array = per_col_header.char_to_float(array)
+ array = array.T
+
+ elif "CM2" == Type:
+ # Read GlobalHeader
+ global_header = GlobalHeader.read(fd, Type, endian)
+ size += global_header.size
+
+ # Read matrix
+ buf = fd.read(2 * global_header.rows * global_header.cols)
+ array = np.frombuffer(buf, dtype=np.dtype(endian + "u2"))
+ array = array.reshape((global_header.rows, global_header.cols))
+
+ # Decompress
+ array = global_header.uint_to_float(array)
+
+ elif "CM3" == Type:
+ # Read GlobalHeader
+ global_header = GlobalHeader.read(fd, Type, endian)
+ size += global_header.size
+
+ # Read matrix
+ buf = fd.read(global_header.rows * global_header.cols)
+ array = np.frombuffer(buf, dtype=np.dtype(endian + "u1"))
+ array = array.reshape((global_header.rows, global_header.cols))
+
+ # Decompress
+ array = global_header.uint_to_float(array)
+
+ else:
+ if Type == "FM" or Type == "FV":
+ dtype = endian + "f"
+ bytes_per_sample = 4
+ elif Type == "DM" or Type == "DV":
+ dtype = endian + "d"
+ bytes_per_sample = 8
+ else:
+ raise ValueError(
+ 'Unexpected format: "{}". Now FM, FV, DM, DV, '
+ "CM, CM2, CM3 are supported.".format(Type)
+ )
+
+ assert fd.read(1) == b"\4"
+ size += 1
+ rows = struct.unpack(endian + "i", fd.read(4))[0]
+ size += 4
+ dim = rows
+ if "M" in Type: # As matrix
+ assert fd.read(1) == b"\4"
+ size += 1
+ cols = struct.unpack(endian + "i", fd.read(4))[0]
+ size += 4
+ dim = rows * cols
+
+ buf = fd.read(dim * bytes_per_sample)
+ size += dim * bytes_per_sample
+ array = np.frombuffer(buf, dtype=np.dtype(dtype))
+
+ if "M" in Type: # As matrix
+ array = np.reshape(array, (rows, cols))
+
+ if return_size:
+ return array, size
+ else:
+ return array
+
+
+def read_ascii_mat(fd, return_size=False):
+ """Call from load_kaldi_file
+
+ Args:
+ fd (file): binary mode
+ return_size (bool):
+ """
+ string = []
+ size = 0
+
+ # Find '[' char
+ while True:
+ b = fd.read(1)
+ try:
+ char = b.decode(encoding=default_encoding)
+ except UnicodeDecodeError:
+ raise ValueError("File format is wrong?")
+ size += 1
+ if char == " " or char == "\n":
+ continue
+ elif char == "[":
+ hasparent = True
+ break
+ else:
+ string.append(char)
+ hasparent = False
+ break
+
+ # Read data
+ ndmin = 1
+ while True:
+ char = fd.read(1).decode(encoding=default_encoding)
+ size += 1
+ if hasparent:
+ if char == "]":
+ char = fd.read(1).decode(encoding=default_encoding)
+ size += 1
+ assert char == "\n" or char == ""
+ break
+ elif char == "\n":
+ ndmin = 2
+ elif char == "":
+ raise ValueError("There are no corresponding bracket ']' with '['")
+ else:
+ if char == "\n" or char == "":
+ break
+ string.append(char)
+ string = "".join(string)
+ assert len(string) != 0
+
+ # Examine dtype
+ match = re.match(r" *([^ \n]+) *", string)
+ if match is None:
+ dtype = np.float32
+ else:
+ ma = match.group(0)
+ # If first element is integer, deal as interger array
+ try:
+ float(ma)
+ except ValueError:
+ raise RuntimeError(ma + "is not a digit\nFile format is wrong?")
+ if "." in ma:
+ dtype = np.float32
+ else:
+ dtype = np.int32
+ array = np.loadtxt(StringIO(string), dtype=dtype, ndmin=ndmin)
+ if return_size:
+ return array, size
+ else:
+ return array
+
+
+def _read_length_header(fd):
+ (bytes_length,) = struct.unpack(" self._nframes:
+ raise Error("position not in range")
+ self._soundpos = pos
+ self._data_seek_needed = 1
+
+ def readframes(self, nframes):
+ if self._data_seek_needed:
+ self._data_chunk.seek(0, 0)
+ pos = self._soundpos * self._framesize
+ if pos:
+ self._data_chunk.seek(pos, 0)
+ self._data_seek_needed = 0
+ if nframes == 0:
+ return b""
+ data = self._data_chunk.read(nframes * self._framesize)
+ if self._sampwidth != 1 and sys.byteorder == "big":
+ data = audioop.byteswap(data, self._sampwidth)
+ if self._convert and data:
+ data = self._convert(data)
+ self._soundpos = self._soundpos + len(data) // (
+ self._nchannels * self._sampwidth
+ )
+ return data
+
+ #
+ # Internal methods.
+ #
+
+ def _read_fmt_chunk(self, chunk):
+ try:
+ (
+ wFormatTag,
+ self._nchannels,
+ self._framerate,
+ dwAvgBytesPerSec,
+ wBlockAlign,
+ ) = struct.unpack_from(" 4:
+ raise Error("bad sample width")
+ self._sampwidth = sampwidth
+
+ def getsampwidth(self):
+ if not self._sampwidth:
+ raise Error("sample width not set")
+ return self._sampwidth
+
+ def setframerate(self, framerate):
+ if self._datawritten:
+ raise Error("cannot change parameters after starting to write")
+ if framerate <= 0:
+ raise Error("bad frame rate")
+ self._framerate = int(round(framerate))
+
+ def getframerate(self):
+ if not self._framerate:
+ raise Error("frame rate not set")
+ return self._framerate
+
+ def setnframes(self, nframes):
+ if self._datawritten:
+ raise Error("cannot change parameters after starting to write")
+ self._nframes = nframes
+
+ def getnframes(self):
+ return self._nframeswritten
+
+ def setcomptype(self, comptype, compname):
+ if self._datawritten:
+ raise Error("cannot change parameters after starting to write")
+ if comptype not in ("NONE",):
+ raise Error("unsupported compression type")
+ self._comptype = comptype
+ self._compname = compname
+
+ def getcomptype(self):
+ return self._comptype
+
+ def getcompname(self):
+ return self._compname
+
+ def setparams(self, params):
+ nchannels, sampwidth, framerate, nframes, comptype, compname = params
+ if self._datawritten:
+ raise Error("cannot change parameters after starting to write")
+ self.setnchannels(nchannels)
+ self.setsampwidth(sampwidth)
+ self.setframerate(framerate)
+ self.setnframes(nframes)
+ self.setcomptype(comptype, compname)
+
+ def getparams(self):
+ if not self._nchannels or not self._sampwidth or not self._framerate:
+ raise Error("not all parameters set")
+ return _wave_params(
+ self._nchannels,
+ self._sampwidth,
+ self._framerate,
+ self._nframes,
+ self._comptype,
+ self._compname,
+ )
+
+ def setmark(self, id, pos, name):
+ raise Error("setmark() not supported")
+
+ def getmark(self, id):
+ raise Error("no marks")
+
+ def getmarkers(self):
+ return None
+
+ def tell(self):
+ return self._nframeswritten
+
+ def writeframesraw(self, data):
+ if not isinstance(data, (bytes, bytearray)):
+ data = memoryview(data).cast("B")
+ self._ensure_header_written(len(data))
+ nframes = len(data) // (self._sampwidth * self._nchannels)
+ if self._convert:
+ data = self._convert(data)
+ if self._sampwidth != 1 and sys.byteorder == "big":
+ data = audioop.byteswap(data, self._sampwidth)
+ self._file.write(data)
+ self._datawritten += len(data)
+ self._nframeswritten = self._nframeswritten + nframes
+
+ def writeframes(self, data):
+ self.writeframesraw(data)
+ if self._datalength != self._datawritten:
+ self._patchheader()
+
+ def close(self):
+ try:
+ if self._file:
+ self._ensure_header_written(0)
+ if self._datalength != self._datawritten:
+ self._patchheader()
+ self._file.flush()
+ finally:
+ self._file = None
+ file = self._i_opened_the_file
+ if file:
+ self._i_opened_the_file = None
+ file.close()
+
+ #
+ # Internal methods.
+ #
+
+ def _ensure_header_written(self, datasize):
+ if not self._headerwritten:
+ if not self._nchannels:
+ raise Error("# channels not specified")
+ if not self._sampwidth:
+ raise Error("sample width not specified")
+ if not self._framerate:
+ raise Error("sampling rate not specified")
+ self._write_header(datasize)
+
+ def _write_header(self, initlength):
+ assert not self._headerwritten
+ self._file.write(b"RIFF")
+ if not self._nframes:
+ self._nframes = initlength // (self._nchannels * self._sampwidth)
+ self._datalength = self._nframes * self._nchannels * self._sampwidth
+ try:
+ self._form_length_pos = self._file.tell()
+ except (AttributeError, OSError):
+ self._form_length_pos = None
+ self._file.write(
+ struct.pack(
+ "=3.7,
+
+- preferred encoding
+
+locale.getpreferredencoding(). Used for open().
+The default value depends on the local in your unix system.
+
+- stdout and stdin
+
+If PYTHONIOENCODING is set, then it's used,
+else if in a terminal, same as filesystem encoding
+else same as preferred encoding
+
+- default encoding
+
+The default encoding for str.encode() or bytes.decode().
+If Python2, it's ascii, if Python3, it's utf-8.
+
+"""
+
+
+if PY3:
+
+ def my_popen(cmd, mode="r", buffering=-1):
+ """Originated from python os module
+
+ Extend for supporting mode == 'rb' and 'wb'
+
+ Args:
+ cmd (str):
+ mode (str):
+ buffering (int):
+ """
+ if isinstance(cmd, text_type):
+ cmd = cmd.encode(default_encoding)
+ if buffering == 0 or buffering is None:
+ raise ValueError("popen() does not support unbuffered streams")
+ if mode == "r":
+ proc = subprocess.Popen(
+ cmd, shell=True, stdout=subprocess.PIPE, bufsize=buffering
+ )
+ return _wrap_close(
+ io.TextIOWrapper(proc.stdout, encoding=default_encoding), proc
+ )
+ elif mode == "rb":
+ proc = subprocess.Popen(
+ cmd, shell=True, stdout=subprocess.PIPE, bufsize=buffering
+ )
+ return _wrap_close(proc.stdout, proc)
+ elif mode == "w":
+ proc = subprocess.Popen(
+ cmd, shell=True, stdin=subprocess.PIPE, bufsize=buffering
+ )
+ return _wrap_close(
+ io.TextIOWrapper(proc.stdin, encoding=default_encoding), proc
+ )
+ elif mode == "wb":
+ proc = subprocess.Popen(
+ cmd, shell=True, stdin=subprocess.PIPE, bufsize=buffering
+ )
+ return _wrap_close(proc.stdin, proc)
+ else:
+ raise TypeError("Unsupported mode == {}".format(mode))
+
+else:
+ my_popen = os.popen
+
+
+class _wrap_close(object):
+ """Originated from python os module
+
+ A proxy for a file whose close waits for the process
+ """
+
+ def __init__(self, stream, proc):
+ self._stream = stream
+ self._proc = proc
+
+ def close(self):
+ self._stream.close()
+ returncode = self._proc.wait()
+ if returncode == 0:
+ return None
+ if os.name == "nt":
+ return returncode
+ else:
+ return returncode << 8 # Shift left to match old behavior
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ self.close()
+
+ def __getattr__(self, name):
+ return getattr(self._stream, name)
+
+ def __iter__(self):
+ return iter(self._stream)
+
+
+class _stdstream_wrap(object):
+ def __init__(self, fd):
+ self.fd = fd
+
+ def __enter__(self):
+ return self.fd
+
+ def __exit__(self, *args):
+ # Never close
+ pass
+
+ def close(self):
+ # Never close
+ pass
+
+ def __getattr__(self, name):
+ return getattr(self.fd, name)
+
+ def __iter__(self):
+ return iter(self.fd)
+
+
+def open_like_kaldi(name, mode="r"):
+ """Open a file like kaldi io
+
+ Args:
+ name (str or file):
+ mode (str):
+ """
+ # If file descriptor
+ if not isinstance(name, string_types):
+ if PY3 and "b" in mode and isinstance(name, TextIOBase):
+ return name.buffer
+ else:
+ return name
+
+ # If writting to stdout
+ if name.strip().endswith("|"):
+ cmd = name.strip()[:-1].encode(default_encoding)
+ return my_popen(cmd, mode)
+ # If reading from stdin
+ elif name.strip().startswith("|"):
+ cmd = name.strip()[1:].encode(default_encoding)
+ return my_popen(cmd, mode)
+ # If read mode
+ elif name == "-" and "r" in mode:
+ if PY3:
+ if mode == "rb":
+ return _stdstream_wrap(sys.stdin.buffer)
+ else:
+ return _stdstream_wrap(
+ io.TextIOWrapper(sys.stdin.buffer, encoding=default_encoding)
+ )
+ else:
+ return _stdstream_wrap(sys.stdin)
+ # If write mode
+ elif name == "-" and ("w" in mode or "a" in mode):
+ if PY3:
+ if mode == "wb" or mode == "ab":
+ return _stdstream_wrap(sys.stdout.buffer)
+ else:
+ return _stdstream_wrap(
+ io.TextIOWrapper(sys.stdout.buffer, encoding=default_encoding)
+ )
+ else:
+ return _stdstream_wrap(sys.stdout)
+ else:
+ encoding = None if "b" in mode else default_encoding
+ return io.open(name, mode, encoding=encoding)
+
+
+@contextmanager
+def open_or_fd(fname, mode):
+ # If fname is a file name
+ if isinstance(fname, string_types):
+ encoding = None if "b" in mode else default_encoding
+ f = io.open(fname, mode, encoding=encoding)
+ # If fname is a file descriptor
+ else:
+ if PY3 and "b" in mode and isinstance(fname, TextIOBase):
+ f = fname.buffer
+ else:
+ f = fname
+ yield f
+
+ if isinstance(fname, string_types):
+ f.close()
+
+
+class MultiFileDescriptor(object):
+ """What is this class?
+
+ First of all, I want to load all format kaldi files
+ only by using read_kaldi function, and I want to load it
+ from file and file descriptor including standard input stream.
+ To judge its file format it is required to make the
+ file descriptor read and seek(to return original position).
+ However, stdin is not seekable, so I create this clas.
+ This class joints multiple file descriptors
+ and I assume this class is used as follwoing,
+
+ >>> string = fd.read(size)
+ >>> # To check format from string
+ >>> _fd = StringIO(string)
+ >>> newfd = MultiFileDescriptor(_fd, fd)
+ """
+
+ def __init__(self, *fds):
+ self.fds = fds
+
+ if self.seekable():
+ self.init_pos = [f.tell() for f in self.fds]
+ else:
+ self.init_pos = None
+
+ def seek(self, offset, from_what=0):
+ if not self.seekable():
+ if PY3:
+ raise OSError
+ else:
+ raise IOError
+ if offset != 0:
+ raise NotImplementedError("offset={}".format(offset))
+ if from_what == 1:
+ offset += self.tell()
+ from_what = 0
+
+ if from_what == 0:
+ for idx, f in enumerate(self.fds):
+ pos = self.init_pos[idx]
+ f.seek(pos + offset, 0)
+ offset -= f.tell() - pos
+ else:
+ raise NotImplementedError("from_what={}".format(from_what))
+
+ def seekable(self):
+ return all(seekable(f) for f in self.fds)
+
+ def tell(self):
+ if not self.seekable():
+ if PY3:
+ raise OSError
+ else:
+ raise IOError
+ return sum(f.tell() - self.init_pos[idx] for idx, f in enumerate(self.fds))
+
+ def read(self, size=-1):
+ remain = size
+ string = None
+ for f in self.fds:
+ if string is None:
+ string = f.read(remain)
+ else:
+ string += f.read(remain)
+ remain = size - len(string)
+ if remain == 0:
+ break
+ elif remain < 0:
+ remain = -1
+ return string
+
+ def readline(self, size=-1):
+ remain = size
+ string = None
+ for f in self.fds:
+ if string is None:
+ string = f.readline(remain)
+ else:
+ string += f.readline(remain)
+ if isinstance(string, text_type):
+ if string.endswith("\n"):
+ break
+ else:
+ if string.endswith(b"\n"):
+ break
+ remain = size - len(string)
+ if remain == 0:
+ break
+ elif remain < 0:
+ remain = -1
+ return string
+
+
+class CountFileDescriptor(object):
+ def __init__(self, f):
+ self.f = f
+ self.position = 0
+
+ def close(self):
+ return self.f.close()
+
+ def closed(self):
+ return self.f.closed()
+
+ def fileno(self):
+ return self.f.flieno()
+
+ def flush(self):
+ return self.f.flush()
+
+ def isatty(self):
+ return self.f.isatty()
+
+ def readbale(self):
+ return self.f.readable()
+
+ def readline(self, size=-1):
+ line = self.f.readline(size)
+ self.position += len(line)
+ return line
+
+ def readlines(self, hint=-1):
+ lines = self.f.readlines(hint)
+ for line in lines:
+ self.position += len(line)
+ return lines
+
+ def seek(self, offset, whence=0):
+ raise RuntimeError("Can't use seek")
+
+ def seekable(self):
+ return False
+
+ def tell(self):
+ return self.f.tell()
+
+ def truncate(self, size=None):
+ return self.f.trauncate(size)
+
+ def writable(self):
+ return self.f.writable()
+
+ def writelines(self, lines):
+ for line in lines:
+ self.position += len(line)
+ return self.f.writelines(lines)
+
+ def __del__(self):
+ return self.__del__()
+
+ def read(self, size=-1):
+ data = self.f.read(size)
+ self.position += len(data)
+ return data
+
+ def readall(self):
+ data = self.f.readall()
+ self.position += len(data)
+ return data
+
+ def readinfo(self, b):
+ nbyte = self.f.readinfo(b)
+ self.position += nbyte
+ return nbyte
+
+ def write(self, b):
+ self.position += b
+ self.write(b)
+
+
+def parse_specifier(specifier):
+ """A utility to parse "specifier"
+
+ Args:
+ specifier (str):
+ Returns:
+ parsed_dict (OrderedDict):
+ Like {'ark': 'file.ark', 'scp': 'file.scp'}
+
+
+ >>> d = parse_specifier('ark,t,scp:file.ark,file.scp')
+ >>> print(d['ark,t'])
+ file.ark
+
+ """
+ sp = specifier.split(":", 1)
+ if len(sp) != 2:
+ if ":" not in specifier:
+ raise ValueError(
+ "The output file must be specified with "
+ "kaldi-specifier style,"
+ " e.g. ark,scp:out.ark,out.scp, but you gave as "
+ "{}".format(specifier)
+ )
+
+ types, files = sp
+ types = types.split(",")
+ if "ark" not in types and "scp" not in types:
+ raise ValueError(
+ "One of/both ark and scp is required: "
+ "e.g. ark,scp:out.ark,out.scp: "
+ "{}".format(specifier)
+ )
+ elif "ark" in types and "scp" in types:
+ if "," not in files:
+ raise ValueError(
+ "You specified both ark and scp, "
+ "but a file path is given: "
+ "e.g. ark,scp:out.ark,out.scp: {}".format(specifier)
+ )
+ files = files.split(",", 1)
+ else:
+ files = [files]
+
+ spec_dict = {
+ "ark": None,
+ "scp": None,
+ "t": False, # text
+ "o": False, # once
+ "p": False, # permissive
+ "f": False, # flush
+ "s": False, # sorted
+ "cs": False, # called-sorted
+ }
+ for t in types:
+ if t not in spec_dict:
+ raise ValueError("Unknown option {}({})".format(t, types))
+ if t in ("scp", "ark"):
+ if spec_dict[t] is not None:
+ raise ValueError("You specified {} twice".format(t))
+ spec_dict[t] = files.pop(0)
+ else:
+ spec_dict[t] = True
+
+ return spec_dict
+
+
+class LazyLoader(MutableMapping):
+ """Don't use this class directly"""
+
+ def __init__(self, loader):
+ self._dict = {}
+ self._loader = loader
+
+ def __repr__(self):
+ return "LazyLoader [{} keys]".format(len(self))
+
+ def __getitem__(self, key):
+ ark_name = self._dict[key]
+ try:
+ return self._loader(ark_name)
+ except Exception:
+ warnings.warn('An error happens at loading "{}"'.format(ark_name))
+ raise
+
+ def __setitem__(self, key, value):
+ self._dict[key] = value
+
+ def __delitem__(self, key):
+ del self._dict[key]
+
+ def __iter__(self):
+ return self._dict.__iter__()
+
+ def __len__(self):
+ return len(self._dict)
+
+ def __contains__(self, item):
+ return item in self._dict
+
+
+def seekable(f):
+ if hasattr(f, "seekable"):
+ return f.seekable()
+
+ # For Py2
+ else:
+ if hasattr(f, "tell"):
+ try:
+ f.tell()
+ except (IOError, OSError):
+ return False
+ else:
+ return True
+ else:
+ return False
+
+
+class LimitedSizeDict(MutableMapping):
+ def __init__(self, maxsize):
+ self._maxsize = maxsize
+ self.data = OrderedDict()
+
+ def __repr__(self):
+ return repr(self.data)
+
+ def __setitem__(self, key, value):
+ if len(self) >= self._maxsize:
+ self.data.pop(next(iter(self.data)))
+
+ self.data[key] = value
+
+ def __getitem__(self, item):
+ return self.data[item]
+
+ def __delitem__(self, key):
+ self._maxsize -= 1
+ del self.data[key]
+
+ def __iter__(self):
+ return iter(self.data)
+
+ def __len__(self):
+ return len(self.data)
diff --git a/runtime/Lib/site-packages/kaldiio/wavio.py b/runtime/Lib/site-packages/kaldiio/wavio.py
new file mode 100644
index 0000000000000000000000000000000000000000..c389c7ad6cd1c1423d31554adff5465d5c9f0386
--- /dev/null
+++ b/runtime/Lib/site-packages/kaldiio/wavio.py
@@ -0,0 +1,56 @@
+from __future__ import unicode_literals
+
+import numpy as np
+
+import kaldiio.python_wave as wave
+
+
+def read_wav(fd, return_size=False):
+ wd = wave.open(fd)
+ rate = wd.getframerate()
+ nchannels = wd.getnchannels()
+ nbytes = wd.getsampwidth()
+ if nbytes == 1:
+ # 8bit-PCM is unsigned
+ dtype = "uint8"
+ elif nbytes == 2:
+ dtype = "int16"
+ else:
+ raise ValueError("bytes_per_sample must be 1, 2, 4 or 8")
+ data = wd.readframes(wd.getnframes())
+ size = 44 + len(data)
+ array = np.frombuffer(data, dtype=np.dtype(dtype))
+ if nchannels > 1:
+ array = array.reshape(-1, nchannels)
+
+ if return_size:
+ return (rate, array), size
+ else:
+ return rate, array
+
+
+def write_wav(fd, rate, array):
+ if array.dtype == np.uint8:
+ sampwidth = 1
+ elif array.dtype == np.int16:
+ sampwidth = 2
+ else:
+ raise ValueError("Not Supported dtype {}".format(array.dtype))
+
+ if array.ndim == 2:
+ nchannels = array.shape[1]
+ elif array.ndim == 1:
+ nchannels = 1
+ else:
+ raise ValueError(
+ "Not Supported dimension: 0 or 1, but got {}".format(array.ndim)
+ )
+
+ w = wave.Wave_write(fd)
+ w.setnchannels(nchannels)
+ w.setsampwidth(sampwidth)
+ w.setframerate(rate)
+ data = array.tobytes()
+ w.writeframes(data)
+
+ return 44 + len(data)
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/INSTALLER b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/LICENSE b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..19cac54a1c255c89bf3f012eadd1116eb0570d31
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/LICENSE
@@ -0,0 +1,71 @@
+=========================
+ The Kiwi licensing terms
+=========================
+Kiwi is licensed under the terms of the Modified BSD License (also known as
+New or Revised BSD), as follows:
+
+Copyright (c) 2013, Nucleic Development Team
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+Neither the name of the Nucleic Development Team nor the names of its
+contributors may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+About Kiwi
+----------
+Chris Colbert began the Kiwi project in December 2013 in an effort to
+create a blisteringly fast UI constraint solver. Chris is still the
+project lead.
+
+The Nucleic Development Team is the set of all contributors to the Nucleic
+project and its subprojects.
+
+The core team that coordinates development on GitHub can be found here:
+http://github.com/nucleic. The current team consists of:
+
+* Chris Colbert
+
+Our Copyright Policy
+--------------------
+Nucleic uses a shared copyright model. Each contributor maintains copyright
+over their contributions to Nucleic. But, it is important to note that these
+contributions are typically only changes to the repositories. Thus, the Nucleic
+source code, in its entirety is not the copyright of any single person or
+institution. Instead, it is the collective copyright of the entire Nucleic
+Development Team. If individual contributors want to maintain a record of what
+changes/contributions they have specific copyright on, they should indicate
+their copyright in the commit message of the change, when they commit the
+change to one of the Nucleic repositories.
+
+With this in mind, the following banner should be used in any source code file
+to indicate the copyright and license terms:
+
+#------------------------------------------------------------------------------
+# Copyright (c) 2013, Nucleic Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file LICENSE, distributed with this software.
+#------------------------------------------------------------------------------
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/METADATA b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..48338fe25ed4c016424ab090cfcfdee327c78cb8
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/METADATA
@@ -0,0 +1,106 @@
+Metadata-Version: 2.1
+Name: kiwisolver
+Version: 1.4.4
+Summary: A fast implementation of the Cassowary constraint solver
+Author-email: The Nucleic Development Team
+Maintainer-email: "Matthieu C. Dartiailh"
+License: =========================
+ The Kiwi licensing terms
+ =========================
+ Kiwi is licensed under the terms of the Modified BSD License (also known as
+ New or Revised BSD), as follows:
+ Copyright (c) 2013, Nucleic Development Team
+ All rights reserved.
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice, this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+ Neither the name of the Nucleic Development Team nor the names of its
+ contributors may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ About Kiwi
+ ----------
+ Chris Colbert began the Kiwi project in December 2013 in an effort to
+ create a blisteringly fast UI constraint solver. Chris is still the
+ project lead.
+ The Nucleic Development Team is the set of all contributors to the Nucleic
+ project and its subprojects.
+ The core team that coordinates development on GitHub can be found here:
+ http://github.com/nucleic. The current team consists of:
+ * Chris Colbert
+ Our Copyright Policy
+ --------------------
+ Nucleic uses a shared copyright model. Each contributor maintains copyright
+ over their contributions to Nucleic. But, it is important to note that these
+ contributions are typically only changes to the repositories. Thus, the Nucleic
+ source code, in its entirety is not the copyright of any single person or
+ institution. Instead, it is the collective copyright of the entire Nucleic
+ Development Team. If individual contributors want to maintain a record of what
+ changes/contributions they have specific copyright on, they should indicate
+ their copyright in the commit message of the change, when they commit the
+ change to one of the Nucleic repositories.
+ With this in mind, the following banner should be used in any source code file
+ to indicate the copyright and license terms:
+ #------------------------------------------------------------------------------
+ # Copyright (c) 2013, Nucleic Development Team.
+ #
+ # Distributed under the terms of the Modified BSD License.
+ #
+ # The full license is in the file LICENSE, distributed with this software.
+ #------------------------------------------------------------------------------
+Project-URL: homepage, https://github.com/nucleic/kiwi
+Project-URL: documentation, https://kiwisolver.readthedocs.io/en/latest/
+Project-URL: repository, https://github.com/nucleic/kiwi
+Project-URL: changelog, https://github.com/nucleic/kiwi/blob/main/releasenotes.rst
+Classifier: License :: OSI Approved :: BSD License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Requires-Python: >=3.7
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: typing-extensions ; python_version < "3.8"
+
+Welcome to Kiwi
+===============
+
+.. image:: https://travis-ci.org/nucleic/kiwi.svg?branch=main
+ :target: https://travis-ci.org/nucleic/kiwi
+.. image:: https://github.com/nucleic/kiwi/workflows/Continuous%20Integration/badge.svg
+ :target: https://github.com/nucleic/kiwi/actions
+.. image:: https://github.com/nucleic/kiwi/workflows/Documentation%20building/badge.svg
+ :target: https://github.com/nucleic/kiwi/actions
+.. image:: https://codecov.io/gh/nucleic/kiwi/branch/main/graph/badge.svg
+ :target: https://codecov.io/gh/nucleic/kiwi
+.. image:: https://readthedocs.org/projects/kiwisolver/badge/?version=latest
+ :target: https://kiwisolver.readthedocs.io/en/latest/?badge=latest
+ :alt: Documentation Status
+
+Kiwi is an efficient C++ implementation of the Cassowary constraint solving
+algorithm. Kiwi is an implementation of the algorithm based on the
+`seminal Cassowary paper `_.
+It is *not* a refactoring of the original C++ solver. Kiwi has been designed
+from the ground up to be lightweight and fast. Kiwi ranges from 10x to 500x
+faster than the original Cassowary solver with typical usecases gaining a 40x
+improvement. Memory savings are consistently > 5x.
+
+In addition to the C++ solver, Kiwi ships with hand-rolled Python bindings for
+Python 3.7+.
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/RECORD b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..077dfa945b2925532ed2d329bb0308d2ebb5c040
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/RECORD
@@ -0,0 +1,11 @@
+kiwisolver-1.4.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+kiwisolver-1.4.4.dist-info/LICENSE,sha256=mcfCJHgDN3ly03E8EwtAsjyyZ7oHx8X46G0vh6wv1kY,3350
+kiwisolver-1.4.4.dist-info/METADATA,sha256=GsOWfHvjU7M92Fi68cjIA_kZsoFgaCQIotswChWq4IM,6325
+kiwisolver-1.4.4.dist-info/RECORD,,
+kiwisolver-1.4.4.dist-info/WHEEL,sha256=fVcVlLzi8CGi_Ul8vjMdn8gER25dn5GBg9E6k9z41-Y,100
+kiwisolver-1.4.4.dist-info/top_level.txt,sha256=BhbDDMpSTWllCy1Ln0h8gA5zHkrOZogmbr5Ngm3vOhM,15
+kiwisolver/__init__.py,sha256=Rhzve6yZRGpZ_jc0pcbwCEnHSQsuS0f-2dq2SLnw7CQ,1025
+kiwisolver/__pycache__/__init__.cpython-39.pyc,,
+kiwisolver/_cext.cp39-win_amd64.pyd,sha256=E-IFID0cSVgRfNIx9dqA6uscC8MzDxKUeo_jp4eSZ6g,114688
+kiwisolver/_cext.pyi,sha256=ME4eiAXTly9w5FUk3COxFsTpD2pJwGsWHw3C2z2JFx8,9046
+kiwisolver/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/WHEEL b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d5a98374e27e610e1b9b96bd43954d22ff48a4c2
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: bdist_wheel (0.37.1)
+Root-Is-Purelib: false
+Tag: cp39-cp39-win_amd64
+
diff --git a/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/top_level.txt b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..026ef43fa609d83f6ffd5efb15a7adc13cbe1cd8
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver-1.4.4.dist-info/top_level.txt
@@ -0,0 +1,2 @@
+kiwisolver
+src
diff --git a/runtime/Lib/site-packages/kiwisolver/__init__.py b/runtime/Lib/site-packages/kiwisolver/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c230a961263e886ba0c23d112ab0bc2ce7062ad
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver/__init__.py
@@ -0,0 +1,40 @@
+# --------------------------------------------------------------------------------------
+# Copyright (c) 2013-2022, Nucleic Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file LICENSE, distributed with this software.
+# --------------------------------------------------------------------------------------
+from ._cext import (
+ BadRequiredStrength,
+ Constraint,
+ DuplicateConstraint,
+ DuplicateEditVariable,
+ Expression,
+ Solver,
+ Term,
+ UnknownConstraint,
+ UnknownEditVariable,
+ UnsatisfiableConstraint,
+ Variable,
+ __kiwi_version__,
+ __version__,
+ strength,
+)
+
+__all__ = [
+ "BadRequiredStrength",
+ "DuplicateConstraint",
+ "DuplicateEditVariable",
+ "UnknownConstraint",
+ "UnknownEditVariable",
+ "UnsatisfiableConstraint",
+ "strength",
+ "Variable",
+ "Term",
+ "Expression",
+ "Constraint",
+ "Solver",
+ "__version__",
+ "__kiwi_version__",
+]
diff --git a/runtime/Lib/site-packages/kiwisolver/_cext.cp39-win_amd64.pyd b/runtime/Lib/site-packages/kiwisolver/_cext.cp39-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..adbc197b528060dcabbb55e9f1ee223b477a5bbb
Binary files /dev/null and b/runtime/Lib/site-packages/kiwisolver/_cext.cp39-win_amd64.pyd differ
diff --git a/runtime/Lib/site-packages/kiwisolver/_cext.pyi b/runtime/Lib/site-packages/kiwisolver/_cext.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e73659bfeec1a394e1a1f6c1c1446ce11e64450f
--- /dev/null
+++ b/runtime/Lib/site-packages/kiwisolver/_cext.pyi
@@ -0,0 +1,234 @@
+# --------------------------------------------------------------------------------------
+# Copyright (c) 2021, Nucleic Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the file LICENSE, distributed with this software.
+# --------------------------------------------------------------------------------------
+
+from typing import Any, Iterable, NoReturn, Tuple, type_check_only
+
+try:
+ from typing import Literal
+except ImportError:
+ from typing_extensions import Literal # type: ignore
+
+__version__: str
+__kiwi_version__: str
+
+# --- Exceptions
+
+class BadRequiredStrength(Exception): ...
+class DuplicateConstraint(Exception): ...
+class DuplicateEditVariable(Exception): ...
+class UnknownConstraint(Exception): ...
+class UnknownEditVariable(Exception): ...
+class UnsatisfiableConstraint(Exception): ...
+
+# Types
+@type_check_only
+class Strength:
+ @property
+ def weak(self) -> float: ...
+ @property
+ def medium(self) -> float: ...
+ @property
+ def strong(self) -> float: ...
+ @property
+ def required(self) -> float: ...
+ def create(
+ self,
+ a: int | float,
+ b: int | float,
+ c: int | float,
+ weight: int | float = 1.0,
+ /,
+ ) -> float: ...
+
+# This is meant as a singleton and users should not access the Strength type.
+strength: Strength
+
+class Variable:
+ """Variable to express a constraint in a solver."""
+
+ __hash__: None # type: ignore
+ def __init__(self, name: str = "", context: Any = None, /) -> None: ...
+ def name(self) -> str:
+ """Get the name of the variable."""
+ ...
+ def setName(self, name: str, /) -> Any:
+ """Set the name of the variable."""
+ ...
+ def value(self) -> float:
+ """Get the current value of the variable."""
+ ...
+ def context(self) -> Any:
+ """Get the context object associated with the variable."""
+ ...
+ def setContext(self, context: Any, /) -> Any:
+ """Set the context object associated with the variable."""
+ ...
+ def __neg__(self) -> Term: ...
+ def __add__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __radd__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __sub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __rsub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __mul__(self, other: float) -> Term: ...
+ def __rmul__(self, other: float) -> Term: ...
+ def __truediv__(self, other: float) -> Term: ...
+ def __rtruediv__(self, other: float) -> Term: ...
+ def __eq__(self, other: float | Variable | Term | Expression) -> Constraint: ... # type: ignore
+ def __ge__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __le__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __ne__(self, other: Any) -> NoReturn: ...
+ def __gt__(self, other: Any) -> NoReturn: ...
+ def __lt__(self, other: Any) -> NoReturn: ...
+
+class Term:
+ """Product of a variable by a constant pre-factor."""
+
+ __hash__: None # type: ignore
+ def __init__(
+ self, variable: Variable, coefficient: int | float = 1.0, / # noqa
+ ) -> None: ...
+ def coefficient(self) -> float:
+ """Get the coefficient for the term."""
+ ...
+ def variable(self) -> Variable:
+ """Get the variable for the term."""
+ ...
+ def value(self) -> float:
+ """Get the value for the term."""
+ ...
+ def __neg__(self) -> Term: ...
+ def __add__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __radd__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __sub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __rsub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __mul__(self, other: float) -> Term: ...
+ def __rmul__(self, other: float) -> Term: ...
+ def __truediv__(self, other: float) -> Term: ...
+ def __rtruediv__(self, other: float) -> Term: ...
+ def __eq__(self, other: float | Variable | Term | Expression) -> Constraint: ... # type: ignore
+ def __ge__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __le__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __ne__(self, other: Any) -> NoReturn: ...
+ def __gt__(self, other: Any) -> NoReturn: ...
+ def __lt__(self, other: Any) -> NoReturn: ...
+
+class Expression:
+ """Sum of terms and an additional constant."""
+
+ __hash__: None # type: ignore
+ def __init__(
+ self, terms: Iterable[Term], constant: int | float = 0.0, / # noqa
+ ) -> None: ...
+ def constant(self) -> float:
+ "" "Get the constant for the expression." ""
+ ...
+ def terms(self) -> Tuple[Term, ...]:
+ """Get the tuple of terms for the expression."""
+ ...
+ def value(self) -> float:
+ """Get the value for the expression."""
+ ...
+ def __neg__(self) -> Expression: ...
+ def __add__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __radd__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __sub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __rsub__(self, other: float | Variable | Term | Expression) -> Expression: ...
+ def __mul__(self, other: float) -> Expression: ...
+ def __rmul__(self, other: float) -> Expression: ...
+ def __truediv__(self, other: float) -> Expression: ...
+ def __rtruediv__(self, other: float) -> Expression: ...
+ def __eq__(self, other: float | Variable | Term | Expression) -> Constraint: ... # type: ignore
+ def __ge__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __le__(self, other: float | Variable | Term | Expression) -> Constraint: ...
+ def __ne__(self, other: Any) -> NoReturn: ...
+ def __gt__(self, other: Any) -> NoReturn: ...
+ def __lt__(self, other: Any) -> NoReturn: ...
+
+class Constraint:
+ def __init__(
+ self,
+ expression: Expression,
+ op: Literal["=="] | Literal["<="] | Literal[">="],
+ strength: float
+ | Literal["weak"]
+ | Literal["medium"]
+ | Literal["strong"]
+ | Literal["required"] = "required",
+ /,
+ ) -> None: ...
+ def expression(self) -> Expression:
+ """Get the expression object for the constraint."""
+ ...
+ def op(self) -> Literal["=="] | Literal["<="] | Literal[">="]:
+ """Get the relational operator for the constraint."""
+ ...
+ def strength(self) -> float:
+ """Get the strength for the constraint."""
+ ...
+ def __or__(
+ self,
+ other: float
+ | Literal["weak"]
+ | Literal["medium"]
+ | Literal["strong"]
+ | Literal["required"],
+ ) -> Constraint: ...
+ def __ror__(
+ self,
+ other: float
+ | Literal["weak"]
+ | Literal["medium"]
+ | Literal["strong"]
+ | Literal["required"],
+ ) -> Constraint: ...
+
+class Solver:
+ """Kiwi solver class."""
+
+ def __init__(self) -> None: ...
+ def addConstraint(self, constraint: Constraint, /) -> None:
+ """Add a constraint to the solver."""
+ ...
+ def removeConstraint(self, constraint: Constraint, /) -> None:
+ """Remove a constraint from the solver."""
+ ...
+ def hasConstraint(self, constraint: Constraint, /) -> bool:
+ """Check whether the solver contains a constraint."""
+ ...
+ def addEditVariable(
+ self,
+ variable: Variable,
+ strength: float
+ | Literal["weak"]
+ | Literal["medium"]
+ | Literal["strong"]
+ | Literal["required"],
+ /,
+ ) -> None:
+ """Add an edit variable to the solver."""
+ ...
+ def removeEditVariable(self, variable: Variable, /) -> None:
+ """Remove an edit variable from the solver."""
+ ...
+ def hasEditVariable(self, variable: Variable, /) -> bool:
+ """Check whether the solver contains an edit variable."""
+ ...
+ def suggestValue(self, variable: Variable, value: int | float, /) -> None:
+ """Suggest a desired value for an edit variable."""
+ ...
+ def updateVariables(self) -> None:
+ """Update the values of the solver variables."""
+ ...
+ def reset(self) -> None:
+ """Reset the solver to the initial empty starting condition."""
+ ...
+ def dump(self) -> None:
+ """Dump a representation of the solver internals to stdout."""
+ ...
+ def dumps(self) -> str:
+ """Dump a representation of the solver internals to a string."""
+ ...
diff --git a/runtime/Lib/site-packages/kiwisolver/py.typed b/runtime/Lib/site-packages/kiwisolver/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
|