Upload 234 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/INSTALLER +1 -0
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/METADATA +295 -0
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/RECORD +10 -0
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/REQUESTED +0 -0
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/WHEEL +5 -0
- runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/top_level.txt +1 -0
- runtime/Lib/site-packages/LangSegment/LangSegment.py +837 -0
- runtime/Lib/site-packages/LangSegment/__init__.py +8 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/INSTALLER +1 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/LICENSE.txt +29 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/METADATA +167 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/RECORD +229 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/WHEEL +5 -0
- runtime/Lib/site-packages/joblib-1.2.0.dist-info/top_level.txt +1 -0
- runtime/Lib/site-packages/joblib/__init__.py +138 -0
- runtime/Lib/site-packages/joblib/_cloudpickle_wrapper.py +17 -0
- runtime/Lib/site-packages/joblib/_dask.py +368 -0
- runtime/Lib/site-packages/joblib/_deprecated_format_stack.py +397 -0
- runtime/Lib/site-packages/joblib/_deprecated_my_exceptions.py +115 -0
- runtime/Lib/site-packages/joblib/_memmapping_reducer.py +668 -0
- runtime/Lib/site-packages/joblib/_multiprocessing_helpers.py +53 -0
- runtime/Lib/site-packages/joblib/_parallel_backends.py +653 -0
- runtime/Lib/site-packages/joblib/_store_backends.py +414 -0
- runtime/Lib/site-packages/joblib/_utils.py +44 -0
- runtime/Lib/site-packages/joblib/backports.py +190 -0
- runtime/Lib/site-packages/joblib/compressor.py +570 -0
- runtime/Lib/site-packages/joblib/disk.py +136 -0
- runtime/Lib/site-packages/joblib/executor.py +120 -0
- runtime/Lib/site-packages/joblib/externals/__init__.py +0 -0
- runtime/Lib/site-packages/joblib/externals/cloudpickle/__init__.py +8 -0
- runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle.py +948 -0
- runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py +844 -0
- runtime/Lib/site-packages/joblib/externals/cloudpickle/compat.py +18 -0
- runtime/Lib/site-packages/joblib/externals/loky/__init__.py +32 -0
- runtime/Lib/site-packages/joblib/externals/loky/_base.py +28 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/__init__.py +14 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/_posix_reduction.py +64 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/_win_reduction.py +60 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/context.py +304 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/fork_exec.py +42 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py +182 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_win32.py +156 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/process.py +58 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/queues.py +192 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/reduction.py +219 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/resource_tracker.py +371 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/spawn.py +242 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/synchronize.py +391 -0
- runtime/Lib/site-packages/joblib/externals/loky/backend/utils.py +174 -0
- runtime/Lib/site-packages/joblib/externals/loky/cloudpickle_wrapper.py +100 -0
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,295 @@
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: LangSegment
|
| 3 |
+
Version: 0.3.3
|
| 4 |
+
Summary: This is a multilingual tokenization tool that currently supports for zh/ja/en/ko, and more languages.
|
| 5 |
+
Home-page: https://github.com/juntaosun/LangSegment
|
| 6 |
+
Author: sunnyboxs
|
| 7 |
+
License: BSD
|
| 8 |
+
Keywords: language detection,language identification,langid,langid.py,nlp,language
|
| 9 |
+
Platform: UNKNOWN
|
| 10 |
+
Classifier: Intended Audience :: Science/Research
|
| 11 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 19 |
+
Requires-Python: >=3.6
|
| 20 |
+
Description-Content-Type: text/markdown
|
| 21 |
+
Requires-Dist: numpy >=1.19.5
|
| 22 |
+
Requires-Dist: py3langid >=0.2.2
|
| 23 |
+
|
| 24 |
+
# LangSegment
|
| 25 |
+
**<font size=3 color='#00FFFF'>简介:它是一个强大的多语言(97种语言)的混合文本自动分词工具。[中/日/英/韩:已测试]</font>**
|
| 26 |
+
**<font size=3 color='#00FFFF'>主要用途:“一口气” 让你的 TTS 语音合成项目 VITS 说出多国语言,多语种混合文本的分词推理,和预处理训练。</font>**
|
| 27 |
+
**<font size=3 color='#00FFFF'>分词支持:中文/英文/日文/韩语/法语/越南语/俄语/泰语/</font>**
|
| 28 |
+
|
| 29 |
+

|
| 30 |
+
|
| 31 |
+
它基于 py3langid 的扩展实现(>=python3.6)。
|
| 32 |
+
``LangSegment`` It is a multi-lingual (97 languages) text content automatic recognition and segmentation tool.
|
| 33 |
+
The main purposes are: front-end for various TTS (Text-to-Speech) synthesis projects, preprocessing of multilingual text mixing for both training and inference.
|
| 34 |
+
|
| 35 |
+
>Implementation based on py3langid,See LICENSE file for more info.
|
| 36 |
+
https://github.com/adbar/py3langid
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
功能:将文章或句子里的例如(中/英/日/韩),按不同语言自动识别分词,使文本更适合AI处理。
|
| 40 |
+
本代码专为各种 TTS 项目的前端文本多语种混合标注区分,多语言混合训练和推理而编写。
|
| 41 |
+
|
| 42 |
+
## 最近更新:News
|
| 43 |
+
* 版本:v0.3.3 fix (更新帮助见下文)。
|
| 44 |
+
* 添加支持: "zh"中文(数字拼音pinyin),保留多音字(音素)指定。
|
| 45 |
+
* 添加支持: "ru"俄语Russian / "th"泰语Thai。
|
| 46 |
+
* 添加支持: "fr"法语French / "vi"越南语Vietnamese。
|
| 47 |
+
* 语言优先级,置信度评分和阀值。
|
| 48 |
+
* 优化字符处理。fix: LangSegment.setfilters
|
| 49 |
+
* 更细致的处理,中日英韩,分词更精准!
|
| 50 |
+
* 多语言过滤组功能(默认:中/英/日/韩)!帮您自动清理不需要的语言内容。
|
| 51 |
+
* 添加 WebUI 可视化界面,运行 app.py 即可快捷体验(如图所示)。
|
| 52 |
+
|
| 53 |
+
* <a href='https://huggingface.co/spaces/sunnyboxs/LangSegment'><u>点击在线体验,感谢 huggingface 提供服务支持</u>:<img src='https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue'></a>
|
| 54 |
+
|
| 55 |
+

|
| 56 |
+
|
| 57 |
+
```python
|
| 58 |
+
# Gradio demo:To use our gradio demo locally:
|
| 59 |
+
# 运行脚本,打开浏览器 gradio webui 界面,开始快速体验。(gradio==3.50.2)
|
| 60 |
+
python app.py
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## 完全可控:支持
|
| 64 |
+
* (1)自动分词:“韩语中的오빠读什么呢?あなたの体育の先生は誰ですか? 此次带来了四款iPhone 15系列机型”
|
| 65 |
+
* (2)手动分词:“你的名字叫\<ja\>佐々木?\<ja\>吗?”
|
| 66 |
+
|
| 67 |
+
## 语言标签:支持
|
| 68 |
+
>分词语言标签:它和html类似,它需要成对出现 \<zh\>内容\<zh\> 或者 \<zh\>内容\</zh\>。
|
| 69 |
+
本处理结果主要针对(中文=zh , 日文=ja , 英文=en , 韩语=ko), 实际上可支持多达 97 种不同的语言混合处理。
|
| 70 |
+
|
| 71 |
+
## 安装方法:Install (推荐使用官方源)
|
| 72 |
+
```bash
|
| 73 |
+
# 首次安装:官方源(推荐)
|
| 74 |
+
pip3 install LangSegment -i https://pypi.org/simple
|
| 75 |
+
# 后续版本升级或更新:
|
| 76 |
+
pip3 install LangSegment -i https://pypi.org/simple --upgrade
|
| 77 |
+
|
| 78 |
+
# 或者,国内镜像(国内镜像同步慢几天,可能会导致您无法极时获得最新版本!!!):
|
| 79 |
+
# pip3 install LangSegment -i https://pypi.mirrors.ustc.edu.cn/simple
|
| 80 |
+
```
|
| 81 |
+
## 使用示例:Example Input
|
| 82 |
+
>示例中的句子,同时包含中日英韩4种语言,接下来将对它们按不同语种进行分词,以方便各种TTS项目进行语音合成。
|
| 83 |
+
```python
|
| 84 |
+
|
| 85 |
+
# pip3 install LangSegment -i https://pypi.org/simple
|
| 86 |
+
import LangSegment
|
| 87 |
+
|
| 88 |
+
# input text example 示例:
|
| 89 |
+
text = "你的名字叫<ja>佐々木?<ja>吗?韩语中的오빠读什么呢?あなたの体育の先生は\
|
| 90 |
+
誰ですか? 此次发布会带来了四款iPhone 15系列机型\
|
| 91 |
+
和三款Apple Watch等一系列新品,这次的iPad Air采用了LCD屏幕"
|
| 92 |
+
|
| 93 |
+
# example
|
| 94 |
+
langlist = LangSegment.getTexts(text)
|
| 95 |
+
|
| 96 |
+
# output list : {'lang': 'zh', 'text': '...'}
|
| 97 |
+
print("=================================")
|
| 98 |
+
for line in langlist:
|
| 99 |
+
print(line)
|
| 100 |
+
print("=================================")
|
| 101 |
+
```
|
| 102 |
+
## 处理结果:Example Output
|
| 103 |
+
```python
|
| 104 |
+
# output 输出列表行:lang=语言,text=内容
|
| 105 |
+
# ===========================================================================
|
| 106 |
+
# {'lang': 'zh', 'text': '你的名字叫'}
|
| 107 |
+
# {'lang': 'ja', 'text': '佐々木?'}
|
| 108 |
+
# {'lang': 'zh', 'text': '吗?韩语中的'}
|
| 109 |
+
# {'lang': 'ko', 'text': '오빠'}
|
| 110 |
+
# {'lang': 'zh', 'text': '读什么呢?'}
|
| 111 |
+
# {'lang': 'ja', 'text': 'あなたの体育の先生は誰ですか?'}
|
| 112 |
+
# {'lang': 'zh', 'text': ' 此次发布会带来了四款'}
|
| 113 |
+
# {'lang': 'en', 'text': 'i Phone'}
|
| 114 |
+
# {'lang': 'zh', 'text': ' 15系列机型和三款'}
|
| 115 |
+
# {'lang': 'en', 'text': 'Apple Watch'}
|
| 116 |
+
# {'lang': 'zh', 'text': '等一系列新品,这次的'}
|
| 117 |
+
# {'lang': 'en', 'text': 'i Pad Air'}
|
| 118 |
+
# {'lang': 'zh', 'text': '采用了'}
|
| 119 |
+
# {'lang': 'en', 'text': 'L C D'}
|
| 120 |
+
# {'lang': 'zh', 'text': '屏幕'}
|
| 121 |
+
# ===========================================================================
|
| 122 |
+
# 其中英文缩写字母如“LCD”,英文标准发音为“L-C-D”,
|
| 123 |
+
# 而在语音合成TTS项目中,一般用空格隔开字母来单独发音:“L C D”
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
## 英文拼读:支持
|
| 127 |
+
```python
|
| 128 |
+
TTS语音合成(英文字母)大小写拼读规则:
|
| 129 |
+
(1)需要单个字母发音就大写,比如:USA,USB,ChatGPT,LCD,GPU,CEO。
|
| 130 |
+
(2)其它情况正常拼读,就按正常拼写。比如:Nvidia , Cuda 或者全小写 (nvidia , cuda )
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
## 拼音保留:支持(多音字)
|
| 134 |
+
> 版本支持:>= 0.3.2
|
| 135 |
+
> 常见需求:直接修改 TTS 的汉字读音,保留拼音输入。
|
| 136 |
+
```python
|
| 137 |
+
# 开启汉语拼音保留,(TTS标准:数字拼音格式),默认关闭。
|
| 138 |
+
LangSegment.setKeepPinyin(True)
|
| 139 |
+
|
| 140 |
+
# 汉字拼音指定示例:以下句子,括号中的拼音,均识别为中文。
|
| 141 |
+
text = "这个字的读音是角(jue2)色,而不是角(jiao3)色"
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
## 分词纠错:很重要!
|
| 145 |
+
>综上所述,“自动分词”已经极大的提高了我们的工作效率,但还是建议您对分词结果进行人工校对。
|
| 146 |
+
特别是中文与日文,存在大量汉字互用,这对自动分词是极具挑战性的,“分词纠错” 解决方案如下:
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
* (1)自动分词纠错:在中文与日文句子之间,打上句号。来辅助分词(自动上下文分词)。
|
| 150 |
+
* (2)手动分词纠错:您可手动添加语言标签\<ja\>,\<ko\>,\<zh\>,\<en\>等来辅助进行强制分词。
|
| 151 |
+
|
| 152 |
+
以下是语言标签分词详细示例:
|
| 153 |
+
```python
|
| 154 |
+
# 手动分词标签的应用示例,例如针对中日汉字有重叠,而需要在 TTS 中混合发音的情况:
|
| 155 |
+
# 分词标签内的文本将识别成日文ja内容,也可以写成<ja>内容</ja>
|
| 156 |
+
text = "你的名字叫<ja>佐々木?<ja>"
|
| 157 |
+
# 或者:
|
| 158 |
+
text = "你的名字叫<ja>佐々木?</ja>"
|
| 159 |
+
# 以上均能正确输出:
|
| 160 |
+
# 处理成中文-- {'lang': 'zh', 'text': '你的名字叫'}
|
| 161 |
+
# 处理成日文-- {'lang': 'ja', 'text': '佐々木?'}
|
| 162 |
+
```
|
| 163 |
+
自动分词能力目前主要针对中文(zh)/日文(ja)/英文(en)/韩文(ko),进行了特别优化。
|
| 164 |
+
它特别适合各种 TTS 前端文本多语种内容的混合分词(自动/手动),训练和推理使用。
|
| 165 |
+
|
| 166 |
+
```python
|
| 167 |
+
# 手动分词标签规范:<语言标签>文本内容</语言标签>
|
| 168 |
+
# ===========================================================================
|
| 169 |
+
# 如需手动标注,标签需要成对出现,如:“<ja>佐々木<ja>” 或者 “<ja>佐々木</ja>”
|
| 170 |
+
# 错误示范:“你的名字叫<ja>佐々木。” 此句子中出现的单个<ja>标签将被忽略,不会处理。
|
| 171 |
+
# ===========================================================================
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
## 语言过滤:支持
|
| 175 |
+
> 版本支持:>=0.2.0
|
| 176 |
+
语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
|
| 177 |
+
```python
|
| 178 |
+
# Set language filters
|
| 179 |
+
# 设置语言过滤功能,未指定的语言将被清除,使它完全适配您的TTS项目。
|
| 180 |
+
LangSegment.setfilters(["zh", "en", "ja", "ko"]) # 标准写法
|
| 181 |
+
# 或者写成:
|
| 182 |
+
# LangSegment.setfilters(["zh_en_ja_ko"]) # 写法1,过滤效果相同
|
| 183 |
+
# LangSegment.setfilters(["zh-en-ja-ko"]) # 写法2,过滤效果相同
|
| 184 |
+
# 获取过滤器:
|
| 185 |
+
# LangSegment.getfilters()
|
| 186 |
+
|
| 187 |
+
# 参数组合说明,以下是部份场景示例:
|
| 188 |
+
# ["zh"] # 按中文识别
|
| 189 |
+
# ["en"] # 按英文识别
|
| 190 |
+
# ["ja"] # 按日文识别
|
| 191 |
+
# ["ko"] # 按韩文识别
|
| 192 |
+
# ["zh_ja"] # 中日混合识别
|
| 193 |
+
# ["zh_en"] # 中英混合识别
|
| 194 |
+
# ["zh_ko"] # 中韩混合识别
|
| 195 |
+
# ["ja_en"] # 日英混合识别
|
| 196 |
+
# ["zh_ko_en"] # 中韩英混合识别
|
| 197 |
+
# 以上是示例,您可根据自己的TTS项目进行自由组合。
|
| 198 |
+
```
|
| 199 |
+
## 语言优先级:支持(纯数字输入示例)
|
| 200 |
+
> 版本支持:>=0.2.1
|
| 201 |
+
当我们在鉴别纯数字时,比如“123456”,全球通用。如果没有提供上下文,将无法区分归属(默认en)。
|
| 202 |
+
这时候,您只需调整语言优先级。就能准确识别。相关示例如下:
|
| 203 |
+
|
| 204 |
+
```python
|
| 205 |
+
# 仅输入独立纯数字:所有国家通用,因为没有提供上下文,所以无法区分语言归属
|
| 206 |
+
print(LangSegment.getTexts("123456789")) # 国际纯数字,默认输出:英文=en
|
| 207 |
+
|
| 208 |
+
# 调整过滤语言优先级,中文优先,数字按中文优先识别
|
| 209 |
+
LangSegment.setfilters(["zh","ja"])
|
| 210 |
+
print(LangSegment.getTexts("123456789")) # 识别输出:中文=zh
|
| 211 |
+
|
| 212 |
+
# 调整过滤语言优先级,日语优先,数字按日语优先识别
|
| 213 |
+
LangSegment.setfilters(["ja","zh"])
|
| 214 |
+
print(LangSegment.getTexts("123456789")) # 识别输出:日文=ja
|
| 215 |
+
|
| 216 |
+
# 调整过滤语言优先级,韩语优先,数字按韩语优先识别
|
| 217 |
+
LangSegment.setfilters(["ko","zh"])
|
| 218 |
+
print(LangSegment.getTexts("123456789")) # 识别输出:韩文=ko
|
| 219 |
+
|
| 220 |
+
# 识别输出:中文,(因为提供了上下文,汉字“编号:”)
|
| 221 |
+
LangSegment.setfilters(["ko","zh","en","ja"])
|
| 222 |
+
print(LangSegment.getTexts("编号:123456789")) # 提供上下文,识别输出:中文=zh
|
| 223 |
+
print(LangSegment.getTexts("Number:123456789")) # 提供上下文,识别输出:英文=en
|
| 224 |
+
print(LangSegment.getTexts("번호:123456789")) # 提供上下文,识别输出:韩文=ko
|
| 225 |
+
```
|
| 226 |
+
## 优先级与置信度:特殊示例
|
| 227 |
+
> 版本支持:>=0.2.1
|
| 228 |
+
语言优先级除了对输入的纯数字外,它对中文与日文也特别有用,以下是使用示例:
|
| 229 |
+
|
| 230 |
+
* 示例汉字词:“番号”,由于在中文和日语,两者使用几乎完全一样,在中日混合模式下。
|
| 231 |
+
```python
|
| 232 |
+
# 在中日混合下,默认情况为中文优先。
|
| 233 |
+
LangSegment.setfilters(["zh","ja","en","ko"])
|
| 234 |
+
# 默认处理:
|
| 235 |
+
print(LangSegment.getTexts("番号: 123456789"))
|
| 236 |
+
# [{'lang': 'zh', 'text': '番号: 123456789 ', 'score': 0.87188566}]
|
| 237 |
+
# 默认识别:中文=zh ,识别的参考置信度是:0.87
|
| 238 |
+
```
|
| 239 |
+
* 而此时,在中日混合模式下,我们希望它识别成:日语=ja。
|
| 240 |
+
```python
|
| 241 |
+
# 只需按如下调整过滤器的语言优先级。让 ja 优先于 zh 之前。
|
| 242 |
+
LangSegment.setfilters(["ja","zh","en","ko"])
|
| 243 |
+
# 再次处理:
|
| 244 |
+
print(LangSegment.getTexts("番号: 123456789"))
|
| 245 |
+
# [{'lang': 'ja', 'text': '番号: 123456789 ', 'score': 0.87188566}]
|
| 246 |
+
# 阀值的精准控制下,它被优先识别为我们希望的结果:日文=ja
|
| 247 |
+
|
| 248 |
+
# 您还可以添加语言标签:精准控制
|
| 249 |
+
print(LangSegment.getTexts("<ja>番号: 123456789</ja>"))
|
| 250 |
+
# 添加语言标签,正确输出:日文=ja
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
## 预览新增:法语(French)/越南语(Vietnamese)/俄语(Russian)/泰语(Thai)
|
| 254 |
+
> 版本支持:>=0.2.2 (法语(French)/越南语(Vietnamese))
|
| 255 |
+
> 版本支持:>=0.2.3 (俄语(Russian)/泰语(Thai))
|
| 256 |
+
> 法语和越南语,您只需在语言过滤器中添加,即可配合分词标签使用。
|
| 257 |
+
|
| 258 |
+
```python
|
| 259 |
+
# 自动分词启用设置:法语="fr" , 越南语="vi", "ru"俄语=Russian, "th"泰语=Thai
|
| 260 |
+
LangSegment.setfilters(["fr", "vi" , "zh", "ja", "ko", "en"])
|
| 261 |
+
|
| 262 |
+
# 可以随意搭配,比如您的TTS只需(越南语/中文),则仅需保留两个语言。
|
| 263 |
+
# LangSegment.setfilters(["vi" , "zh"])
|
| 264 |
+
|
| 265 |
+
# 对应的(法语fr和越南语vi)手动分词语言标签:
|
| 266 |
+
# <fr>Français</fr>、<vi>Tiếng Việt</vi>
|
| 267 |
+
```
|
| 268 |
+
>每个语种它们对应的语言分词标签: (ISO 639-1 codes given):
|
| 269 |
+
>* \<zh\>:中文 = Chinese
|
| 270 |
+
>* \<en\>:英语 = English
|
| 271 |
+
>* \<ja\>:日语 = Japanese
|
| 272 |
+
>* \<ko\>:韩语 = Korean
|
| 273 |
+
>* \<fr\>:法语 = French
|
| 274 |
+
>* \<vi\>:越南语 = Vietnamese
|
| 275 |
+
>* \<ru\>:俄语 = Russian
|
| 276 |
+
>* \<th\>:泰语 = Thai
|
| 277 |
+
>* 更多其它97个语种标签,在下方完整列表已经列出。
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
## 总结说明:
|
| 281 |
+
它经过了高达 97 种语言的预训练,相信它绝对能满足您的 TTS 语音合成项目所需。
|
| 282 |
+
comes pre-trained on 97 languages (ISO 639-1 codes given):
|
| 283 |
+
>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
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
---
|
| 287 |
+
---
|
| 288 |
+
> 备注:多语种混合文本转语音合成(TTS),中/日/英/韩/已完成测试。
|
| 289 |
+
其它语种未作具体测试,如有Bug和优化建议,欢迎提出或指正,感谢~。
|
| 290 |
+
Note: The speech synthesis test content is currently mainly for four categories: Chinese, Japanese, English and Korean.
|
| 291 |
+
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~
|
| 292 |
+
Special thanks to the following projects: [py3langid](https://github.com/adbar/py3langid)
|
| 293 |
+
---
|
| 294 |
+
---
|
| 295 |
+
|
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/RECORD
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LangSegment-0.3.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
LangSegment-0.3.3.dist-info/METADATA,sha256=-TyEKCRRg1NTF6tk9LlV88cL1aojbmKF24Cx-CJ8fTc,15251
|
| 3 |
+
LangSegment-0.3.3.dist-info/RECORD,,
|
| 4 |
+
LangSegment-0.3.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 5 |
+
LangSegment-0.3.3.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
|
| 6 |
+
LangSegment-0.3.3.dist-info/top_level.txt,sha256=Vg8k4ac6vg9w9gy7bI5JReoo-pLVXtmsmcfQCN4IaJw,12
|
| 7 |
+
LangSegment/LangSegment.py,sha256=QdBWPscz-4U9EWfKOlcgcs9733rMEajJmwVXRqSS_DU,44726
|
| 8 |
+
LangSegment/__init__.py,sha256=qgAenFaQR4zrmTgj4mhgBF4ccPvKF4M78phDZQzS0G4,278
|
| 9 |
+
LangSegment/__pycache__/LangSegment.cpython-39.pyc,,
|
| 10 |
+
LangSegment/__pycache__/__init__.cpython-39.pyc,,
|
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/REQUESTED
ADDED
|
File without changes
|
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.41.2)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
runtime/Lib/site-packages/LangSegment-0.3.3.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
LangSegment
|
runtime/Lib/site-packages/LangSegment/LangSegment.py
ADDED
|
@@ -0,0 +1,837 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file bundles language identification functions.
|
| 3 |
+
|
| 4 |
+
Modifications (fork): Copyright (c) 2021, Adrien Barbaresi.
|
| 5 |
+
|
| 6 |
+
Original code: Copyright (c) 2011 Marco Lui <saffsd@gmail.com>.
|
| 7 |
+
Based on research by Marco Lui and Tim Baldwin.
|
| 8 |
+
|
| 9 |
+
See LICENSE file for more info.
|
| 10 |
+
https://github.com/adbar/py3langid
|
| 11 |
+
|
| 12 |
+
Projects:
|
| 13 |
+
https://github.com/juntaosun/LangSegment
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import re
|
| 17 |
+
from collections import defaultdict
|
| 18 |
+
|
| 19 |
+
# import langid
|
| 20 |
+
# import py3langid as langid
|
| 21 |
+
# pip install py3langid==0.2.2
|
| 22 |
+
|
| 23 |
+
# 启用语言预测概率归一化,概率预测的分数。因此,实现重新规范化 产生 0-1 范围内的输出。
|
| 24 |
+
# langid disables probability normalization by default. For command-line usages of , it can be enabled by passing the flag.
|
| 25 |
+
# For probability normalization in library use, the user must instantiate their own . An example of such usage is as follows:
|
| 26 |
+
from py3langid.langid import LanguageIdentifier, MODEL_FILE
|
| 27 |
+
langid = LanguageIdentifier.from_pickled_model(MODEL_FILE, norm_probs=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# -----------------------------------
|
| 31 |
+
# 更新日志:新版本分词更加精准。
|
| 32 |
+
# Changelog: The new version of the word segmentation is more accurate.
|
| 33 |
+
# チェンジログ:新しいバージョンの単語セグメンテーションはより正確です。
|
| 34 |
+
# Changelog: 분할이라는 단어의 새로운 버전이 더 정확합니다.
|
| 35 |
+
# -----------------------------------
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Word segmentation function:
|
| 39 |
+
# automatically identify and split the words (Chinese/English/Japanese/Korean) in the article or sentence according to different languages,
|
| 40 |
+
# making it more suitable for TTS processing.
|
| 41 |
+
# This code is designed for front-end text multi-lingual mixed annotation distinction, multi-language mixed training and inference of various TTS projects.
|
| 42 |
+
# 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.
|
| 43 |
+
|
| 44 |
+
#===========================================================================================================
|
| 45 |
+
#分かち書き機能:文章や文章の中の例えば(中国語/英語/日本語/韓国語)を、異なる言語で自動的に認識して分割し、TTS処理により適したものにします。
|
| 46 |
+
#このコードは、さまざまなTTSプロジェクトのフロントエンドテキストの多言語混合注釈区別、多言語混合トレーニング、および推論のために特別に作成されています。
|
| 47 |
+
#===========================================================================================================
|
| 48 |
+
#(1)自動分詞:「韓国語では何を読むのですかあなたの体育の先生は誰ですか?今回の発表会では、iPhone 15シリーズの4機種が登場しました」
|
| 49 |
+
#(2)手动分词:“あなたの名前は<ja>佐々木ですか?<ja>ですか?”
|
| 50 |
+
#この処理結果は主に(中国語=ja、日本語=ja、英語=en、韓国語=ko)を対象としており、実際には最大97の異なる言語の混合処理をサポートできます。
|
| 51 |
+
#===========================================================================================================
|
| 52 |
+
|
| 53 |
+
#===========================================================================================================
|
| 54 |
+
# 단어 분할 기능: 기사 또는 문장에서 단어(중국어/영어/일본어/한국어)를 다른 언어에 따라 자동으로 식별하고 분할하여 TTS 처리에 더 적합합니다.
|
| 55 |
+
# 이 코드는 프런트 엔드 텍스트 다국어 혼합 주석 분화, 다국어 혼합 교육 및 다양한 TTS 프로젝트의 추론을 위해 설계되었습니다.
|
| 56 |
+
#===========================================================================================================
|
| 57 |
+
# (1) 자동 단어 분할: "한국어로 무엇을 읽습니까? 스포츠 씨? 이 컨퍼런스는 4개의 iPhone 15 시리즈 모델을 제공합니다."
|
| 58 |
+
# (2) 수동 참여: "이름이 <ja>Saki입니까? <ja>?"
|
| 59 |
+
# 이 처리 결과는 주로 (중국어 = zh, 일본어 = ja, 영어 = en, 한국어 = ko)를 위한 것이며 실제로 혼합 처리를 위해 최대 97개의 언어를 지원합니다.
|
| 60 |
+
#===========================================================================================================
|
| 61 |
+
|
| 62 |
+
# ===========================================================================================================
|
| 63 |
+
# 分词功能:将文章或句子里的例如(中/英/日/韩),按不同语言自动识别并拆分,让它更适合TTS处理。
|
| 64 |
+
# 本代码专为各种 TTS 项目的前端文本多语种混合标注区分,多语言混合训练和推理而编写。
|
| 65 |
+
# ===========================================================================================================
|
| 66 |
+
# (1)自动分词:“韩语中的오빠读什么呢?あなたの体育の先生は誰ですか? 此次发布会带来了四款iPhone 15系列机型”
|
| 67 |
+
# (2)手动分词:“你的名字叫<ja>佐々木?<ja>吗?”
|
| 68 |
+
# 本处理结果主要针对(中文=zh , 日文=ja , 英文=en , 韩语=ko), 实际上可支持多达 97 种不同的语言混合处理。
|
| 69 |
+
# ===========================================================================================================
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# 手动分词标签规范:<语言标签>文本内容</语言标签>
|
| 73 |
+
# 수동 단어 분할 태그 사양: <언어 태그> 텍스트 내용</언어 태그>
|
| 74 |
+
# Manual word segmentation tag specification: <language tags> text content </language tags>
|
| 75 |
+
# 手動分詞タグ仕様:<言語タグ>テキスト内容</言語タグ>
|
| 76 |
+
# ===========================================================================================================
|
| 77 |
+
# For manual word segmentation, labels need to appear in pairs, such as:
|
| 78 |
+
# 如需手动分词,标签需要成对出现,例如:“<ja>佐々木<ja>” 或者 “<ja>佐々木</ja>”
|
| 79 |
+
# 错误示范:“你的名字叫<ja>佐々木。” 此句子中出现的单个<ja>标签将被忽略,不会处理。
|
| 80 |
+
# Error demonstration: "Your name is <ja>佐々木。" Single <ja> tags that appear in this sentence will be ignored and will not be processed.
|
| 81 |
+
# ===========================================================================================================
|
| 82 |
+
|
| 83 |
+
class LangSegment():
|
| 84 |
+
|
| 85 |
+
_text_cache = None
|
| 86 |
+
_text_lasts = None
|
| 87 |
+
_text_langs = None
|
| 88 |
+
_lang_count = None
|
| 89 |
+
_lang_eos = None
|
| 90 |
+
|
| 91 |
+
# 可自定义语言匹配标签:カスタマイズ可能な言語対応タグ:사용자 지정 가능한 언어 일치 태그:
|
| 92 |
+
# Customizable language matching tags: These are supported,이 표현들은 모두 지지합니다
|
| 93 |
+
# <zh>你好<zh> , <ja>佐々木</ja> , <en>OK<en> , <ko>오빠</ko> 这些写法均支持
|
| 94 |
+
SYMBOLS_PATTERN = r'(<([a-zA-Z|-]*)>(.*?)<\/*[a-zA-Z|-]*>)'
|
| 95 |
+
|
| 96 |
+
# 语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
|
| 97 |
+
# 언어 필터 그룹 기능을 사용하면 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
|
| 98 |
+
# 言語フィルターグループ機能では、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
|
| 99 |
+
# The language filter group function allows you to specify reserved languages.
|
| 100 |
+
# Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.
|
| 101 |
+
# 排名越前,优先级越高,The higher the ranking, the higher the priority,ランキングが上位になるほど、優先度が高くなります。
|
| 102 |
+
|
| 103 |
+
# 系统默认过滤器。System default filter。(ISO 639-1 codes given)
|
| 104 |
+
# ----------------------------------------------------------------------------------------------------------------------------------
|
| 105 |
+
# "zh"中文=Chinese ,"en"英语=English ,"ja"日语=Japanese ,"ko"韩语=Korean ,"fr"法语=French ,"vi"越南语=Vietnamese , "ru"俄语=Russian
|
| 106 |
+
# "th"泰语=Thai
|
| 107 |
+
# ----------------------------------------------------------------------------------------------------------------------------------
|
| 108 |
+
DEFAULT_FILTERS = ["zh", "ja", "ko", "en"]
|
| 109 |
+
|
| 110 |
+
# 用户可自定义过滤器。User-defined filters
|
| 111 |
+
Langfilters = DEFAULT_FILTERS[:] # 创建副本
|
| 112 |
+
|
| 113 |
+
# 试验性支持:您可自定义添加:"fr"法语 , "vi"越南语。Experimental: You can customize to add: "fr" French, "vi" Vietnamese.
|
| 114 |
+
# 请使用API启用:LangSegment.setfilters(["zh", "en", "ja", "ko", "fr", "vi" , "ru" , "th"]) # 您可自定义添加,如:"fr"法语 , "vi"越南语。
|
| 115 |
+
|
| 116 |
+
# 预览版功能,自动启用或禁用,无需设置
|
| 117 |
+
# Preview feature, automatically enabled or disabled, no settings required
|
| 118 |
+
EnablePreview = False
|
| 119 |
+
|
| 120 |
+
# 除此以外,它支持简写过滤器,只需按不同语种任意组合即可。
|
| 121 |
+
# In addition to that, it supports abbreviation filters, allowing for any combination of different languages.
|
| 122 |
+
# 示例:您可以任意指定多种组合,进行过滤
|
| 123 |
+
# Example: You can specify any combination to filter
|
| 124 |
+
|
| 125 |
+
# 中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
|
| 126 |
+
# 중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
|
| 127 |
+
# 中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
|
| 128 |
+
# Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
|
| 129 |
+
# Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
|
| 130 |
+
LangPriorityThreshold = 0.89
|
| 131 |
+
|
| 132 |
+
# Langfilters = ["zh"] # 按中文识别
|
| 133 |
+
# Langfilters = ["en"] # 按英文识别
|
| 134 |
+
# Langfilters = ["ja"] # 按日文识别
|
| 135 |
+
# Langfilters = ["ko"] # 按韩文识别
|
| 136 |
+
# Langfilters = ["zh_ja"] # 中日混合识别
|
| 137 |
+
# Langfilters = ["zh_en"] # 中英混合识别
|
| 138 |
+
# Langfilters = ["ja_en"] # 日英混合识别
|
| 139 |
+
# Langfilters = ["zh_ko"] # 中韩混合识别
|
| 140 |
+
# Langfilters = ["ja_ko"] # 日韩混合识别
|
| 141 |
+
# Langfilters = ["en_ko"] # 英韩混合识别
|
| 142 |
+
# Langfilters = ["zh_ja_en"] # 中日英混合识别
|
| 143 |
+
# Langfilters = ["zh_ja_en_ko"] # 中日英韩混合识别
|
| 144 |
+
|
| 145 |
+
# 更多过滤组合,请您随意。。。For more filter combinations, please feel free to......
|
| 146 |
+
# より多くのフィルターの組み合わせ、お気軽に。。。더 많은 필터 조합을 원하시면 자유롭게 해주세요. .....
|
| 147 |
+
|
| 148 |
+
# 可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。
|
| 149 |
+
# 开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
|
| 150 |
+
keepPinyin = False
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# DEFINITION
|
| 154 |
+
PARSE_TAG = re.compile(r'(⑥\$*\d+[\d]{6,}⑥)')
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def _clears():
|
| 158 |
+
LangSegment._text_cache = None
|
| 159 |
+
LangSegment._text_lasts = None
|
| 160 |
+
LangSegment._text_langs = None
|
| 161 |
+
LangSegment._text_waits = None
|
| 162 |
+
LangSegment._lang_count = None
|
| 163 |
+
LangSegment._lang_eos = None
|
| 164 |
+
pass
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def _is_english_word(word):
|
| 168 |
+
return bool(re.match(r'^[a-zA-Z]+$', word))
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def _is_chinese(word):
|
| 172 |
+
for char in word:
|
| 173 |
+
if '\u4e00' <= char <= '\u9fff':
|
| 174 |
+
return True
|
| 175 |
+
return False
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def _is_japanese_kana(word):
|
| 179 |
+
pattern = re.compile(r'[\u3040-\u309F\u30A0-\u30FF]+')
|
| 180 |
+
matches = pattern.findall(word)
|
| 181 |
+
return len(matches) > 0
|
| 182 |
+
|
| 183 |
+
@staticmethod
|
| 184 |
+
def _insert_english_uppercase(word):
|
| 185 |
+
modified_text = re.sub(r'(?<!\b)([A-Z])', r' \1', word)
|
| 186 |
+
modified_text = modified_text.strip('-')
|
| 187 |
+
return modified_text + " "
|
| 188 |
+
|
| 189 |
+
@staticmethod
|
| 190 |
+
def _statistics(language, text):
|
| 191 |
+
# Language word statistics:
|
| 192 |
+
# Chinese characters usually occupy double bytes
|
| 193 |
+
if LangSegment._lang_count is None or not isinstance(LangSegment._lang_count, defaultdict):
|
| 194 |
+
LangSegment._lang_count = defaultdict(int)
|
| 195 |
+
lang_count = LangSegment._lang_count
|
| 196 |
+
if not "|" in language:
|
| 197 |
+
lang_count[language] += int(len(text)*2) if language == "zh" else len(text)
|
| 198 |
+
LangSegment._lang_count = lang_count
|
| 199 |
+
pass
|
| 200 |
+
|
| 201 |
+
@staticmethod
|
| 202 |
+
def _clear_text_number(text):
|
| 203 |
+
clear_text = re.sub(r'([^\w\s]+)','',re.sub(r'\n+','',text)).strip()
|
| 204 |
+
is_number = len(re.sub(re.compile(r'(\d+)'),'',clear_text)) == 0
|
| 205 |
+
return clear_text,is_number
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def _saveData(words,language:str,text:str,score:float):
|
| 209 |
+
# Pre-detection
|
| 210 |
+
clear_text , is_number = LangSegment._clear_text_number(text)
|
| 211 |
+
# Merge the same language and save the results
|
| 212 |
+
preData = words[-1] if len(words) > 0 else None
|
| 213 |
+
if preData is not None:
|
| 214 |
+
if len(clear_text) == 0:language = preData["lang"]
|
| 215 |
+
elif is_number == True:language = preData["lang"]
|
| 216 |
+
_ , pre_is_number = LangSegment._clear_text_number(preData["text"])
|
| 217 |
+
if (preData["lang"] == language):
|
| 218 |
+
LangSegment._statistics(preData["lang"],text)
|
| 219 |
+
text = preData["text"] + text
|
| 220 |
+
preData["text"] = text
|
| 221 |
+
return preData
|
| 222 |
+
elif pre_is_number == True:
|
| 223 |
+
text = f'{preData["text"]}{text}'
|
| 224 |
+
words.pop()
|
| 225 |
+
elif is_number == True:
|
| 226 |
+
priority_language = LangSegment._get_filters_string()[:2]
|
| 227 |
+
if priority_language in "ja-zh-en-ko-fr-vi":language = priority_language
|
| 228 |
+
data = {"lang":language,"text": text,"score":score}
|
| 229 |
+
filters = LangSegment.Langfilters
|
| 230 |
+
if filters is None or len(filters) == 0 or "?" in language or \
|
| 231 |
+
language in filters or language in filters[0] or \
|
| 232 |
+
filters[0] == "*" or filters[0] in "alls-mixs-autos":
|
| 233 |
+
words.append(data)
|
| 234 |
+
LangSegment._statistics(data["lang"],data["text"])
|
| 235 |
+
return data
|
| 236 |
+
|
| 237 |
+
@staticmethod
|
| 238 |
+
def _addwords(words,language,text,score):
|
| 239 |
+
if text is None or len(text.strip()) == 0:return True
|
| 240 |
+
if language is None:language = ""
|
| 241 |
+
language = language.lower()
|
| 242 |
+
if language == 'en':text = LangSegment._insert_english_uppercase(text)
|
| 243 |
+
# text = re.sub(r'[(())]', ',' , text) # Keep it.
|
| 244 |
+
text_waits = LangSegment._text_waits
|
| 245 |
+
ispre_waits = len(text_waits)>0
|
| 246 |
+
preResult = text_waits.pop() if ispre_waits else None
|
| 247 |
+
if preResult is None:preResult = words[-1] if len(words) > 0 else None
|
| 248 |
+
if preResult and ("|" in preResult["lang"]):
|
| 249 |
+
pre_lang = preResult["lang"]
|
| 250 |
+
if language in pre_lang:preResult["lang"] = language = language.split("|")[0]
|
| 251 |
+
else:preResult["lang"]=pre_lang.split("|")[0]
|
| 252 |
+
if ispre_waits:preResult = LangSegment._saveData(words,preResult["lang"],preResult["text"],preResult["score"])
|
| 253 |
+
pre_lang = preResult["lang"] if preResult else None
|
| 254 |
+
if ("|" in language) and (pre_lang and not pre_lang in language and not "…" in language):language = language.split("|")[0]
|
| 255 |
+
if "|" in language:LangSegment._text_waits.append({"lang":language,"text": text,"score":score})
|
| 256 |
+
else:LangSegment._saveData(words,language,text,score)
|
| 257 |
+
return False
|
| 258 |
+
|
| 259 |
+
@staticmethod
|
| 260 |
+
def _get_prev_data(words):
|
| 261 |
+
data = words[-1] if words and len(words) > 0 else None
|
| 262 |
+
if data:return (data["lang"] , data["text"])
|
| 263 |
+
return (None,"")
|
| 264 |
+
|
| 265 |
+
@staticmethod
|
| 266 |
+
def _match_ending(input , index):
|
| 267 |
+
if input is None or len(input) == 0:return False,None
|
| 268 |
+
input = re.sub(r'\s+', '', input)
|
| 269 |
+
if len(input) == 0 or abs(index) > len(input):return False,None
|
| 270 |
+
ending_pattern = re.compile(r'([「」“”‘’"\'::。.!!?.?])')
|
| 271 |
+
return ending_pattern.match(input[index]),input[index]
|
| 272 |
+
|
| 273 |
+
@staticmethod
|
| 274 |
+
def _cleans_text(cleans_text):
|
| 275 |
+
cleans_text = re.sub(r'(.*?)([^\w]+)', r'\1 ', cleans_text)
|
| 276 |
+
cleans_text = re.sub(r'(.)\1+', r'\1', cleans_text)
|
| 277 |
+
return cleans_text.strip()
|
| 278 |
+
|
| 279 |
+
@staticmethod
|
| 280 |
+
def _lang_classify(cleans_text):
|
| 281 |
+
language, score = langid.classify(cleans_text)
|
| 282 |
+
return language, score
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def _get_filters_string():
|
| 286 |
+
filters = LangSegment.Langfilters
|
| 287 |
+
return "-".join(filters).lower().strip() if filters is not None else ""
|
| 288 |
+
|
| 289 |
+
@staticmethod
|
| 290 |
+
def _parse_language(words , segment):
|
| 291 |
+
LANG_JA = "ja"
|
| 292 |
+
LANG_ZH = "zh"
|
| 293 |
+
LANG_ZH_JA = f'{LANG_ZH}|{LANG_JA}'
|
| 294 |
+
LANG_JA_ZH = f'{LANG_JA}|{LANG_ZH}'
|
| 295 |
+
language = LANG_ZH
|
| 296 |
+
regex_pattern = re.compile(r'([^\w\s]+)')
|
| 297 |
+
lines = regex_pattern.split(segment)
|
| 298 |
+
lines_max = len(lines)
|
| 299 |
+
LANG_EOS =LangSegment._lang_eos
|
| 300 |
+
for index, text in enumerate(lines):
|
| 301 |
+
if len(text) == 0:continue
|
| 302 |
+
EOS = index >= (lines_max - 1)
|
| 303 |
+
nextId = index + 1
|
| 304 |
+
nextText = lines[nextId] if not EOS else ""
|
| 305 |
+
nextPunc = len(re.sub(regex_pattern,'',re.sub(r'\n+','',nextText)).strip()) == 0
|
| 306 |
+
textPunc = len(re.sub(regex_pattern,'',re.sub(r'\n+','',text)).strip()) == 0
|
| 307 |
+
if not EOS and (textPunc == True or ( len(nextText.strip()) >= 0 and nextPunc == True)):
|
| 308 |
+
lines[nextId] = f'{text}{nextText}'
|
| 309 |
+
continue
|
| 310 |
+
number_tags = re.compile(r'(⑥\d{6,}⑥)')
|
| 311 |
+
cleans_text = re.sub(number_tags, '' ,text)
|
| 312 |
+
cleans_text = re.sub(r'\d+', '' ,cleans_text)
|
| 313 |
+
cleans_text = LangSegment._cleans_text(cleans_text)
|
| 314 |
+
# fix:Langid's recognition of short sentences is inaccurate, and it is spliced longer.
|
| 315 |
+
if not EOS and len(cleans_text) <= 2:
|
| 316 |
+
lines[nextId] = f'{text}{nextText}'
|
| 317 |
+
continue
|
| 318 |
+
language,score = LangSegment._lang_classify(cleans_text)
|
| 319 |
+
prev_language , prev_text = LangSegment._get_prev_data(words)
|
| 320 |
+
if language != LANG_ZH and all('\u4e00' <= c <= '\u9fff' for c in re.sub(r'\s','',cleans_text)):language,score = LANG_ZH,1
|
| 321 |
+
if len(cleans_text) <= 5 and LangSegment._is_chinese(cleans_text):
|
| 322 |
+
filters_string = LangSegment._get_filters_string()
|
| 323 |
+
if score < LangSegment.LangPriorityThreshold and len(filters_string) > 0:
|
| 324 |
+
index_ja , index_zh = filters_string.find(LANG_JA) , filters_string.find(LANG_ZH)
|
| 325 |
+
if index_ja != -1 and index_ja < index_zh:language = LANG_JA
|
| 326 |
+
elif index_zh != -1 and index_zh < index_ja:language = LANG_ZH
|
| 327 |
+
if LangSegment._is_japanese_kana(cleans_text):language = LANG_JA
|
| 328 |
+
elif len(cleans_text) > 2 and score > 0.90:pass
|
| 329 |
+
elif EOS and LANG_EOS:language = LANG_ZH if len(cleans_text) <= 1 else language
|
| 330 |
+
else:
|
| 331 |
+
LANG_UNKNOWN = LANG_ZH_JA if language == LANG_ZH or (len(cleans_text) <=2 and prev_language == LANG_ZH) else LANG_JA_ZH
|
| 332 |
+
match_end,match_char = LangSegment._match_ending(text, -1)
|
| 333 |
+
referen = prev_language in LANG_UNKNOWN or LANG_UNKNOWN in prev_language if prev_language else False
|
| 334 |
+
if match_char in "。.": language = prev_language if referen and len(words) > 0 else language
|
| 335 |
+
else:language = f"{LANG_UNKNOWN}|…"
|
| 336 |
+
text,*_ = re.subn(number_tags , LangSegment._restore_number , text )
|
| 337 |
+
LangSegment._addwords(words,language,text,score)
|
| 338 |
+
pass
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
@staticmethod
|
| 342 |
+
def _restore_number(matche):
|
| 343 |
+
value = matche.group(0)
|
| 344 |
+
text_cache = LangSegment._text_cache
|
| 345 |
+
if value in text_cache:
|
| 346 |
+
process , data = text_cache[value]
|
| 347 |
+
tag , match = data
|
| 348 |
+
value = match
|
| 349 |
+
return value
|
| 350 |
+
|
| 351 |
+
@staticmethod
|
| 352 |
+
def _pattern_symbols(item , text):
|
| 353 |
+
if text is None:return text
|
| 354 |
+
tag , pattern , process = item
|
| 355 |
+
matches = pattern.findall(text)
|
| 356 |
+
if len(matches) == 1 and "".join(matches[0]) == text:
|
| 357 |
+
return text
|
| 358 |
+
for i , match in enumerate(matches):
|
| 359 |
+
key = f"⑥{tag}{i:06d}⑥"
|
| 360 |
+
text = re.sub(pattern , key , text , count=1)
|
| 361 |
+
LangSegment._text_cache[key] = (process , (tag , match))
|
| 362 |
+
return text
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def _process_symbol(words,data):
|
| 366 |
+
tag , match = data
|
| 367 |
+
language = match[1]
|
| 368 |
+
text = match[2]
|
| 369 |
+
score = 1.0
|
| 370 |
+
LangSegment._addwords(words,language,text,score)
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
@staticmethod
|
| 374 |
+
def _process_english(words,data):
|
| 375 |
+
tag , match = data
|
| 376 |
+
text = match[0]
|
| 377 |
+
filters = LangSegment._get_filters_string()
|
| 378 |
+
priority_language = filters[:2]
|
| 379 |
+
# Preview feature, other language segmentation processing
|
| 380 |
+
enablePreview = LangSegment.EnablePreview
|
| 381 |
+
if enablePreview == True:
|
| 382 |
+
# Experimental: Other language support
|
| 383 |
+
regex_pattern = re.compile(r'(.*?[。.??!!]+[\n]{,1})')
|
| 384 |
+
lines = regex_pattern.split(text)
|
| 385 |
+
for index , text in enumerate(lines):
|
| 386 |
+
if len(text.strip()) == 0:continue
|
| 387 |
+
cleans_text = LangSegment._cleans_text(text)
|
| 388 |
+
language,score = LangSegment._lang_classify(cleans_text)
|
| 389 |
+
if language in filters:pass
|
| 390 |
+
elif score >= 0.95:continue # High score, but not in the filter, excluded.
|
| 391 |
+
elif score <= 0.15 and filters[:2] == "fr":language = priority_language
|
| 392 |
+
else:language = "en"
|
| 393 |
+
LangSegment._addwords(words,language,text,score)
|
| 394 |
+
else:
|
| 395 |
+
# Default is English
|
| 396 |
+
language, score = "en", 1.0
|
| 397 |
+
LangSegment._addwords(words,language,text,score)
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
@staticmethod
|
| 401 |
+
def _process_Russian(words,data):
|
| 402 |
+
tag , match = data
|
| 403 |
+
text = match[0]
|
| 404 |
+
language = "ru"
|
| 405 |
+
score = 1.0
|
| 406 |
+
LangSegment._addwords(words,language,text,score)
|
| 407 |
+
pass
|
| 408 |
+
|
| 409 |
+
@staticmethod
|
| 410 |
+
def _process_Thai(words,data):
|
| 411 |
+
tag , match = data
|
| 412 |
+
text = match[0]
|
| 413 |
+
language = "th"
|
| 414 |
+
score = 1.0
|
| 415 |
+
LangSegment._addwords(words,language,text,score)
|
| 416 |
+
pass
|
| 417 |
+
|
| 418 |
+
@staticmethod
|
| 419 |
+
def _process_korean(words,data):
|
| 420 |
+
tag , match = data
|
| 421 |
+
text = match[0]
|
| 422 |
+
language = "ko"
|
| 423 |
+
score = 1.0
|
| 424 |
+
LangSegment._addwords(words,language,text,score)
|
| 425 |
+
pass
|
| 426 |
+
|
| 427 |
+
@staticmethod
|
| 428 |
+
def _process_quotes(words,data):
|
| 429 |
+
tag , match = data
|
| 430 |
+
text = "".join(match)
|
| 431 |
+
childs = LangSegment.PARSE_TAG.findall(text)
|
| 432 |
+
if len(childs) > 0:
|
| 433 |
+
LangSegment._process_tags(words , text , False)
|
| 434 |
+
else:
|
| 435 |
+
cleans_text = LangSegment._cleans_text(match[1])
|
| 436 |
+
if len(cleans_text) <= 5:
|
| 437 |
+
LangSegment._parse_language(words,text)
|
| 438 |
+
else:
|
| 439 |
+
language,score = LangSegment._lang_classify(cleans_text)
|
| 440 |
+
LangSegment._addwords(words,language,text,score)
|
| 441 |
+
pass
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
@staticmethod
|
| 445 |
+
def _process_pinyin(words,data):
|
| 446 |
+
tag , match = data
|
| 447 |
+
text = match
|
| 448 |
+
language = "zh"
|
| 449 |
+
score = 1.0
|
| 450 |
+
LangSegment._addwords(words,language,text,score)
|
| 451 |
+
pass
|
| 452 |
+
|
| 453 |
+
@staticmethod
|
| 454 |
+
def _process_number(words,data): # "$0" process only
|
| 455 |
+
"""
|
| 456 |
+
Numbers alone cannot accurately identify language.
|
| 457 |
+
Because numbers are universal in all languages.
|
| 458 |
+
So it won't be executed here, just for testing.
|
| 459 |
+
"""
|
| 460 |
+
tag , match = data
|
| 461 |
+
language = words[0]["lang"] if len(words) > 0 else "zh"
|
| 462 |
+
text = match
|
| 463 |
+
score = 0.0
|
| 464 |
+
LangSegment._addwords(words,language,text,score)
|
| 465 |
+
pass
|
| 466 |
+
|
| 467 |
+
@staticmethod
|
| 468 |
+
def _process_tags(words , text , root_tag):
|
| 469 |
+
text_cache = LangSegment._text_cache
|
| 470 |
+
segments = re.split(LangSegment.PARSE_TAG, text)
|
| 471 |
+
segments_len = len(segments) - 1
|
| 472 |
+
for index , text in enumerate(segments):
|
| 473 |
+
if root_tag:LangSegment._lang_eos = index >= segments_len
|
| 474 |
+
if LangSegment.PARSE_TAG.match(text):
|
| 475 |
+
process , data = text_cache[text]
|
| 476 |
+
if process:process(words , data)
|
| 477 |
+
else:
|
| 478 |
+
LangSegment._parse_language(words , text)
|
| 479 |
+
pass
|
| 480 |
+
return words
|
| 481 |
+
|
| 482 |
+
@staticmethod
|
| 483 |
+
def _parse_symbols(text):
|
| 484 |
+
TAG_NUM = "00" # "00" => default channels , "$0" => testing channel
|
| 485 |
+
TAG_S1,TAG_S2,TAG_P1,TAG_P2,TAG_EN,TAG_KO,TAG_RU,TAG_TH = "$1" ,"$2" ,"$3" ,"$4" ,"$5" ,"$6" ,"$7","$8"
|
| 486 |
+
TAG_BASE = re.compile(fr'(([【《((“‘"\']*[LANGUAGE]+[\W\s]*)+)')
|
| 487 |
+
# Get custom language filter
|
| 488 |
+
filters = LangSegment.Langfilters
|
| 489 |
+
filters = filters if filters is not None else ""
|
| 490 |
+
# =======================================================================================================
|
| 491 |
+
# Experimental: Other language support.Thử nghiệm: Hỗ trợ ngôn ngữ khác.Expérimental : prise en charge d’autres langues.
|
| 492 |
+
# 相关语言字符如有缺失,熟悉相关语言的朋友,可以提交把缺失的发音符号补全。
|
| 493 |
+
# If relevant language characters are missing, friends who are familiar with the relevant languages can submit a submission to complete the missing pronunciation symbols.
|
| 494 |
+
# 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.
|
| 495 |
+
# 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.
|
| 496 |
+
# -------------------------------------------------------------------------------------------------------
|
| 497 |
+
# Preview feature, other language support
|
| 498 |
+
enablePreview = LangSegment.EnablePreview
|
| 499 |
+
if "fr" in filters or \
|
| 500 |
+
"vi" in filters:enablePreview = True
|
| 501 |
+
LangSegment.EnablePreview = enablePreview
|
| 502 |
+
# 实验性:法语字符支持。Prise en charge des caractères français
|
| 503 |
+
RE_FR = "" if not enablePreview else "àáâãäåæçèéêëìíîïðñòóôõöùúûüýþÿ"
|
| 504 |
+
# 实验性:越南语字符支持。Hỗ trợ ký tự tiếng Việt
|
| 505 |
+
RE_VI = "" if not enablePreview else "đơưăáàảãạắằẳẵặấầẩẫậéèẻẽẹếềểễệíìỉĩịóòỏõọốồổỗộớờởỡợúùủũụứừửữựôâêơưỷỹ"
|
| 506 |
+
# -------------------------------------------------------------------------------------------------------
|
| 507 |
+
# Basic options:
|
| 508 |
+
process_list = [
|
| 509 |
+
( TAG_S1 , re.compile(LangSegment.SYMBOLS_PATTERN) , LangSegment._process_symbol ), # Symbol Tag
|
| 510 |
+
( TAG_KO , re.compile(re.sub(r'LANGUAGE',f'\uac00-\ud7a3',TAG_BASE.pattern)) , LangSegment._process_korean ), # Korean words
|
| 511 |
+
( TAG_TH , re.compile(re.sub(r'LANGUAGE',f'\u0E00-\u0E7F',TAG_BASE.pattern)) , LangSegment._process_Thai ), # Thai words support.
|
| 512 |
+
( TAG_RU , re.compile(re.sub(r'LANGUAGE',f'А-Яа-яЁё',TAG_BASE.pattern)) , LangSegment._process_Russian ), # Russian words support.
|
| 513 |
+
( TAG_NUM , re.compile(r'(\W*\d+\W+\d*\W*\d*)') , LangSegment._process_number ), # Number words, Universal in all languages, Ignore it.
|
| 514 |
+
( 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.
|
| 515 |
+
( TAG_P1 , re.compile(r'(["\'])(.*?)(\1)') , LangSegment._process_quotes ), # Regular quotes
|
| 516 |
+
( TAG_P2 , re.compile(r'([\n]*[【《((“‘])([^【《((“‘’”))》】]{3,})([’”))》】][\W\s]*[\n]{,1})') , LangSegment._process_quotes ), # Special quotes, There are left and right.
|
| 517 |
+
]
|
| 518 |
+
# Extended options: Default False
|
| 519 |
+
if LangSegment.keepPinyin == True:process_list.insert(1 ,
|
| 520 |
+
( TAG_S2 , re.compile(r'([\(({](?:\s*\w*\d\w*\s*)+[})\)])') , LangSegment._process_pinyin ), # Chinese Pinyin Tag.
|
| 521 |
+
)
|
| 522 |
+
# -------------------------------------------------------------------------------------------------------
|
| 523 |
+
words = []
|
| 524 |
+
lines = re.findall(r'.*\n*', re.sub(LangSegment.PARSE_TAG, '' ,text))
|
| 525 |
+
for index , text in enumerate(lines):
|
| 526 |
+
if len(text.strip()) == 0:continue
|
| 527 |
+
LangSegment._lang_eos = False
|
| 528 |
+
LangSegment._text_cache = {}
|
| 529 |
+
for item in process_list:
|
| 530 |
+
text = LangSegment._pattern_symbols(item , text)
|
| 531 |
+
cur_word = LangSegment._process_tags([] , text , True)
|
| 532 |
+
if len(cur_word) == 0:continue
|
| 533 |
+
cur_data = cur_word[0] if len(cur_word) > 0 else None
|
| 534 |
+
pre_data = words[-1] if len(words) > 0 else None
|
| 535 |
+
if cur_data and pre_data and cur_data["lang"] == pre_data["lang"]:
|
| 536 |
+
cur_data["text"] = f'{pre_data["text"]}{cur_data["text"]}'
|
| 537 |
+
words.pop()
|
| 538 |
+
words += cur_word
|
| 539 |
+
lang_count = LangSegment._lang_count
|
| 540 |
+
if lang_count and len(lang_count) > 0:
|
| 541 |
+
lang_count = dict(sorted(lang_count.items(), key=lambda x: x[1], reverse=True))
|
| 542 |
+
lang_count = list(lang_count.items())
|
| 543 |
+
LangSegment._lang_count = lang_count
|
| 544 |
+
return words
|
| 545 |
+
|
| 546 |
+
@staticmethod
|
| 547 |
+
def setfilters(filters):
|
| 548 |
+
# 当过滤器更改时,清除缓存
|
| 549 |
+
# 필터가 변경되면 캐시를 지웁니다.
|
| 550 |
+
# フィルタが変更されると、キャッシュがクリアされます
|
| 551 |
+
# When the filter changes, clear the cache
|
| 552 |
+
if LangSegment.Langfilters != filters:
|
| 553 |
+
LangSegment._clears()
|
| 554 |
+
LangSegment.Langfilters = filters
|
| 555 |
+
pass
|
| 556 |
+
|
| 557 |
+
@staticmethod
|
| 558 |
+
def getfilters():
|
| 559 |
+
return LangSegment.Langfilters
|
| 560 |
+
|
| 561 |
+
@staticmethod
|
| 562 |
+
def setPriorityThreshold(threshold:float):
|
| 563 |
+
LangSegment.LangPriorityThreshold = threshold
|
| 564 |
+
pass
|
| 565 |
+
|
| 566 |
+
@staticmethod
|
| 567 |
+
def getPriorityThreshold():
|
| 568 |
+
return LangSegment.LangPriorityThreshold
|
| 569 |
+
|
| 570 |
+
@staticmethod
|
| 571 |
+
def getCounts():
|
| 572 |
+
lang_count = LangSegment._lang_count
|
| 573 |
+
if lang_count is not None:return lang_count
|
| 574 |
+
text_langs = LangSegment._text_langs
|
| 575 |
+
if text_langs is None or len(text_langs) == 0:return [("zh",0)]
|
| 576 |
+
lang_counts = defaultdict(int)
|
| 577 |
+
for d in text_langs:lang_counts[d['lang']] += int(len(d['text'])*2) if d['lang'] == "zh" else len(d['text'])
|
| 578 |
+
lang_counts = dict(sorted(lang_counts.items(), key=lambda x: x[1], reverse=True))
|
| 579 |
+
lang_counts = list(lang_counts.items())
|
| 580 |
+
LangSegment._lang_count = lang_counts
|
| 581 |
+
return lang_counts
|
| 582 |
+
|
| 583 |
+
@staticmethod
|
| 584 |
+
def getTexts(text:str):
|
| 585 |
+
if text is None or len(text.strip()) == 0:
|
| 586 |
+
LangSegment._clears()
|
| 587 |
+
return []
|
| 588 |
+
# lasts
|
| 589 |
+
text_langs = LangSegment._text_langs
|
| 590 |
+
if LangSegment._text_lasts == text and text_langs is not None:return text_langs
|
| 591 |
+
# parse
|
| 592 |
+
LangSegment._text_waits = []
|
| 593 |
+
LangSegment._lang_count = None
|
| 594 |
+
LangSegment._text_lasts = text
|
| 595 |
+
text = LangSegment._parse_symbols(text)
|
| 596 |
+
LangSegment._text_langs = text
|
| 597 |
+
return text
|
| 598 |
+
|
| 599 |
+
@staticmethod
|
| 600 |
+
def classify(text:str):
|
| 601 |
+
return LangSegment.getTexts(text)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def setfilters(filters):
|
| 605 |
+
"""
|
| 606 |
+
功能:语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
|
| 607 |
+
기능: 언어 필터 그룹 기능, 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
|
| 608 |
+
機能:言語フィルターグループ機能で、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
|
| 609 |
+
Function: Language filter group function, you can specify reserved languages. \n
|
| 610 |
+
Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.\n
|
| 611 |
+
Args:
|
| 612 |
+
filters (list): ["zh", "en", "ja", "ko"] 排名越前,优先级越高
|
| 613 |
+
"""
|
| 614 |
+
LangSegment.setfilters(filters)
|
| 615 |
+
pass
|
| 616 |
+
|
| 617 |
+
def getfilters():
|
| 618 |
+
"""
|
| 619 |
+
功能:语言过滤组功能, 可以指定保留语言。不在过滤组中的语言将被清除。您可随心搭配TTS语音合成所支持的语言。
|
| 620 |
+
기능: 언어 필터 그룹 기능, 예약된 언어를 지정할 수 있습니다. 필터 그룹에 없는 언어는 지워집니다. TTS 텍스트에서 지원하는 언어를 원하는 대로 일치시킬 수 있습니다.
|
| 621 |
+
機能:言語フィルターグループ機能で、予約言語を指定できます。フィルターグループに含まれていない言語はクリアされます。TTS音声合成がサポートする言語を自由に組み合わせることができます。
|
| 622 |
+
Function: Language filter group function, you can specify reserved languages. \n
|
| 623 |
+
Languages not in the filter group will be cleared. You can match the languages supported by TTS Text To Speech as you like.\n
|
| 624 |
+
Args:
|
| 625 |
+
filters (list): ["zh", "en", "ja", "ko"] 排名越前,优先级越高
|
| 626 |
+
"""
|
| 627 |
+
return LangSegment.getfilters()
|
| 628 |
+
|
| 629 |
+
# # @Deprecated:Use shorter setfilters
|
| 630 |
+
# def setLangfilters(filters):
|
| 631 |
+
# """
|
| 632 |
+
# >0.1.9废除:使用更简短的setfilters
|
| 633 |
+
# """
|
| 634 |
+
# setfilters(filters)
|
| 635 |
+
# # @Deprecated:Use shorter getfilters
|
| 636 |
+
# def getLangfilters():
|
| 637 |
+
# """
|
| 638 |
+
# >0.1.9废除:使用更简短的getfilters
|
| 639 |
+
# """
|
| 640 |
+
# return getfilters()
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def setKeepPinyin(value:bool):
|
| 644 |
+
"""
|
| 645 |
+
可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。\n
|
| 646 |
+
开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
|
| 647 |
+
"""
|
| 648 |
+
LangSegment.keepPinyin = value
|
| 649 |
+
pass
|
| 650 |
+
|
| 651 |
+
def getKeepPinyin():
|
| 652 |
+
"""
|
| 653 |
+
可选保留:支持中文数字拼音格式,更方便前端实现拼音音素修改和推理,默认关闭 False 。\n
|
| 654 |
+
开启后 True ,括号内的数字拼音格式均保留,并识别输出为:"zh"中文。
|
| 655 |
+
"""
|
| 656 |
+
return LangSegment.keepPinyin
|
| 657 |
+
|
| 658 |
+
def setEnablePreview(value:bool):
|
| 659 |
+
"""
|
| 660 |
+
启用预览版功能(默认关闭)
|
| 661 |
+
Enable preview functionality (off by default)
|
| 662 |
+
Args:
|
| 663 |
+
value (bool): True=开启, False=关闭
|
| 664 |
+
"""
|
| 665 |
+
LangSegment.EnablePreview = (value == True)
|
| 666 |
+
pass
|
| 667 |
+
|
| 668 |
+
def getEnablePreview():
|
| 669 |
+
"""
|
| 670 |
+
启用预览版功能(默认关闭)
|
| 671 |
+
Enable preview functionality (off by default)
|
| 672 |
+
Args:
|
| 673 |
+
value (bool): True=开启, False=关闭
|
| 674 |
+
"""
|
| 675 |
+
return LangSegment.EnablePreview == True
|
| 676 |
+
|
| 677 |
+
def setPriorityThreshold(threshold:float):
|
| 678 |
+
"""
|
| 679 |
+
中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
|
| 680 |
+
中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
|
| 681 |
+
중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
|
| 682 |
+
Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
|
| 683 |
+
Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
|
| 684 |
+
Args:
|
| 685 |
+
threshold:float (score range is 0 ~ 1)
|
| 686 |
+
"""
|
| 687 |
+
LangSegment.setPriorityThreshold(threshold)
|
| 688 |
+
pass
|
| 689 |
+
|
| 690 |
+
def getPriorityThreshold():
|
| 691 |
+
"""
|
| 692 |
+
中/日语言优先级阀值(评分范围为 0 ~ 1):评分低于设定阀值 <0.89 时,启用 filters 中的优先级。\n
|
| 693 |
+
中国語/日本語の優先度しきい値(スコア範囲0〜1):スコアが設定されたしきい値<0.89未満の場合、フィルターの優先度が有効になります。\n
|
| 694 |
+
중/일본어 우선 순위 임계값(점수 범위 0-1): 점수가 설정된 임계값 <0.89보다 낮을 때 필터에서 우선 순위를 활성화합니다.
|
| 695 |
+
Chinese and Japanese language priority threshold (score range is 0 ~ 1): The default threshold is 0.89. \n
|
| 696 |
+
Only the common characters between Chinese and Japanese are processed with confidence and priority. \n
|
| 697 |
+
Args:
|
| 698 |
+
threshold:float (score range is 0 ~ 1)
|
| 699 |
+
"""
|
| 700 |
+
return LangSegment.getPriorityThreshold()
|
| 701 |
+
|
| 702 |
+
def getTexts(text:str):
|
| 703 |
+
"""
|
| 704 |
+
功能:对输入的文本进行多语种分词\n
|
| 705 |
+
기능: 입력 텍스트의 다국어 분할 \n
|
| 706 |
+
機能:入力されたテキストの多言語セグメンテーション\n
|
| 707 |
+
Feature: Tokenizing multilingual text input.\n
|
| 708 |
+
参数-Args:
|
| 709 |
+
text (str): Text content,文本内容\n
|
| 710 |
+
返回-Returns:
|
| 711 |
+
list: 示例结果:[{'lang':'zh','text':'?'},...]\n
|
| 712 |
+
lang=语种 , text=内容\n
|
| 713 |
+
"""
|
| 714 |
+
return LangSegment.getTexts(text)
|
| 715 |
+
|
| 716 |
+
def getCounts():
|
| 717 |
+
"""
|
| 718 |
+
功能:分词结果统计,按语种字数降序,用于确定其主要语言\n
|
| 719 |
+
기능: 주요 언어를 결정하는 데 사용되는 언어별 단어 수 내림차순으로 단어 분할 결과의 통계 \n
|
| 720 |
+
機能:主な言語を決定するために使用される、言語の単語数の降順による単語分割結果の統計\n
|
| 721 |
+
Function: Tokenizing multilingual text input.\n
|
| 722 |
+
返回-Returns:
|
| 723 |
+
list: 示例结果:[('zh', 5), ('ja', 2), ('en', 1)] = [(语种,字数含标点)]\n
|
| 724 |
+
"""
|
| 725 |
+
return LangSegment.getCounts()
|
| 726 |
+
|
| 727 |
+
def classify(text:str):
|
| 728 |
+
"""
|
| 729 |
+
功能:兼容接口实现
|
| 730 |
+
Function: Compatible interface implementation
|
| 731 |
+
"""
|
| 732 |
+
return LangSegment.classify(text)
|
| 733 |
+
|
| 734 |
+
def printList(langlist):
|
| 735 |
+
"""
|
| 736 |
+
功能:打印数组结果
|
| 737 |
+
기능: 어레이 결과 인쇄
|
| 738 |
+
機能:配列結果を印刷
|
| 739 |
+
Function: Print array results
|
| 740 |
+
"""
|
| 741 |
+
print("\n\n===================【打印结果】===================")
|
| 742 |
+
if langlist is None or len(langlist) == 0:
|
| 743 |
+
print("无内容结果,No content result")
|
| 744 |
+
return
|
| 745 |
+
for line in langlist:
|
| 746 |
+
print(line)
|
| 747 |
+
pass
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
|
| 751 |
+
def main():
|
| 752 |
+
|
| 753 |
+
# -----------------------------------
|
| 754 |
+
# 更新日志:新版本分词更加精准。
|
| 755 |
+
# Changelog: The new version of the word segmentation is more accurate.
|
| 756 |
+
# チェンジログ:新しいバージョンの単語セグメンテーションはより正確です。
|
| 757 |
+
# Changelog: 분할이라는 단어의 새로운 버전이 더 정확합니다.
|
| 758 |
+
# -----------------------------------
|
| 759 |
+
|
| 760 |
+
# 输入示例1:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
|
| 761 |
+
# text = "“昨日は雨が降った,音楽、映画。。。”你今天学习日语了吗?春は桜の季節です。语种分词是语音合成必不可少的环节。言語分詞は音声合成に欠かせない環節である!"
|
| 762 |
+
|
| 763 |
+
# 输入示例2:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
|
| 764 |
+
# text = "欢迎来玩。東京,は日本の首都です。欢迎来玩. 太好了!"
|
| 765 |
+
|
| 766 |
+
# 输入示例3:(包含日文,中文)Input Example 1: (including Japanese, Chinese)
|
| 767 |
+
# text = "明日、私たちは海辺にバカンスに行きます。你会说日语吗:“中国語、話せますか” 你的日语真好啊!"
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
# 输入示例4:(包含日文,中文,韩语,英文)Input Example 4: (including Japanese, Chinese, Korean, English)
|
| 771 |
+
# text = "你的名字叫<ja>佐々木?<ja>吗?韩语中的안녕 오빠读什么呢?あなたの体育の先生は誰ですか? 此次发布会带来了四款iPhone 15系列机型和三款Apple Watch等一系列新品,这次的iPad Air采用了LCD屏幕"
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
# 试验性支持:"fr"法语 , "vi"越南语 , "ru"俄语 , "th"泰语。Experimental: Other language support.
|
| 775 |
+
LangSegment.setfilters(["fr", "vi" , "ja", "zh", "ko", "en" , "ru" , "th"])
|
| 776 |
+
text = """
|
| 777 |
+
我喜欢在雨天里听音乐。
|
| 778 |
+
I enjoy listening to music on rainy days.
|
| 779 |
+
雨の日に音楽を聴くのが好きです。
|
| 780 |
+
비 오는 날에 음악을 듣는 것을 즐깁니다。
|
| 781 |
+
J'aime écouter de la musique les jours de pluie.
|
| 782 |
+
Tôi thích nghe nhạc vào những ngày mưa.
|
| 783 |
+
Мне нравится слушать музыку в дождливую погоду.
|
| 784 |
+
ฉันชอบฟังเพลงในวันที่ฝนตก
|
| 785 |
+
"""
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
# 进行分词:(接入TTS项目仅需一行代码调用)Segmentation: (Only one line of code is required to access the TTS project)
|
| 789 |
+
langlist = LangSegment.getTexts(text)
|
| 790 |
+
printList(langlist)
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
# 语种统计:Language statistics:
|
| 794 |
+
print("\n===================【语种统计】===================")
|
| 795 |
+
# 获取所有语种数组结果,根据内容字数降序排列
|
| 796 |
+
# Get the array results in all languages, sorted in descending order according to the number of content words
|
| 797 |
+
langCounts = LangSegment.getCounts()
|
| 798 |
+
print(langCounts , "\n")
|
| 799 |
+
|
| 800 |
+
# 根据结果获取内容的主要语种 (语言,字数含标点)
|
| 801 |
+
# Get the main language of content based on the results (language, word count including punctuation)
|
| 802 |
+
lang , count = langCounts[0]
|
| 803 |
+
print(f"输入内容的主要语言为 = {lang} ,字数 = {count}")
|
| 804 |
+
print("==================================================\n")
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
# 分词输出:lang=语言,text=内容。Word output: lang = language, text = content
|
| 808 |
+
# ===================【打印结果】===================
|
| 809 |
+
# {'lang': 'zh', 'text': '你的名字叫'}
|
| 810 |
+
# {'lang': 'ja', 'text': '佐々木?'}
|
| 811 |
+
# {'lang': 'zh', 'text': '吗?韩语中的'}
|
| 812 |
+
# {'lang': 'ko', 'text': '안녕 오빠'}
|
| 813 |
+
# {'lang': 'zh', 'text': '读什么呢?'}
|
| 814 |
+
# {'lang': 'ja', 'text': 'あなたの体育の先生は誰ですか?'}
|
| 815 |
+
# {'lang': 'zh', 'text': ' 此次发布会带来了四款'}
|
| 816 |
+
# {'lang': 'en', 'text': 'i Phone '}
|
| 817 |
+
# {'lang': 'zh', 'text': '15系列机型和三款'}
|
| 818 |
+
# {'lang': 'en', 'text': 'Apple Watch '}
|
| 819 |
+
# {'lang': 'zh', 'text': '等一系列新品,这次的'}
|
| 820 |
+
# {'lang': 'en', 'text': 'i Pad Air '}
|
| 821 |
+
# {'lang': 'zh', 'text': '采用了'}
|
| 822 |
+
# {'lang': 'en', 'text': 'L C D '}
|
| 823 |
+
# {'lang': 'zh', 'text': '屏幕'}
|
| 824 |
+
# ===================【语种统计】===================
|
| 825 |
+
|
| 826 |
+
# ===================【语种统计】===================
|
| 827 |
+
# [('zh', 51), ('ja', 19), ('en', 18), ('ko', 5)]
|
| 828 |
+
|
| 829 |
+
# 输入内容的主要语言为 = zh ,字数 = 51
|
| 830 |
+
# ==================================================
|
| 831 |
+
# The main language of the input content is = zh, word count = 51
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
if __name__ == "__main__":
|
| 835 |
+
main()
|
| 836 |
+
|
| 837 |
+
|
runtime/Lib/site-packages/LangSegment/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .LangSegment import LangSegment,getTexts,classify,getCounts,printList,setfilters,getfilters,setPriorityThreshold,getPriorityThreshold,setEnablePreview,getEnablePreview,setKeepPinyin,getKeepPinyin
|
| 2 |
+
|
| 3 |
+
# release
|
| 4 |
+
__version__ = '0.3.3'
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# develop
|
| 8 |
+
__develop__ = 'dev-0.0.1'
|
runtime/Lib/site-packages/joblib-1.2.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
runtime/Lib/site-packages/joblib-1.2.0.dist-info/LICENSE.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
BSD 3-Clause License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2008-2021, The joblib developers.
|
| 4 |
+
All rights reserved.
|
| 5 |
+
|
| 6 |
+
Redistribution and use in source and binary forms, with or without
|
| 7 |
+
modification, are permitted provided that the following conditions are met:
|
| 8 |
+
|
| 9 |
+
* Redistributions of source code must retain the above copyright notice, this
|
| 10 |
+
list of conditions and the following disclaimer.
|
| 11 |
+
|
| 12 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
| 13 |
+
this list of conditions and the following disclaimer in the documentation
|
| 14 |
+
and/or other materials provided with the distribution.
|
| 15 |
+
|
| 16 |
+
* Neither the name of the copyright holder nor the names of its
|
| 17 |
+
contributors may be used to endorse or promote products derived from
|
| 18 |
+
this software without specific prior written permission.
|
| 19 |
+
|
| 20 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 21 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 22 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 23 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 24 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 25 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 26 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 27 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 28 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 29 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
runtime/Lib/site-packages/joblib-1.2.0.dist-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|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: joblib
|
| 3 |
+
Version: 1.2.0
|
| 4 |
+
Summary: Lightweight pipelining with Python functions
|
| 5 |
+
Home-page: https://joblib.readthedocs.io
|
| 6 |
+
Author: Gael Varoquaux
|
| 7 |
+
Author-email: gael.varoquaux@normalesup.org
|
| 8 |
+
License: BSD
|
| 9 |
+
Project-URL: Source, https://github.com/joblib/joblib
|
| 10 |
+
Platform: any
|
| 11 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 12 |
+
Classifier: Environment :: Console
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Intended Audience :: Science/Research
|
| 15 |
+
Classifier: Intended Audience :: Education
|
| 16 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 17 |
+
Classifier: Operating System :: OS Independent
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 23 |
+
Classifier: Topic :: Scientific/Engineering
|
| 24 |
+
Classifier: Topic :: Utilities
|
| 25 |
+
Classifier: Topic :: Software Development :: Libraries
|
| 26 |
+
Requires-Python: >=3.7
|
| 27 |
+
Description-Content-Type: text/x-rst
|
| 28 |
+
License-File: LICENSE.txt
|
| 29 |
+
|
| 30 |
+
|PyPi| |Azure| |ReadTheDocs| |Codecov|
|
| 31 |
+
|
| 32 |
+
.. |PyPi| image:: https://badge.fury.io/py/joblib.svg
|
| 33 |
+
:target: https://badge.fury.io/py/joblib
|
| 34 |
+
:alt: Joblib version
|
| 35 |
+
|
| 36 |
+
.. |Azure| image:: https://dev.azure.com/joblib/joblib/_apis/build/status/joblib.joblib?branchName=master
|
| 37 |
+
:target: https://dev.azure.com/joblib/joblib/_build?definitionId=3&_a=summary&branchFilter=40
|
| 38 |
+
:alt: Azure CI status
|
| 39 |
+
|
| 40 |
+
.. |ReadTheDocs| image:: https://readthedocs.org/projects/joblib/badge/?version=latest
|
| 41 |
+
:target: https://joblib.readthedocs.io/en/latest/?badge=latest
|
| 42 |
+
:alt: Documentation Status
|
| 43 |
+
|
| 44 |
+
.. |Codecov| image:: https://codecov.io/gh/joblib/joblib/branch/master/graph/badge.svg
|
| 45 |
+
:target: https://codecov.io/gh/joblib/joblib
|
| 46 |
+
:alt: Codecov coverage
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
The homepage of joblib with user documentation is located on:
|
| 50 |
+
|
| 51 |
+
https://joblib.readthedocs.io
|
| 52 |
+
|
| 53 |
+
Getting the latest code
|
| 54 |
+
=======================
|
| 55 |
+
|
| 56 |
+
To get the latest code using git, simply type::
|
| 57 |
+
|
| 58 |
+
git clone git://github.com/joblib/joblib.git
|
| 59 |
+
|
| 60 |
+
If you don't have git installed, you can download a zip or tarball
|
| 61 |
+
of the latest code: http://github.com/joblib/joblib/archives/master
|
| 62 |
+
|
| 63 |
+
Installing
|
| 64 |
+
==========
|
| 65 |
+
|
| 66 |
+
You can use `pip` to install joblib::
|
| 67 |
+
|
| 68 |
+
pip install joblib
|
| 69 |
+
|
| 70 |
+
from any directory or::
|
| 71 |
+
|
| 72 |
+
python setup.py install
|
| 73 |
+
|
| 74 |
+
from the source directory.
|
| 75 |
+
|
| 76 |
+
Dependencies
|
| 77 |
+
============
|
| 78 |
+
|
| 79 |
+
- Joblib has no mandatory dependencies besides Python (supported versions are
|
| 80 |
+
3.7+).
|
| 81 |
+
- Joblib has an optional dependency on Numpy (at least version 1.6.1) for array
|
| 82 |
+
manipulation.
|
| 83 |
+
- Joblib includes its own vendored copy of
|
| 84 |
+
`loky <https://github.com/tomMoral/loky>`_ for process management.
|
| 85 |
+
- Joblib can efficiently dump and load numpy arrays but does not require numpy
|
| 86 |
+
to be installed.
|
| 87 |
+
- Joblib has an optional dependency on
|
| 88 |
+
`python-lz4 <https://pypi.python.org/pypi/lz4>`_ as a faster alternative to
|
| 89 |
+
zlib and gzip for compressed serialization.
|
| 90 |
+
- Joblib has an optional dependency on psutil to mitigate memory leaks in
|
| 91 |
+
parallel worker processes.
|
| 92 |
+
- Some examples require external dependencies such as pandas. See the
|
| 93 |
+
instructions in the `Building the docs`_ section for details.
|
| 94 |
+
|
| 95 |
+
Workflow to contribute
|
| 96 |
+
======================
|
| 97 |
+
|
| 98 |
+
To contribute to joblib, first create an account on `github
|
| 99 |
+
<http://github.com/>`_. Once this is done, fork the `joblib repository
|
| 100 |
+
<http://github.com/joblib/joblib>`_ to have your own repository,
|
| 101 |
+
clone it using 'git clone' on the computers where you want to work. Make
|
| 102 |
+
your changes in your clone, push them to your github account, test them
|
| 103 |
+
on several computers, and when you are happy with them, send a pull
|
| 104 |
+
request to the main repository.
|
| 105 |
+
|
| 106 |
+
Running the test suite
|
| 107 |
+
======================
|
| 108 |
+
|
| 109 |
+
To run the test suite, you need the pytest (version >= 3) and coverage modules.
|
| 110 |
+
Run the test suite using::
|
| 111 |
+
|
| 112 |
+
pytest joblib
|
| 113 |
+
|
| 114 |
+
from the root of the project.
|
| 115 |
+
|
| 116 |
+
Building the docs
|
| 117 |
+
=================
|
| 118 |
+
|
| 119 |
+
To build the docs you need to have sphinx (>=1.4) and some dependencies
|
| 120 |
+
installed::
|
| 121 |
+
|
| 122 |
+
pip install -U -r .readthedocs-requirements.txt
|
| 123 |
+
|
| 124 |
+
The docs can then be built with the following command::
|
| 125 |
+
|
| 126 |
+
make doc
|
| 127 |
+
|
| 128 |
+
The html docs are located in the ``doc/_build/html`` directory.
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
Making a source tarball
|
| 132 |
+
=======================
|
| 133 |
+
|
| 134 |
+
To create a source tarball, eg for packaging or distributing, run the
|
| 135 |
+
following command::
|
| 136 |
+
|
| 137 |
+
python setup.py sdist
|
| 138 |
+
|
| 139 |
+
The tarball will be created in the `dist` directory. This command will
|
| 140 |
+
compile the docs, and the resulting tarball can be installed with
|
| 141 |
+
no extra dependencies than the Python standard library. You will need
|
| 142 |
+
setuptool and sphinx.
|
| 143 |
+
|
| 144 |
+
Making a release and uploading it to PyPI
|
| 145 |
+
=========================================
|
| 146 |
+
|
| 147 |
+
This command is only run by project manager, to make a release, and
|
| 148 |
+
upload in to PyPI::
|
| 149 |
+
|
| 150 |
+
python setup.py sdist bdist_wheel
|
| 151 |
+
twine upload dist/*
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
Note that the documentation should automatically get updated at each git
|
| 155 |
+
push. If that is not the case, try building th doc locally and resolve
|
| 156 |
+
any doc build error (in particular when running the examples).
|
| 157 |
+
|
| 158 |
+
Updating the changelog
|
| 159 |
+
======================
|
| 160 |
+
|
| 161 |
+
Changes are listed in the CHANGES.rst file. They must be manually updated
|
| 162 |
+
but, the following git command may be used to generate the lines::
|
| 163 |
+
|
| 164 |
+
git log --abbrev-commit --date=short --no-merges --sparse
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
|
runtime/Lib/site-packages/joblib-1.2.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 2 |
+
joblib-1.2.0.dist-info/LICENSE.txt,sha256=QmEpEcGHLF5LQ_auDo7llGfNNQMyJBz3LOkGQCZPrmo,1527
|
| 3 |
+
joblib-1.2.0.dist-info/METADATA,sha256=8WqQd0iOL12Xi46VHDpPINbmuwBKJAbVZhm431qnTjc,5297
|
| 4 |
+
joblib-1.2.0.dist-info/RECORD,,
|
| 5 |
+
joblib-1.2.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
|
| 6 |
+
joblib-1.2.0.dist-info/top_level.txt,sha256=P0LsoZ45gBL7ckL4lqQt7tdbrHD4xlVYhffmhHeeT_U,7
|
| 7 |
+
joblib/__init__.py,sha256=CXOHJmaK9uQ_RyLc4X-FusXf_NDOwd9gIfkE13qA1yM,4995
|
| 8 |
+
joblib/__pycache__/__init__.cpython-39.pyc,,
|
| 9 |
+
joblib/__pycache__/_cloudpickle_wrapper.cpython-39.pyc,,
|
| 10 |
+
joblib/__pycache__/_dask.cpython-39.pyc,,
|
| 11 |
+
joblib/__pycache__/_deprecated_format_stack.cpython-39.pyc,,
|
| 12 |
+
joblib/__pycache__/_deprecated_my_exceptions.cpython-39.pyc,,
|
| 13 |
+
joblib/__pycache__/_memmapping_reducer.cpython-39.pyc,,
|
| 14 |
+
joblib/__pycache__/_multiprocessing_helpers.cpython-39.pyc,,
|
| 15 |
+
joblib/__pycache__/_parallel_backends.cpython-39.pyc,,
|
| 16 |
+
joblib/__pycache__/_store_backends.cpython-39.pyc,,
|
| 17 |
+
joblib/__pycache__/_utils.cpython-39.pyc,,
|
| 18 |
+
joblib/__pycache__/backports.cpython-39.pyc,,
|
| 19 |
+
joblib/__pycache__/compressor.cpython-39.pyc,,
|
| 20 |
+
joblib/__pycache__/disk.cpython-39.pyc,,
|
| 21 |
+
joblib/__pycache__/executor.cpython-39.pyc,,
|
| 22 |
+
joblib/__pycache__/format_stack.cpython-39.pyc,,
|
| 23 |
+
joblib/__pycache__/func_inspect.cpython-39.pyc,,
|
| 24 |
+
joblib/__pycache__/hashing.cpython-39.pyc,,
|
| 25 |
+
joblib/__pycache__/logger.cpython-39.pyc,,
|
| 26 |
+
joblib/__pycache__/memory.cpython-39.pyc,,
|
| 27 |
+
joblib/__pycache__/my_exceptions.cpython-39.pyc,,
|
| 28 |
+
joblib/__pycache__/numpy_pickle.cpython-39.pyc,,
|
| 29 |
+
joblib/__pycache__/numpy_pickle_compat.cpython-39.pyc,,
|
| 30 |
+
joblib/__pycache__/numpy_pickle_utils.cpython-39.pyc,,
|
| 31 |
+
joblib/__pycache__/parallel.cpython-39.pyc,,
|
| 32 |
+
joblib/__pycache__/pool.cpython-39.pyc,,
|
| 33 |
+
joblib/__pycache__/testing.cpython-39.pyc,,
|
| 34 |
+
joblib/_cloudpickle_wrapper.py,sha256=fUx9s5qv2nMDi0xhIT7ttYJd6fGG8aYdBJbdXM-cBmc,376
|
| 35 |
+
joblib/_dask.py,sha256=Tj4GRYMAucsTblVr0HYNDg0tPFgZcjP6zA55jyPj6NM,13006
|
| 36 |
+
joblib/_deprecated_format_stack.py,sha256=_pPLwMH6hydhpPCNxRRTCkbcsKu-SdM0H-cxn5X-EDE,14505
|
| 37 |
+
joblib/_deprecated_my_exceptions.py,sha256=q8QyZCf_sFBM6PUKaebZMTdIIyx8yeBuOfbyxZX7mA0,4134
|
| 38 |
+
joblib/_memmapping_reducer.py,sha256=axuV2_zUxk7k7iJIWPXM9JXxh20_n3wHwrye1BfmmHE,28277
|
| 39 |
+
joblib/_multiprocessing_helpers.py,sha256=t7wIXfrLfzqFXjOeOYs4JP45tptxmYm5_yE8ylIRbR8,1925
|
| 40 |
+
joblib/_parallel_backends.py,sha256=1ui21a49B-xcu-l1dpzdzytb0sWKsiI0otiIir8o1hU,25438
|
| 41 |
+
joblib/_store_backends.py,sha256=uH1_HSM4C28QM-mCR2Tlq5XQZpwQP7In5kxcWfX9ZO0,14434
|
| 42 |
+
joblib/_utils.py,sha256=1Z5H3H2D0GVNMgQlCusSziMGHKHOl0V3um1tDLj-jY0,1116
|
| 43 |
+
joblib/backports.py,sha256=SLHgXOABF9JiHan3RmI_jIIvkiWEyOoGecg8pIA7z1o,6082
|
| 44 |
+
joblib/compressor.py,sha256=1u7lSlHAji0DMvH2qsxTol1dGzDNTWOsLLCFZuSq1AU,19769
|
| 45 |
+
joblib/disk.py,sha256=PxUC63dBG2O1GriL1SLskHUjz7XzR-y6rqKEJHEY0jA,4389
|
| 46 |
+
joblib/executor.py,sha256=wF4pTwot1wRzGLqozbQ8m46SN40RSUFVMLxprqxG2AY,5316
|
| 47 |
+
joblib/externals/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 48 |
+
joblib/externals/__pycache__/__init__.cpython-39.pyc,,
|
| 49 |
+
joblib/externals/cloudpickle/__init__.py,sha256=AjJuqYtfWZSP5igeJIFvAYsNy6kHgLen58Q4w-ZyWH4,292
|
| 50 |
+
joblib/externals/cloudpickle/__pycache__/__init__.cpython-39.pyc,,
|
| 51 |
+
joblib/externals/cloudpickle/__pycache__/cloudpickle.cpython-39.pyc,,
|
| 52 |
+
joblib/externals/cloudpickle/__pycache__/cloudpickle_fast.cpython-39.pyc,,
|
| 53 |
+
joblib/externals/cloudpickle/__pycache__/compat.cpython-39.pyc,,
|
| 54 |
+
joblib/externals/cloudpickle/cloudpickle.py,sha256=tdSUqMaT1OQcSairpMCPqWn6npVpcdjLuTbhUjD11a8,35137
|
| 55 |
+
joblib/externals/cloudpickle/cloudpickle_fast.py,sha256=BXEnvuGqN1rakNfxpmk0zEbZdQLqttn3n2QCO410mRk,34114
|
| 56 |
+
joblib/externals/cloudpickle/compat.py,sha256=ITODUx0U_b7chpS47_Siqx7YP1rMYUpJH6B3rBANmWY,508
|
| 57 |
+
joblib/externals/loky/__init__.py,sha256=V1JyKhbeXyZ4ThFoXVIvC3GQDc9FOXN4VHV6KV69xs0,1085
|
| 58 |
+
joblib/externals/loky/__pycache__/__init__.cpython-39.pyc,,
|
| 59 |
+
joblib/externals/loky/__pycache__/_base.cpython-39.pyc,,
|
| 60 |
+
joblib/externals/loky/__pycache__/cloudpickle_wrapper.cpython-39.pyc,,
|
| 61 |
+
joblib/externals/loky/__pycache__/initializers.cpython-39.pyc,,
|
| 62 |
+
joblib/externals/loky/__pycache__/process_executor.cpython-39.pyc,,
|
| 63 |
+
joblib/externals/loky/__pycache__/reusable_executor.cpython-39.pyc,,
|
| 64 |
+
joblib/externals/loky/_base.py,sha256=Jd_A_xtbMztXEbsD5I8J1-UUv1M2BGFyrPMMnd9mA-Q,1057
|
| 65 |
+
joblib/externals/loky/backend/__init__.py,sha256=7jTmGTrtjxnQF6rqX_xOd3odn22K-zbe4_Of5yZ6dTc,312
|
| 66 |
+
joblib/externals/loky/backend/__pycache__/__init__.cpython-39.pyc,,
|
| 67 |
+
joblib/externals/loky/backend/__pycache__/_posix_reduction.cpython-39.pyc,,
|
| 68 |
+
joblib/externals/loky/backend/__pycache__/_win_reduction.cpython-39.pyc,,
|
| 69 |
+
joblib/externals/loky/backend/__pycache__/context.cpython-39.pyc,,
|
| 70 |
+
joblib/externals/loky/backend/__pycache__/fork_exec.cpython-39.pyc,,
|
| 71 |
+
joblib/externals/loky/backend/__pycache__/popen_loky_posix.cpython-39.pyc,,
|
| 72 |
+
joblib/externals/loky/backend/__pycache__/popen_loky_win32.cpython-39.pyc,,
|
| 73 |
+
joblib/externals/loky/backend/__pycache__/process.cpython-39.pyc,,
|
| 74 |
+
joblib/externals/loky/backend/__pycache__/queues.cpython-39.pyc,,
|
| 75 |
+
joblib/externals/loky/backend/__pycache__/reduction.cpython-39.pyc,,
|
| 76 |
+
joblib/externals/loky/backend/__pycache__/resource_tracker.cpython-39.pyc,,
|
| 77 |
+
joblib/externals/loky/backend/__pycache__/spawn.cpython-39.pyc,,
|
| 78 |
+
joblib/externals/loky/backend/__pycache__/synchronize.cpython-39.pyc,,
|
| 79 |
+
joblib/externals/loky/backend/__pycache__/utils.cpython-39.pyc,,
|
| 80 |
+
joblib/externals/loky/backend/_posix_reduction.py,sha256=FTCvX2f5IfKX5obn5tr61xP6TkN4E68L-mBhWr8tpn4,1801
|
| 81 |
+
joblib/externals/loky/backend/_win_reduction.py,sha256=F6hddzf7ZPUj1O4OYJbZ12pJmBrvGZ3mDaispPa-iqo,2042
|
| 82 |
+
joblib/externals/loky/backend/context.py,sha256=BIRF8utNPHzb0EbjplFzlL0YYa87bPKN2vbFE-NQxl4,11433
|
| 83 |
+
joblib/externals/loky/backend/fork_exec.py,sha256=rBuA8fdO5TVaQBeV7TFrLri3VhLzseyKnBc04fB904A,1185
|
| 84 |
+
joblib/externals/loky/backend/popen_loky_posix.py,sha256=9wOtvORNSP11KQKa8jRSVfQHVvel7lUtCWGRPEkMhTk,5556
|
| 85 |
+
joblib/externals/loky/backend/popen_loky_win32.py,sha256=nll8E81wMpglVazStwo7k3OybdDqOItKA2L84VEr4ag,5052
|
| 86 |
+
joblib/externals/loky/backend/process.py,sha256=LgGKNvSIN7uA-piZ3vdEWpJPgGepU73cRiacA9VqdG0,1798
|
| 87 |
+
joblib/externals/loky/backend/queues.py,sha256=29UGM2u12PvXCB6c-Gkakmc_jlzdYzF0MoXlIileY6Q,6801
|
| 88 |
+
joblib/externals/loky/backend/reduction.py,sha256=6IAslYWdqqotcVSh-6caV-Hy142BaqRQedR7pCYmvtU,7062
|
| 89 |
+
joblib/externals/loky/backend/resource_tracker.py,sha256=Z6dqTP3SyAwtzVDEVbXeAwQj1BKkijhO1uSGst397ug,14359
|
| 90 |
+
joblib/externals/loky/backend/spawn.py,sha256=mydRcNAvzdJt6f1v2T-ORXzF5DlmNKDYTnHukCTLzqE,8857
|
| 91 |
+
joblib/externals/loky/backend/synchronize.py,sha256=CvVpKTTlaKhH0ED573XF9ZrBGau4eBjn3KQGYSCkOfU,11719
|
| 92 |
+
joblib/externals/loky/backend/utils.py,sha256=-bzkl3uj8sr9pFzxUbL6_-f7W-ekC4P10Im1JxXwBcc,5738
|
| 93 |
+
joblib/externals/loky/cloudpickle_wrapper.py,sha256=gUDfxIQ7sm_stiGym1lP5SP9xFbJnUbVZiIG_ypKE9s,3578
|
| 94 |
+
joblib/externals/loky/initializers.py,sha256=XHjfNLD9Y5ruzrpg9geluDPxs4C-kn4s9q1iUGSBlGA,2539
|
| 95 |
+
joblib/externals/loky/process_executor.py,sha256=XVSS0A3WcsweWfnaBnAVtStMtu-1X9y9MYeE-adaCkA,48885
|
| 96 |
+
joblib/externals/loky/reusable_executor.py,sha256=_y61oYui2GMqq5XnOScrwH5Z82lFBgUI6nMnYMGnKBg,10028
|
| 97 |
+
joblib/format_stack.py,sha256=I5WFLlnyYhrYEtZWJXtVhv70B7AwWV_pL4ElvgnIW1o,1045
|
| 98 |
+
joblib/func_inspect.py,sha256=sS-Nc7Xe8SJXtRta8ILhzOCF2KG9TE_UGe5V9qTQIIg,13945
|
| 99 |
+
joblib/hashing.py,sha256=NO90wKt1boeyAM8RlD0HtNwJHVsGLvKdVj9oRGpi8_Y,10537
|
| 100 |
+
joblib/logger.py,sha256=xjTDhqjpQU8DjIqrL35IiZ1z7HJ-fgbVc-7Ijcii3Eg,5129
|
| 101 |
+
joblib/memory.py,sha256=j5nTnYMzVDcQOtQYE68Oc_HAu_JY9bF8VXOysHfFvUQ,40609
|
| 102 |
+
joblib/my_exceptions.py,sha256=-TkSV9Uy6kVSOSm870CQFYHIbIM6CJKlQtrrM-XRDAw,962
|
| 103 |
+
joblib/numpy_pickle.py,sha256=58LBcb1HIvEoew4yCwPl18dvSnCA7F0zLTacOUimN7E,26869
|
| 104 |
+
joblib/numpy_pickle_compat.py,sha256=eRRsub4aOB0fPmkC5L-JoKKs6Nv7hFs9ZwQmDmbANQg,8547
|
| 105 |
+
joblib/numpy_pickle_utils.py,sha256=Ema4jJslsCG_HDIAtnjT7wDNw09Uv-5367N02SN3lAM,8705
|
| 106 |
+
joblib/parallel.py,sha256=_4fVQXQ2mlnJeAaIJQHGNw3w32nw5Rj9pfW-FVi9bX4,48569
|
| 107 |
+
joblib/pool.py,sha256=JuG9uuE3KJwR8gJZIGzwJqObJD0xFuUhQP2IYvgQab0,14334
|
| 108 |
+
joblib/test/__init__.py,sha256=bkIwY5OneyPcRn2VuzQlIFdtW5Cwo1mUJ7IfSztDO9c,73
|
| 109 |
+
joblib/test/__pycache__/__init__.cpython-39.pyc,,
|
| 110 |
+
joblib/test/__pycache__/common.cpython-39.pyc,,
|
| 111 |
+
joblib/test/__pycache__/test_backports.cpython-39.pyc,,
|
| 112 |
+
joblib/test/__pycache__/test_cloudpickle_wrapper.cpython-39.pyc,,
|
| 113 |
+
joblib/test/__pycache__/test_dask.cpython-39.pyc,,
|
| 114 |
+
joblib/test/__pycache__/test_deprecated_objects.cpython-39.pyc,,
|
| 115 |
+
joblib/test/__pycache__/test_disk.cpython-39.pyc,,
|
| 116 |
+
joblib/test/__pycache__/test_format_stack.cpython-39.pyc,,
|
| 117 |
+
joblib/test/__pycache__/test_func_inspect.cpython-39.pyc,,
|
| 118 |
+
joblib/test/__pycache__/test_func_inspect_special_encoding.cpython-39.pyc,,
|
| 119 |
+
joblib/test/__pycache__/test_hashing.cpython-39.pyc,,
|
| 120 |
+
joblib/test/__pycache__/test_init.cpython-39.pyc,,
|
| 121 |
+
joblib/test/__pycache__/test_logger.cpython-39.pyc,,
|
| 122 |
+
joblib/test/__pycache__/test_memmapping.cpython-39.pyc,,
|
| 123 |
+
joblib/test/__pycache__/test_memory.cpython-39.pyc,,
|
| 124 |
+
joblib/test/__pycache__/test_missing_multiprocessing.cpython-39.pyc,,
|
| 125 |
+
joblib/test/__pycache__/test_module.cpython-39.pyc,,
|
| 126 |
+
joblib/test/__pycache__/test_my_exceptions.cpython-39.pyc,,
|
| 127 |
+
joblib/test/__pycache__/test_numpy_pickle.cpython-39.pyc,,
|
| 128 |
+
joblib/test/__pycache__/test_numpy_pickle_compat.cpython-39.pyc,,
|
| 129 |
+
joblib/test/__pycache__/test_numpy_pickle_utils.cpython-39.pyc,,
|
| 130 |
+
joblib/test/__pycache__/test_parallel.cpython-39.pyc,,
|
| 131 |
+
joblib/test/__pycache__/test_store_backends.cpython-39.pyc,,
|
| 132 |
+
joblib/test/__pycache__/test_testing.cpython-39.pyc,,
|
| 133 |
+
joblib/test/__pycache__/test_utils.cpython-39.pyc,,
|
| 134 |
+
joblib/test/__pycache__/testutils.cpython-39.pyc,,
|
| 135 |
+
joblib/test/common.py,sha256=gWDIvGl8Ns6vPTBvItuSFoEWigI0EPXSoPkSvqSM4zM,3283
|
| 136 |
+
joblib/test/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 137 |
+
joblib/test/data/__pycache__/__init__.cpython-39.pyc,,
|
| 138 |
+
joblib/test/data/__pycache__/create_numpy_pickle.cpython-39.pyc,,
|
| 139 |
+
joblib/test/data/create_numpy_pickle.py,sha256=9Gm6_T-pqe7LGTo0xbz3e1KjIhqKKb6A7ImSAlY2RyM,3459
|
| 140 |
+
joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np16.gz,sha256=QYRH6Q2DSGVorjCSqWCxjTWCMOJKyew4Nl2qmfQVvQ8,769
|
| 141 |
+
joblib/test/data/joblib_0.10.0_compressed_pickle_py27_np17.gz,sha256=ofTozM_KlPJa50TR8FCwc09mMmO6OO0GQhgUBLNIsXs,757
|
| 142 |
+
joblib/test/data/joblib_0.10.0_compressed_pickle_py33_np18.gz,sha256=2eIVeA-XjOaT5IEQ6tI2UuHG3hwhiRciMmkBmPcIh4g,792
|
| 143 |
+
joblib/test/data/joblib_0.10.0_compressed_pickle_py34_np19.gz,sha256=Gr2z_1tVWDH1H3_wCVHmakknf8KqeHKT8Yz4d1vmUCM,794
|
| 144 |
+
joblib/test/data/joblib_0.10.0_compressed_pickle_py35_np19.gz,sha256=pWw_xuDbOkECqu1KGf1OFU7s2VbzC2v5F5iXhE7TwB4,790
|
| 145 |
+
joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl,sha256=icRQjj374B-AHk5znxre0T9oWUHokoHIBQ8MqKo8l-U,986
|
| 146 |
+
joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.bz2,sha256=oYQVIyMiUxyRgWSuBBSOvCWKzToA-kUpcoQWdV4UoV4,997
|
| 147 |
+
joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.gzip,sha256=Jpv3iGcDgKTv-O4nZsUreIbUK7qnt2cugZ-VMgNeEDQ,798
|
| 148 |
+
joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.lzma,sha256=c0wu0x8pPv4BcStj7pE61rZpf68FLG_pNzQZ4e82zH8,660
|
| 149 |
+
joblib/test/data/joblib_0.10.0_pickle_py27_np17.pkl.xz,sha256=77FG1FDG0GHQav-1bxc4Tn9ky6ubUW_MbE0_iGmz5wc,712
|
| 150 |
+
joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl,sha256=4GTC7s_cWNVShERn2nvVbspZYJgyK_0man4TEqvdVzU,1068
|
| 151 |
+
joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.bz2,sha256=6G1vbs_iYmz2kYJ6w4qB1k7D67UnxUMus0S4SWeBtFo,1000
|
| 152 |
+
joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.gzip,sha256=tlRUWeJS1BXmcwtLNSNK9L0hDHekFl07CqWxTShinmY,831
|
| 153 |
+
joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.lzma,sha256=CorPwnfv3rR5hjNtJI01-sEBMOnkSxNlRVaWTszMopA,694
|
| 154 |
+
joblib/test/data/joblib_0.10.0_pickle_py33_np18.pkl.xz,sha256=Dppj3MffOKsKETeptEtDaxPOv6MA6xnbpK5LzlDQ-oE,752
|
| 155 |
+
joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl,sha256=HL5Fb1uR9aPLjjhoOPJ2wwM1Qyo1FCZoYYd2HVw0Fos,1068
|
| 156 |
+
joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2,sha256=Pyr2fqZnwfUxXdyrBr-kRwBYY8HA_Yi7fgSguKy5pUs,1021
|
| 157 |
+
joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.gzip,sha256=os8NJjQI9FhnlZM-Ay9dX_Uo35gZnoJCgQSIVvcBPfE,831
|
| 158 |
+
joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.lzma,sha256=Q_0y43qU7_GqAabJ8y3PWVhOisurnCAq3GzuCu04V58,697
|
| 159 |
+
joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz,sha256=BNfmiQfpeLVpdfkwlJK4hJ5Cpgl0vreVyekyc5d_PNM,752
|
| 160 |
+
joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl,sha256=l7nvLolhBDIdPFznOz3lBHiMOPBPCMi1bXop1tFSCpY,1068
|
| 161 |
+
joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.bz2,sha256=pqGpuIS-ZU4uP8mkglHs8MaSDiVcPy7l3XHYJSppRgY,1005
|
| 162 |
+
joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.gzip,sha256=YRFXE6LEb6qK72yPqnXdqQVY8Ts8xKUS9PWQKhLxWvk,833
|
| 163 |
+
joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.lzma,sha256=Bf7gCUeTuTjCkbcIdyZYz69irblX4SAVQEzxCnMQhNU,701
|
| 164 |
+
joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz,sha256=As8w2LGWwwNmKy3QNdKljK63Yq46gjRf_RJ0lh5_WqA,752
|
| 165 |
+
joblib/test/data/joblib_0.11.0_compressed_pickle_py36_np111.gz,sha256=1WrnXDqDoNEPYOZX1Q5Wr2463b8vVV6fw4Wm5S4bMt4,800
|
| 166 |
+
joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl,sha256=XmsOFxeC1f1aYdGETclG6yfF9rLoB11DayOAhDMULrw,1068
|
| 167 |
+
joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.bz2,sha256=vI2yWb50LKL_NgZyd_XkoD5teIg93uI42mWnx9ee-AQ,991
|
| 168 |
+
joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.gzip,sha256=1WrnXDqDoNEPYOZX1Q5Wr2463b8vVV6fw4Wm5S4bMt4,800
|
| 169 |
+
joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.lzma,sha256=IWA0JlZG2ur53HgTUDl1m7q79dcVq6b0VOq33gKoJU0,715
|
| 170 |
+
joblib/test/data/joblib_0.11.0_pickle_py36_np111.pkl.xz,sha256=3Xh_NbMZdBjYx7ynfJ3Fyke28izSRSSzzNB0z5D4k9Y,752
|
| 171 |
+
joblib/test/data/joblib_0.8.4_compressed_pickle_py27_np17.gz,sha256=Sp-ZT7i6pj5on2gbptszu7RarzJpOmHJ67UKOmCPQMg,659
|
| 172 |
+
joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np16.gz,sha256=NLtDrvo2XIH0KvUUAvhOqMeoXEjGW0IuTk_osu5XiDw,658
|
| 173 |
+
joblib/test/data/joblib_0.9.2_compressed_pickle_py27_np17.gz,sha256=NLtDrvo2XIH0KvUUAvhOqMeoXEjGW0IuTk_osu5XiDw,658
|
| 174 |
+
joblib/test/data/joblib_0.9.2_compressed_pickle_py34_np19.gz,sha256=nzO9iiGkG3KbBdrF3usOho8higkrDj_lmICUzxZyF_Y,673
|
| 175 |
+
joblib/test/data/joblib_0.9.2_compressed_pickle_py35_np19.gz,sha256=nzO9iiGkG3KbBdrF3usOho8higkrDj_lmICUzxZyF_Y,673
|
| 176 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl,sha256=naijdk2xIeKdIa3mfJw0JlmOdtiN6uRM1yOJg6-M73M,670
|
| 177 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
|
| 178 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
|
| 179 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_03.npy,sha256=oMRa4qKJhBy-uiRDt-uqOzHAqencxzKUrKVynaAJJAU,236
|
| 180 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np16.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
|
| 181 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl,sha256=LynX8dLOygfxDfFywOgm7wgWOhSxLG7z-oDsU6X83Dw,670
|
| 182 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
|
| 183 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
|
| 184 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_03.npy,sha256=oMRa4qKJhBy-uiRDt-uqOzHAqencxzKUrKVynaAJJAU,236
|
| 185 |
+
joblib/test/data/joblib_0.9.2_pickle_py27_np17.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
|
| 186 |
+
joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl,sha256=w9TLxpDTzp5TI6cU6lRvMsAasXEChcQgGE9s30sm_CU,691
|
| 187 |
+
joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
|
| 188 |
+
joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
|
| 189 |
+
joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
|
| 190 |
+
joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
|
| 191 |
+
joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl,sha256=ilOBAOaulLFvKrD32S1NfnpiK-LfzA9rC3O2I7xROuI,691
|
| 192 |
+
joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
|
| 193 |
+
joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
|
| 194 |
+
joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
|
| 195 |
+
joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
|
| 196 |
+
joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl,sha256=WfDVIqKcMzzh1gSAshIfzBoIpdLdZQuG79yYf5kfpOo,691
|
| 197 |
+
joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_01.npy,sha256=DvvX2c5-7DpuCg20HnleA5bMo9awN9rWxhtGSEPSiAk,120
|
| 198 |
+
joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy,sha256=HBzzbLeB-8whuVO7CgtF3wktoOrg52WILlljzNcBBbE,120
|
| 199 |
+
joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_03.npy,sha256=jt6aZKUrJdfbMJUJVsl47As5MrfRSs1avGMhbmS6vec,307
|
| 200 |
+
joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy,sha256=PsviRClLqT4IR5sWwbmpQR41af9mDtBFncodJBOB3wU,104
|
| 201 |
+
joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz,sha256=8jYfWJsx0oY2J-3LlmEigK5cClnJSW2J2rfeSTZw-Ts,802
|
| 202 |
+
joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_01.npy.z,sha256=YT9VvT3sEl2uWlOyvH2CkyE9Sok4od9O3kWtgeuUUqE,43
|
| 203 |
+
joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_02.npy.z,sha256=txA5RDI0PRuiU_UNKY8pGp-zQgQQ9vaVvMi60hOPaVs,43
|
| 204 |
+
joblib/test/data/joblib_0.9.4.dev0_compressed_cache_size_pickle_py35_np19.gz_03.npy.z,sha256=d3AwICvU2MpSNjh2aPIsdJeGZLlDjANAF1Soa6uM0Po,37
|
| 205 |
+
joblib/test/test_backports.py,sha256=Y9bhGa6H-K_FgLkDyXaSHzpaWk148Rjn8R9IKCKdy-k,1175
|
| 206 |
+
joblib/test/test_cloudpickle_wrapper.py,sha256=GNaOG8SygvHfWNdhV5nirM3uo4F-5OB3yuGlg7xtrSY,749
|
| 207 |
+
joblib/test/test_dask.py,sha256=LmHYrjNKa8v7I3hnEV1nmSzVoG6Ip5gOcBBrxlZDy0M,18004
|
| 208 |
+
joblib/test/test_deprecated_objects.py,sha256=r5Y_Bcomk-CXvwCDlNrIN7eqXytVeQ4h_sMPinkPkrE,1077
|
| 209 |
+
joblib/test/test_disk.py,sha256=wJd1o9nLzqEjLqxxkgB9S7-UcKjHPQ8qK5l0czcNp0o,2205
|
| 210 |
+
joblib/test/test_format_stack.py,sha256=wTtjRlp0edNv7_NzxZU6DAVJQoebL-lnGsUEMwVZXpM,4250
|
| 211 |
+
joblib/test/test_func_inspect.py,sha256=KDvLtRziyA_r6GiNEh05_zhlx9ntJW7abSuQ6cqJajU,8935
|
| 212 |
+
joblib/test/test_func_inspect_special_encoding.py,sha256=oHbMTPOK3XI0YVoS0GsouJ-GfM_neP4GOIJC-TKnNgU,146
|
| 213 |
+
joblib/test/test_hashing.py,sha256=bW7F8gLQwDpCOFRCAWlDx1iyGjQ3BDEYBol3vpEztaE,16078
|
| 214 |
+
joblib/test/test_init.py,sha256=bgNF-9CIJl1MFNA75LBWOaiNtvduVfuvglz_u9Tt8Uc,422
|
| 215 |
+
joblib/test/test_logger.py,sha256=WjxDzpRmdwj_Uyt2R-S3DFRT9CGTk7G2DWucU3sqbu8,985
|
| 216 |
+
joblib/test/test_memmapping.py,sha256=l7uIhxgbcLh1WepMdB2IBEamZ_RisbVK38BQtdGPB1o,42512
|
| 217 |
+
joblib/test/test_memory.py,sha256=sgoBhXWgZjWTb3GiV21RAn34ehpku5aaZjzWR6338Ow,43864
|
| 218 |
+
joblib/test/test_missing_multiprocessing.py,sha256=oeneMgi6iUVIbkfazGvXmOp6fqa7ok9uhj902Qjs_nk,1123
|
| 219 |
+
joblib/test/test_module.py,sha256=HTHQSgnwa-1blkvhL_oVBO5yYdw8IrQTIJCK_QCsMtM,1936
|
| 220 |
+
joblib/test/test_my_exceptions.py,sha256=4_1xlIwbgEt6_bqaQ8lGyTfUAV7RhLMRRbQKIyYOTA8,2066
|
| 221 |
+
joblib/test/test_numpy_pickle.py,sha256=dzt4F53-ANNEr0jWqCeppePIaHp7uh8vuCu7rx9-CtE,42357
|
| 222 |
+
joblib/test/test_numpy_pickle_compat.py,sha256=C5OiaFrqmxYD57fr_LpmItd6OOZPeOMfo9RVr6ZZIkk,624
|
| 223 |
+
joblib/test/test_numpy_pickle_utils.py,sha256=PJVVgr-v3so9oAf9LblASRCpt-wXAo19FvsUpw-fZjI,421
|
| 224 |
+
joblib/test/test_parallel.py,sha256=WAnr1vHXnEN8muI-txTOXZ2AMv8hWVOoTxKqCgputhg,61231
|
| 225 |
+
joblib/test/test_store_backends.py,sha256=fZh0_E5Rj5VTJ_UzH3autHpWwEaWQvWTiQB8felVAN4,1942
|
| 226 |
+
joblib/test/test_testing.py,sha256=I-EkdKHWdHu8m5fo2NnyB0AqR8zAOJ01WKKvyZYRneY,2467
|
| 227 |
+
joblib/test/test_utils.py,sha256=L6aBHiZrF6TUFbPGmQXGyNMnoAy5pEhOJoH5CAG_6CU,584
|
| 228 |
+
joblib/test/testutils.py,sha256=6a7zVJm1kg6M-t4CH9tz8A6rMdC6ZY9sU6wBB8C7Zzo,251
|
| 229 |
+
joblib/testing.py,sha256=JqQDWEkN76ZPmt65EswiERMofFre_JUFzBJgfmw2k2w,2260
|
runtime/Lib/site-packages/joblib-1.2.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.37.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
runtime/Lib/site-packages/joblib-1.2.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
joblib
|
runtime/Lib/site-packages/joblib/__init__.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Joblib is a set of tools to provide **lightweight pipelining in
|
| 2 |
+
Python**. In particular:
|
| 3 |
+
|
| 4 |
+
1. transparent disk-caching of functions and lazy re-evaluation
|
| 5 |
+
(memoize pattern)
|
| 6 |
+
|
| 7 |
+
2. easy simple parallel computing
|
| 8 |
+
|
| 9 |
+
Joblib is optimized to be **fast** and **robust** on large
|
| 10 |
+
data in particular and has specific optimizations for `numpy` arrays. It is
|
| 11 |
+
**BSD-licensed**.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
==================== ===============================================
|
| 15 |
+
**Documentation:** https://joblib.readthedocs.io
|
| 16 |
+
|
| 17 |
+
**Download:** https://pypi.python.org/pypi/joblib#downloads
|
| 18 |
+
|
| 19 |
+
**Source code:** https://github.com/joblib/joblib
|
| 20 |
+
|
| 21 |
+
**Report issues:** https://github.com/joblib/joblib/issues
|
| 22 |
+
==================== ===============================================
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
Vision
|
| 26 |
+
--------
|
| 27 |
+
|
| 28 |
+
The vision is to provide tools to easily achieve better performance and
|
| 29 |
+
reproducibility when working with long running jobs.
|
| 30 |
+
|
| 31 |
+
* **Avoid computing the same thing twice**: code is often rerun again and
|
| 32 |
+
again, for instance when prototyping computational-heavy jobs (as in
|
| 33 |
+
scientific development), but hand-crafted solutions to alleviate this
|
| 34 |
+
issue are error-prone and often lead to unreproducible results.
|
| 35 |
+
|
| 36 |
+
* **Persist to disk transparently**: efficiently persisting
|
| 37 |
+
arbitrary objects containing large data is hard. Using
|
| 38 |
+
joblib's caching mechanism avoids hand-written persistence and
|
| 39 |
+
implicitly links the file on disk to the execution context of
|
| 40 |
+
the original Python object. As a result, joblib's persistence is
|
| 41 |
+
good for resuming an application status or computational job, eg
|
| 42 |
+
after a crash.
|
| 43 |
+
|
| 44 |
+
Joblib addresses these problems while **leaving your code and your flow
|
| 45 |
+
control as unmodified as possible** (no framework, no new paradigms).
|
| 46 |
+
|
| 47 |
+
Main features
|
| 48 |
+
------------------
|
| 49 |
+
|
| 50 |
+
1) **Transparent and fast disk-caching of output value:** a memoize or
|
| 51 |
+
make-like functionality for Python functions that works well for
|
| 52 |
+
arbitrary Python objects, including very large numpy arrays. Separate
|
| 53 |
+
persistence and flow-execution logic from domain logic or algorithmic
|
| 54 |
+
code by writing the operations as a set of steps with well-defined
|
| 55 |
+
inputs and outputs: Python functions. Joblib can save their
|
| 56 |
+
computation to disk and rerun it only if necessary::
|
| 57 |
+
|
| 58 |
+
>>> from joblib import Memory
|
| 59 |
+
>>> cachedir = 'your_cache_dir_goes_here'
|
| 60 |
+
>>> mem = Memory(cachedir)
|
| 61 |
+
>>> import numpy as np
|
| 62 |
+
>>> a = np.vander(np.arange(3)).astype(float)
|
| 63 |
+
>>> square = mem.cache(np.square)
|
| 64 |
+
>>> b = square(a) # doctest: +ELLIPSIS
|
| 65 |
+
________________________________________________________________________________
|
| 66 |
+
[Memory] Calling square...
|
| 67 |
+
square(array([[0., 0., 1.],
|
| 68 |
+
[1., 1., 1.],
|
| 69 |
+
[4., 2., 1.]]))
|
| 70 |
+
___________________________________________________________square - 0...s, 0.0min
|
| 71 |
+
|
| 72 |
+
>>> c = square(a)
|
| 73 |
+
>>> # The above call did not trigger an evaluation
|
| 74 |
+
|
| 75 |
+
2) **Embarrassingly parallel helper:** to make it easy to write readable
|
| 76 |
+
parallel code and debug it quickly::
|
| 77 |
+
|
| 78 |
+
>>> from joblib import Parallel, delayed
|
| 79 |
+
>>> from math import sqrt
|
| 80 |
+
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
|
| 81 |
+
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
3) **Fast compressed Persistence**: a replacement for pickle to work
|
| 85 |
+
efficiently on Python objects containing large data (
|
| 86 |
+
*joblib.dump* & *joblib.load* ).
|
| 87 |
+
|
| 88 |
+
..
|
| 89 |
+
>>> import shutil ; shutil.rmtree(cachedir)
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
# PEP0440 compatible formatted version, see:
|
| 94 |
+
# https://www.python.org/dev/peps/pep-0440/
|
| 95 |
+
#
|
| 96 |
+
# Generic release markers:
|
| 97 |
+
# X.Y
|
| 98 |
+
# X.Y.Z # For bugfix releases
|
| 99 |
+
#
|
| 100 |
+
# Admissible pre-release markers:
|
| 101 |
+
# X.YaN # Alpha release
|
| 102 |
+
# X.YbN # Beta release
|
| 103 |
+
# X.YrcN # Release Candidate
|
| 104 |
+
# X.Y # Final release
|
| 105 |
+
#
|
| 106 |
+
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
|
| 107 |
+
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
|
| 108 |
+
#
|
| 109 |
+
__version__ = '1.2.0'
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
import os
|
| 113 |
+
from .memory import Memory, MemorizedResult, register_store_backend
|
| 114 |
+
from .logger import PrintTime
|
| 115 |
+
from .logger import Logger
|
| 116 |
+
from .hashing import hash
|
| 117 |
+
from .numpy_pickle import dump
|
| 118 |
+
from .numpy_pickle import load
|
| 119 |
+
from .compressor import register_compressor
|
| 120 |
+
from .parallel import Parallel
|
| 121 |
+
from .parallel import delayed
|
| 122 |
+
from .parallel import cpu_count
|
| 123 |
+
from .parallel import register_parallel_backend
|
| 124 |
+
from .parallel import parallel_backend
|
| 125 |
+
from .parallel import effective_n_jobs
|
| 126 |
+
from ._cloudpickle_wrapper import wrap_non_picklable_objects
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
__all__ = ['Memory', 'MemorizedResult', 'PrintTime', 'Logger', 'hash', 'dump',
|
| 130 |
+
'load', 'Parallel', 'delayed', 'cpu_count', 'effective_n_jobs',
|
| 131 |
+
'register_parallel_backend', 'parallel_backend',
|
| 132 |
+
'register_store_backend', 'register_compressor',
|
| 133 |
+
'wrap_non_picklable_objects']
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# Workaround issue discovered in intel-openmp 2019.5:
|
| 137 |
+
# https://github.com/ContinuumIO/anaconda-issues/issues/11294
|
| 138 |
+
os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE")
|
runtime/Lib/site-packages/joblib/_cloudpickle_wrapper.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Small shim of loky's cloudpickle_wrapper to avoid failure when
|
| 3 |
+
multiprocessing is not available.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from ._multiprocessing_helpers import mp
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def my_wrap_non_picklable_objects(obj, keep_wrapper=True):
|
| 11 |
+
return obj
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
if mp is None:
|
| 15 |
+
wrap_non_picklable_objects = my_wrap_non_picklable_objects
|
| 16 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import print_function, division, absolute_import
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
import contextlib
|
| 6 |
+
|
| 7 |
+
import time
|
| 8 |
+
from uuid import uuid4
|
| 9 |
+
import weakref
|
| 10 |
+
|
| 11 |
+
from .parallel import AutoBatchingMixin, ParallelBackendBase, BatchedCalls
|
| 12 |
+
from .parallel import parallel_backend
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import dask
|
| 16 |
+
import distributed
|
| 17 |
+
except ImportError:
|
| 18 |
+
dask = None
|
| 19 |
+
distributed = None
|
| 20 |
+
|
| 21 |
+
if dask is not None and distributed is not None:
|
| 22 |
+
from dask.utils import funcname, itemgetter
|
| 23 |
+
from dask.sizeof import sizeof
|
| 24 |
+
from dask.distributed import (
|
| 25 |
+
Client,
|
| 26 |
+
as_completed,
|
| 27 |
+
get_client,
|
| 28 |
+
secede,
|
| 29 |
+
rejoin,
|
| 30 |
+
get_worker
|
| 31 |
+
)
|
| 32 |
+
from distributed.utils import thread_state
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
# asyncio.TimeoutError, Python3-only error thrown by recent versions of
|
| 37 |
+
# distributed
|
| 38 |
+
from distributed.utils import TimeoutError as _TimeoutError
|
| 39 |
+
except ImportError:
|
| 40 |
+
from tornado.gen import TimeoutError as _TimeoutError
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def is_weakrefable(obj):
|
| 44 |
+
try:
|
| 45 |
+
weakref.ref(obj)
|
| 46 |
+
return True
|
| 47 |
+
except TypeError:
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _WeakKeyDictionary:
|
| 52 |
+
"""A variant of weakref.WeakKeyDictionary for unhashable objects.
|
| 53 |
+
|
| 54 |
+
This datastructure is used to store futures for broadcasted data objects
|
| 55 |
+
such as large numpy arrays or pandas dataframes that are not hashable and
|
| 56 |
+
therefore cannot be used as keys of traditional python dicts.
|
| 57 |
+
|
| 58 |
+
Furthermore using a dict with id(array) as key is not safe because the
|
| 59 |
+
Python is likely to reuse id of recently collected arrays.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self):
|
| 63 |
+
self._data = {}
|
| 64 |
+
|
| 65 |
+
def __getitem__(self, obj):
|
| 66 |
+
ref, val = self._data[id(obj)]
|
| 67 |
+
if ref() is not obj:
|
| 68 |
+
# In case of a race condition with on_destroy.
|
| 69 |
+
raise KeyError(obj)
|
| 70 |
+
return val
|
| 71 |
+
|
| 72 |
+
def __setitem__(self, obj, value):
|
| 73 |
+
key = id(obj)
|
| 74 |
+
try:
|
| 75 |
+
ref, _ = self._data[key]
|
| 76 |
+
if ref() is not obj:
|
| 77 |
+
# In case of race condition with on_destroy.
|
| 78 |
+
raise KeyError(obj)
|
| 79 |
+
except KeyError:
|
| 80 |
+
# Insert the new entry in the mapping along with a weakref
|
| 81 |
+
# callback to automatically delete the entry from the mapping
|
| 82 |
+
# as soon as the object used as key is garbage collected.
|
| 83 |
+
def on_destroy(_):
|
| 84 |
+
del self._data[key]
|
| 85 |
+
ref = weakref.ref(obj, on_destroy)
|
| 86 |
+
self._data[key] = ref, value
|
| 87 |
+
|
| 88 |
+
def __len__(self):
|
| 89 |
+
return len(self._data)
|
| 90 |
+
|
| 91 |
+
def clear(self):
|
| 92 |
+
self._data.clear()
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _funcname(x):
|
| 96 |
+
try:
|
| 97 |
+
if isinstance(x, list):
|
| 98 |
+
x = x[0][0]
|
| 99 |
+
except Exception:
|
| 100 |
+
pass
|
| 101 |
+
return funcname(x)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _make_tasks_summary(tasks):
|
| 105 |
+
"""Summarize of list of (func, args, kwargs) function calls"""
|
| 106 |
+
unique_funcs = {func for func, args, kwargs in tasks}
|
| 107 |
+
|
| 108 |
+
if len(unique_funcs) == 1:
|
| 109 |
+
mixed = False
|
| 110 |
+
else:
|
| 111 |
+
mixed = True
|
| 112 |
+
return len(tasks), mixed, _funcname(tasks)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class Batch:
|
| 116 |
+
"""dask-compatible wrapper that executes a batch of tasks"""
|
| 117 |
+
def __init__(self, tasks):
|
| 118 |
+
# collect some metadata from the tasks to ease Batch calls
|
| 119 |
+
# introspection when debugging
|
| 120 |
+
self._num_tasks, self._mixed, self._funcname = _make_tasks_summary(
|
| 121 |
+
tasks
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def __call__(self, tasks=None):
|
| 125 |
+
results = []
|
| 126 |
+
with parallel_backend('dask'):
|
| 127 |
+
for func, args, kwargs in tasks:
|
| 128 |
+
results.append(func(*args, **kwargs))
|
| 129 |
+
return results
|
| 130 |
+
|
| 131 |
+
def __repr__(self):
|
| 132 |
+
descr = f"batch_of_{self._funcname}_{self._num_tasks}_calls"
|
| 133 |
+
if self._mixed:
|
| 134 |
+
descr = "mixed_" + descr
|
| 135 |
+
return descr
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _joblib_probe_task():
|
| 139 |
+
# Noop used by the joblib connector to probe when workers are ready.
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class DaskDistributedBackend(AutoBatchingMixin, ParallelBackendBase):
|
| 144 |
+
MIN_IDEAL_BATCH_DURATION = 0.2
|
| 145 |
+
MAX_IDEAL_BATCH_DURATION = 1.0
|
| 146 |
+
supports_timeout = True
|
| 147 |
+
|
| 148 |
+
def __init__(self, scheduler_host=None, scatter=None,
|
| 149 |
+
client=None, loop=None, wait_for_workers_timeout=10,
|
| 150 |
+
**submit_kwargs):
|
| 151 |
+
super().__init__()
|
| 152 |
+
|
| 153 |
+
if distributed is None:
|
| 154 |
+
msg = ("You are trying to use 'dask' as a joblib parallel backend "
|
| 155 |
+
"but dask is not installed. Please install dask "
|
| 156 |
+
"to fix this error.")
|
| 157 |
+
raise ValueError(msg)
|
| 158 |
+
|
| 159 |
+
if client is None:
|
| 160 |
+
if scheduler_host:
|
| 161 |
+
client = Client(scheduler_host, loop=loop,
|
| 162 |
+
set_as_default=False)
|
| 163 |
+
else:
|
| 164 |
+
try:
|
| 165 |
+
client = get_client()
|
| 166 |
+
except ValueError as e:
|
| 167 |
+
msg = ("To use Joblib with Dask first create a Dask Client"
|
| 168 |
+
"\n\n"
|
| 169 |
+
" from dask.distributed import Client\n"
|
| 170 |
+
" client = Client()\n"
|
| 171 |
+
"or\n"
|
| 172 |
+
" client = Client('scheduler-address:8786')")
|
| 173 |
+
raise ValueError(msg) from e
|
| 174 |
+
|
| 175 |
+
self.client = client
|
| 176 |
+
|
| 177 |
+
if scatter is not None and not isinstance(scatter, (list, tuple)):
|
| 178 |
+
raise TypeError("scatter must be a list/tuple, got "
|
| 179 |
+
"`%s`" % type(scatter).__name__)
|
| 180 |
+
|
| 181 |
+
if scatter is not None and len(scatter) > 0:
|
| 182 |
+
# Keep a reference to the scattered data to keep the ids the same
|
| 183 |
+
self._scatter = list(scatter)
|
| 184 |
+
scattered = self.client.scatter(scatter, broadcast=True)
|
| 185 |
+
self.data_futures = {id(x): f for x, f in zip(scatter, scattered)}
|
| 186 |
+
else:
|
| 187 |
+
self._scatter = []
|
| 188 |
+
self.data_futures = {}
|
| 189 |
+
self.wait_for_workers_timeout = wait_for_workers_timeout
|
| 190 |
+
self.submit_kwargs = submit_kwargs
|
| 191 |
+
self.waiting_futures = as_completed(
|
| 192 |
+
[],
|
| 193 |
+
loop=client.loop,
|
| 194 |
+
with_results=True,
|
| 195 |
+
raise_errors=False
|
| 196 |
+
)
|
| 197 |
+
self._results = {}
|
| 198 |
+
self._callbacks = {}
|
| 199 |
+
|
| 200 |
+
async def _collect(self):
|
| 201 |
+
while self._continue:
|
| 202 |
+
async for future, result in self.waiting_futures:
|
| 203 |
+
cf_future = self._results.pop(future)
|
| 204 |
+
callback = self._callbacks.pop(future)
|
| 205 |
+
if future.status == "error":
|
| 206 |
+
typ, exc, tb = result
|
| 207 |
+
cf_future.set_exception(exc)
|
| 208 |
+
else:
|
| 209 |
+
cf_future.set_result(result)
|
| 210 |
+
callback(result)
|
| 211 |
+
await asyncio.sleep(0.01)
|
| 212 |
+
|
| 213 |
+
def __reduce__(self):
|
| 214 |
+
return (DaskDistributedBackend, ())
|
| 215 |
+
|
| 216 |
+
def get_nested_backend(self):
|
| 217 |
+
return DaskDistributedBackend(client=self.client), -1
|
| 218 |
+
|
| 219 |
+
def configure(self, n_jobs=1, parallel=None, **backend_args):
|
| 220 |
+
self.parallel = parallel
|
| 221 |
+
return self.effective_n_jobs(n_jobs)
|
| 222 |
+
|
| 223 |
+
def start_call(self):
|
| 224 |
+
self._continue = True
|
| 225 |
+
self.client.loop.add_callback(self._collect)
|
| 226 |
+
self.call_data_futures = _WeakKeyDictionary()
|
| 227 |
+
|
| 228 |
+
def stop_call(self):
|
| 229 |
+
# The explicit call to clear is required to break a cycling reference
|
| 230 |
+
# to the futures.
|
| 231 |
+
self._continue = False
|
| 232 |
+
# wait for the future collection routine (self._backend._collect) to
|
| 233 |
+
# finish in order to limit asyncio warnings due to aborting _collect
|
| 234 |
+
# during a following backend termination call
|
| 235 |
+
time.sleep(0.01)
|
| 236 |
+
self.call_data_futures.clear()
|
| 237 |
+
|
| 238 |
+
def effective_n_jobs(self, n_jobs):
|
| 239 |
+
effective_n_jobs = sum(self.client.ncores().values())
|
| 240 |
+
if effective_n_jobs != 0 or not self.wait_for_workers_timeout:
|
| 241 |
+
return effective_n_jobs
|
| 242 |
+
|
| 243 |
+
# If there is no worker, schedule a probe task to wait for the workers
|
| 244 |
+
# to come up and be available. If the dask cluster is in adaptive mode
|
| 245 |
+
# task might cause the cluster to provision some workers.
|
| 246 |
+
try:
|
| 247 |
+
self.client.submit(_joblib_probe_task).result(
|
| 248 |
+
timeout=self.wait_for_workers_timeout)
|
| 249 |
+
except _TimeoutError as e:
|
| 250 |
+
error_msg = (
|
| 251 |
+
"DaskDistributedBackend has no worker after {} seconds. "
|
| 252 |
+
"Make sure that workers are started and can properly connect "
|
| 253 |
+
"to the scheduler and increase the joblib/dask connection "
|
| 254 |
+
"timeout with:\n\n"
|
| 255 |
+
"parallel_backend('dask', wait_for_workers_timeout={})"
|
| 256 |
+
).format(self.wait_for_workers_timeout,
|
| 257 |
+
max(10, 2 * self.wait_for_workers_timeout))
|
| 258 |
+
raise TimeoutError(error_msg) from e
|
| 259 |
+
return sum(self.client.ncores().values())
|
| 260 |
+
|
| 261 |
+
async def _to_func_args(self, func):
|
| 262 |
+
itemgetters = dict()
|
| 263 |
+
|
| 264 |
+
# Futures that are dynamically generated during a single call to
|
| 265 |
+
# Parallel.__call__.
|
| 266 |
+
call_data_futures = getattr(self, 'call_data_futures', None)
|
| 267 |
+
|
| 268 |
+
async def maybe_to_futures(args):
|
| 269 |
+
out = []
|
| 270 |
+
for arg in args:
|
| 271 |
+
arg_id = id(arg)
|
| 272 |
+
if arg_id in itemgetters:
|
| 273 |
+
out.append(itemgetters[arg_id])
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
f = self.data_futures.get(arg_id, None)
|
| 277 |
+
if f is None and call_data_futures is not None:
|
| 278 |
+
try:
|
| 279 |
+
f = await call_data_futures[arg]
|
| 280 |
+
except KeyError:
|
| 281 |
+
pass
|
| 282 |
+
if f is None:
|
| 283 |
+
if is_weakrefable(arg) and sizeof(arg) > 1e3:
|
| 284 |
+
# Automatically scatter large objects to some of
|
| 285 |
+
# the workers to avoid duplicated data transfers.
|
| 286 |
+
# Rely on automated inter-worker data stealing if
|
| 287 |
+
# more workers need to reuse this data
|
| 288 |
+
# concurrently.
|
| 289 |
+
# set hash=False - nested scatter calls (i.e
|
| 290 |
+
# calling client.scatter inside a dask worker)
|
| 291 |
+
# using hash=True often raise CancelledError,
|
| 292 |
+
# see dask/distributed#3703
|
| 293 |
+
_coro = self.client.scatter(
|
| 294 |
+
arg,
|
| 295 |
+
asynchronous=True,
|
| 296 |
+
hash=False
|
| 297 |
+
)
|
| 298 |
+
# Centralize the scattering of identical arguments
|
| 299 |
+
# between concurrent apply_async callbacks by
|
| 300 |
+
# exposing the running coroutine in
|
| 301 |
+
# call_data_futures before it completes.
|
| 302 |
+
t = asyncio.Task(_coro)
|
| 303 |
+
call_data_futures[arg] = t
|
| 304 |
+
|
| 305 |
+
f = await t
|
| 306 |
+
|
| 307 |
+
if f is not None:
|
| 308 |
+
out.append(f)
|
| 309 |
+
else:
|
| 310 |
+
out.append(arg)
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
tasks = []
|
| 314 |
+
for f, args, kwargs in func.items:
|
| 315 |
+
args = list(await maybe_to_futures(args))
|
| 316 |
+
kwargs = dict(zip(kwargs.keys(),
|
| 317 |
+
await maybe_to_futures(kwargs.values())))
|
| 318 |
+
tasks.append((f, args, kwargs))
|
| 319 |
+
|
| 320 |
+
return (Batch(tasks), tasks)
|
| 321 |
+
|
| 322 |
+
def apply_async(self, func, callback=None):
|
| 323 |
+
|
| 324 |
+
cf_future = concurrent.futures.Future()
|
| 325 |
+
cf_future.get = cf_future.result # achieve AsyncResult API
|
| 326 |
+
|
| 327 |
+
async def f(func, callback):
|
| 328 |
+
batch, tasks = await self._to_func_args(func)
|
| 329 |
+
key = f'{repr(batch)}-{uuid4().hex}'
|
| 330 |
+
|
| 331 |
+
dask_future = self.client.submit(
|
| 332 |
+
batch, tasks=tasks, key=key, **self.submit_kwargs
|
| 333 |
+
)
|
| 334 |
+
self.waiting_futures.add(dask_future)
|
| 335 |
+
self._callbacks[dask_future] = callback
|
| 336 |
+
self._results[dask_future] = cf_future
|
| 337 |
+
|
| 338 |
+
self.client.loop.add_callback(f, func, callback)
|
| 339 |
+
|
| 340 |
+
return cf_future
|
| 341 |
+
|
| 342 |
+
def abort_everything(self, ensure_ready=True):
|
| 343 |
+
""" Tell the client to cancel any task submitted via this instance
|
| 344 |
+
|
| 345 |
+
joblib.Parallel will never access those results
|
| 346 |
+
"""
|
| 347 |
+
with self.waiting_futures.lock:
|
| 348 |
+
self.waiting_futures.futures.clear()
|
| 349 |
+
while not self.waiting_futures.queue.empty():
|
| 350 |
+
self.waiting_futures.queue.get()
|
| 351 |
+
|
| 352 |
+
@contextlib.contextmanager
|
| 353 |
+
def retrieval_context(self):
|
| 354 |
+
"""Override ParallelBackendBase.retrieval_context to avoid deadlocks.
|
| 355 |
+
|
| 356 |
+
This removes thread from the worker's thread pool (using 'secede').
|
| 357 |
+
Seceding avoids deadlock in nested parallelism settings.
|
| 358 |
+
"""
|
| 359 |
+
# See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how
|
| 360 |
+
# this is used.
|
| 361 |
+
if hasattr(thread_state, 'execution_state'):
|
| 362 |
+
# we are in a worker. Secede to avoid deadlock.
|
| 363 |
+
secede()
|
| 364 |
+
|
| 365 |
+
yield
|
| 366 |
+
|
| 367 |
+
if hasattr(thread_state, 'execution_state'):
|
| 368 |
+
rejoin()
|
runtime/Lib/site-packages/joblib/_deprecated_format_stack.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Represent an exception with a lot of information.
|
| 3 |
+
|
| 4 |
+
Provides 2 useful functions:
|
| 5 |
+
|
| 6 |
+
format_exc: format an exception into a complete traceback, with full
|
| 7 |
+
debugging instruction.
|
| 8 |
+
|
| 9 |
+
format_outer_frames: format the current position in the stack call.
|
| 10 |
+
|
| 11 |
+
Adapted from IPython's VerboseTB.
|
| 12 |
+
"""
|
| 13 |
+
# Authors: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
|
| 14 |
+
# Nathaniel Gray <n8gray@caltech.edu>
|
| 15 |
+
# Fernando Perez <fperez@colorado.edu>
|
| 16 |
+
# Copyright: 2010, Gael Varoquaux
|
| 17 |
+
# 2001-2004, Fernando Perez
|
| 18 |
+
# 2001 Nathaniel Gray
|
| 19 |
+
# License: BSD 3 clause
|
| 20 |
+
# flake8: noqa
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
import inspect
|
| 24 |
+
import keyword
|
| 25 |
+
import linecache
|
| 26 |
+
import os
|
| 27 |
+
import pydoc
|
| 28 |
+
import sys
|
| 29 |
+
import time
|
| 30 |
+
import tokenize
|
| 31 |
+
import traceback
|
| 32 |
+
|
| 33 |
+
INDENT = ' ' * 8
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
###############################################################################
|
| 37 |
+
# some internal-use functions
|
| 38 |
+
def safe_repr(value):
|
| 39 |
+
"""Hopefully pretty robust repr equivalent."""
|
| 40 |
+
# this is pretty horrible but should always return *something*
|
| 41 |
+
try:
|
| 42 |
+
return pydoc.text.repr(value)
|
| 43 |
+
except KeyboardInterrupt:
|
| 44 |
+
raise
|
| 45 |
+
except:
|
| 46 |
+
try:
|
| 47 |
+
return repr(value)
|
| 48 |
+
except KeyboardInterrupt:
|
| 49 |
+
raise
|
| 50 |
+
except:
|
| 51 |
+
try:
|
| 52 |
+
# all still in an except block so we catch
|
| 53 |
+
# getattr raising
|
| 54 |
+
name = getattr(value, '__name__', None)
|
| 55 |
+
if name:
|
| 56 |
+
# ick, recursion
|
| 57 |
+
return safe_repr(name)
|
| 58 |
+
klass = getattr(value, '__class__', None)
|
| 59 |
+
if klass:
|
| 60 |
+
return '%s instance' % safe_repr(klass)
|
| 61 |
+
except KeyboardInterrupt:
|
| 62 |
+
raise
|
| 63 |
+
except:
|
| 64 |
+
return 'UNRECOVERABLE REPR FAILURE'
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def eq_repr(value, repr=safe_repr):
|
| 68 |
+
return '=%s' % repr(value)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
###############################################################################
|
| 72 |
+
def uniq_stable(elems):
|
| 73 |
+
"""uniq_stable(elems) -> list
|
| 74 |
+
|
| 75 |
+
Return from an iterable, a list of all the unique elements in the input,
|
| 76 |
+
but maintaining the order in which they first appear.
|
| 77 |
+
|
| 78 |
+
A naive solution to this problem which just makes a dictionary with the
|
| 79 |
+
elements as keys fails to respect the stability condition, since
|
| 80 |
+
dictionaries are unsorted by nature.
|
| 81 |
+
|
| 82 |
+
Note: All elements in the input must be hashable.
|
| 83 |
+
"""
|
| 84 |
+
unique = []
|
| 85 |
+
unique_set = set()
|
| 86 |
+
for nn in elems:
|
| 87 |
+
if nn not in unique_set:
|
| 88 |
+
unique.append(nn)
|
| 89 |
+
unique_set.add(nn)
|
| 90 |
+
return unique
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
###############################################################################
|
| 94 |
+
def fix_frame_records_filenames(records):
|
| 95 |
+
"""Try to fix the filenames in each record from inspect.getinnerframes().
|
| 96 |
+
|
| 97 |
+
Particularly, modules loaded from within zip files have useless filenames
|
| 98 |
+
attached to their code object, and inspect.getinnerframes() just uses it.
|
| 99 |
+
"""
|
| 100 |
+
fixed_records = []
|
| 101 |
+
for frame, filename, line_no, func_name, lines, index in records:
|
| 102 |
+
# Look inside the frame's globals dictionary for __file__, which should
|
| 103 |
+
# be better.
|
| 104 |
+
better_fn = frame.f_globals.get('__file__', None)
|
| 105 |
+
if isinstance(better_fn, str):
|
| 106 |
+
# Check the type just in case someone did something weird with
|
| 107 |
+
# __file__. It might also be None if the error occurred during
|
| 108 |
+
# import.
|
| 109 |
+
filename = better_fn
|
| 110 |
+
fixed_records.append((frame, filename, line_no, func_name, lines,
|
| 111 |
+
index))
|
| 112 |
+
return fixed_records
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _fixed_getframes(etb, context=1, tb_offset=0):
|
| 116 |
+
LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
|
| 117 |
+
|
| 118 |
+
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
|
| 119 |
+
|
| 120 |
+
# If the error is at the console, don't build any context, since it would
|
| 121 |
+
# otherwise produce 5 blank lines printed out (there is no file at the
|
| 122 |
+
# console)
|
| 123 |
+
rec_check = records[tb_offset:]
|
| 124 |
+
try:
|
| 125 |
+
rname = rec_check[0][1]
|
| 126 |
+
if rname == '<ipython console>' or rname.endswith('<string>'):
|
| 127 |
+
return rec_check
|
| 128 |
+
except IndexError:
|
| 129 |
+
pass
|
| 130 |
+
|
| 131 |
+
aux = traceback.extract_tb(etb)
|
| 132 |
+
assert len(records) == len(aux)
|
| 133 |
+
for i, (file, lnum, _, _) in enumerate(aux):
|
| 134 |
+
maybe_start = lnum - 1 - context // 2
|
| 135 |
+
start = max(maybe_start, 0)
|
| 136 |
+
end = start + context
|
| 137 |
+
lines = linecache.getlines(file)[start:end]
|
| 138 |
+
buf = list(records[i])
|
| 139 |
+
buf[LNUM_POS] = lnum
|
| 140 |
+
buf[INDEX_POS] = lnum - 1 - start
|
| 141 |
+
buf[LINES_POS] = lines
|
| 142 |
+
records[i] = tuple(buf)
|
| 143 |
+
return records[tb_offset:]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _format_traceback_lines(lnum, index, lines, lvals=None):
|
| 147 |
+
numbers_width = 7
|
| 148 |
+
res = []
|
| 149 |
+
i = lnum - index
|
| 150 |
+
|
| 151 |
+
for line in lines:
|
| 152 |
+
if i == lnum:
|
| 153 |
+
# This is the line with the error
|
| 154 |
+
pad = numbers_width - len(str(i))
|
| 155 |
+
if pad >= 3:
|
| 156 |
+
marker = '-' * (pad - 3) + '-> '
|
| 157 |
+
elif pad == 2:
|
| 158 |
+
marker = '> '
|
| 159 |
+
elif pad == 1:
|
| 160 |
+
marker = '>'
|
| 161 |
+
else:
|
| 162 |
+
marker = ''
|
| 163 |
+
num = marker + str(i)
|
| 164 |
+
else:
|
| 165 |
+
num = '%*s' % (numbers_width, i)
|
| 166 |
+
line = '%s %s' % (num, line)
|
| 167 |
+
|
| 168 |
+
res.append(line)
|
| 169 |
+
if lvals and i == lnum:
|
| 170 |
+
res.append(lvals + '\n')
|
| 171 |
+
i = i + 1
|
| 172 |
+
return res
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def format_records(records): # , print_globals=False):
|
| 176 |
+
# Loop over all records printing context and info
|
| 177 |
+
frames = []
|
| 178 |
+
abspath = os.path.abspath
|
| 179 |
+
for frame, file, lnum, func, lines, index in records:
|
| 180 |
+
try:
|
| 181 |
+
file = file and abspath(file) or '?'
|
| 182 |
+
except OSError:
|
| 183 |
+
# if file is '<console>' or something not in the filesystem,
|
| 184 |
+
# the abspath call will throw an OSError. Just ignore it and
|
| 185 |
+
# keep the original file string.
|
| 186 |
+
pass
|
| 187 |
+
|
| 188 |
+
if file.endswith('.pyc'):
|
| 189 |
+
file = file[:-4] + '.py'
|
| 190 |
+
|
| 191 |
+
link = file
|
| 192 |
+
|
| 193 |
+
args, varargs, varkw, locals = inspect.getargvalues(frame)
|
| 194 |
+
|
| 195 |
+
if func == '?':
|
| 196 |
+
call = ''
|
| 197 |
+
else:
|
| 198 |
+
# Decide whether to include variable details or not
|
| 199 |
+
try:
|
| 200 |
+
call = 'in %s%s' % (func, inspect.formatargvalues(args,
|
| 201 |
+
varargs, varkw, locals,
|
| 202 |
+
formatvalue=eq_repr))
|
| 203 |
+
except KeyError:
|
| 204 |
+
# Very odd crash from inspect.formatargvalues(). The
|
| 205 |
+
# scenario under which it appeared was a call to
|
| 206 |
+
# view(array,scale) in NumTut.view.view(), where scale had
|
| 207 |
+
# been defined as a scalar (it should be a tuple). Somehow
|
| 208 |
+
# inspect messes up resolving the argument list of view()
|
| 209 |
+
# and barfs out. At some point I should dig into this one
|
| 210 |
+
# and file a bug report about it.
|
| 211 |
+
print("\nJoblib's exception reporting continues...\n")
|
| 212 |
+
call = 'in %s(***failed resolving arguments***)' % func
|
| 213 |
+
|
| 214 |
+
# Initialize a list of names on the current line, which the
|
| 215 |
+
# tokenizer below will populate.
|
| 216 |
+
names = []
|
| 217 |
+
|
| 218 |
+
def tokeneater(token_type, token, start, end, line):
|
| 219 |
+
"""Stateful tokeneater which builds dotted names.
|
| 220 |
+
|
| 221 |
+
The list of names it appends to (from the enclosing scope) can
|
| 222 |
+
contain repeated composite names. This is unavoidable, since
|
| 223 |
+
there is no way to disambiguate partial dotted structures until
|
| 224 |
+
the full list is known. The caller is responsible for pruning
|
| 225 |
+
the final list of duplicates before using it."""
|
| 226 |
+
|
| 227 |
+
# build composite names
|
| 228 |
+
if token == '.':
|
| 229 |
+
try:
|
| 230 |
+
names[-1] += '.'
|
| 231 |
+
# store state so the next token is added for x.y.z names
|
| 232 |
+
tokeneater.name_cont = True
|
| 233 |
+
return
|
| 234 |
+
except IndexError:
|
| 235 |
+
pass
|
| 236 |
+
if token_type == tokenize.NAME and token not in keyword.kwlist:
|
| 237 |
+
if tokeneater.name_cont:
|
| 238 |
+
# Dotted names
|
| 239 |
+
names[-1] += token
|
| 240 |
+
tokeneater.name_cont = False
|
| 241 |
+
else:
|
| 242 |
+
# Regular new names. We append everything, the caller
|
| 243 |
+
# will be responsible for pruning the list later. It's
|
| 244 |
+
# very tricky to try to prune as we go, b/c composite
|
| 245 |
+
# names can fool us. The pruning at the end is easy
|
| 246 |
+
# to do (or the caller can print a list with repeated
|
| 247 |
+
# names if so desired.
|
| 248 |
+
names.append(token)
|
| 249 |
+
elif token_type == tokenize.NEWLINE:
|
| 250 |
+
raise IndexError
|
| 251 |
+
# we need to store a bit of state in the tokenizer to build
|
| 252 |
+
# dotted names
|
| 253 |
+
tokeneater.name_cont = False
|
| 254 |
+
|
| 255 |
+
def linereader(file=file, lnum=[lnum], getline=linecache.getline):
|
| 256 |
+
line = getline(file, lnum[0])
|
| 257 |
+
lnum[0] += 1
|
| 258 |
+
return line
|
| 259 |
+
|
| 260 |
+
# Build the list of names on this line of code where the exception
|
| 261 |
+
# occurred.
|
| 262 |
+
try:
|
| 263 |
+
# This builds the names list in-place by capturing it from the
|
| 264 |
+
# enclosing scope.
|
| 265 |
+
for token in tokenize.generate_tokens(linereader):
|
| 266 |
+
tokeneater(*token)
|
| 267 |
+
except (IndexError, UnicodeDecodeError, SyntaxError):
|
| 268 |
+
# signals exit of tokenizer
|
| 269 |
+
# SyntaxError can happen when trying to tokenize
|
| 270 |
+
# a compiled (e.g. .so or .pyd) extension
|
| 271 |
+
pass
|
| 272 |
+
except tokenize.TokenError as msg:
|
| 273 |
+
_m = ("An unexpected error occurred while tokenizing input file %s\n"
|
| 274 |
+
"The following traceback may be corrupted or invalid\n"
|
| 275 |
+
"The error message is: %s\n" % (file, msg))
|
| 276 |
+
print(_m)
|
| 277 |
+
|
| 278 |
+
# prune names list of duplicates, but keep the right order
|
| 279 |
+
unique_names = uniq_stable(names)
|
| 280 |
+
|
| 281 |
+
# Start loop over vars
|
| 282 |
+
lvals = []
|
| 283 |
+
for name_full in unique_names:
|
| 284 |
+
name_base = name_full.split('.', 1)[0]
|
| 285 |
+
if name_base in frame.f_code.co_varnames:
|
| 286 |
+
if name_base in locals.keys():
|
| 287 |
+
try:
|
| 288 |
+
value = safe_repr(eval(name_full, locals))
|
| 289 |
+
except:
|
| 290 |
+
value = "undefined"
|
| 291 |
+
else:
|
| 292 |
+
value = "undefined"
|
| 293 |
+
name = name_full
|
| 294 |
+
lvals.append('%s = %s' % (name, value))
|
| 295 |
+
#elif print_globals:
|
| 296 |
+
# if frame.f_globals.has_key(name_base):
|
| 297 |
+
# try:
|
| 298 |
+
# value = safe_repr(eval(name_full,frame.f_globals))
|
| 299 |
+
# except:
|
| 300 |
+
# value = "undefined"
|
| 301 |
+
# else:
|
| 302 |
+
# value = "undefined"
|
| 303 |
+
# name = 'global %s' % name_full
|
| 304 |
+
# lvals.append('%s = %s' % (name,value))
|
| 305 |
+
if lvals:
|
| 306 |
+
lvals = '%s%s' % (INDENT, ('\n%s' % INDENT).join(lvals))
|
| 307 |
+
else:
|
| 308 |
+
lvals = ''
|
| 309 |
+
|
| 310 |
+
level = '%s\n%s %s\n' % (75 * '.', link, call)
|
| 311 |
+
|
| 312 |
+
if index is None:
|
| 313 |
+
frames.append(level)
|
| 314 |
+
else:
|
| 315 |
+
frames.append('%s%s' % (level, ''.join(
|
| 316 |
+
_format_traceback_lines(lnum, index, lines, lvals))))
|
| 317 |
+
|
| 318 |
+
return frames
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
###############################################################################
|
| 322 |
+
def format_exc(etype, evalue, etb, context=5, tb_offset=0):
|
| 323 |
+
""" Return a nice text document describing the traceback.
|
| 324 |
+
|
| 325 |
+
Parameters
|
| 326 |
+
-----------
|
| 327 |
+
etype, evalue, etb: as returned by sys.exc_info
|
| 328 |
+
context: number of lines of the source file to plot
|
| 329 |
+
tb_offset: the number of stack frame not to use (0 = use all)
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
# some locals
|
| 333 |
+
try:
|
| 334 |
+
etype = etype.__name__
|
| 335 |
+
except AttributeError:
|
| 336 |
+
pass
|
| 337 |
+
|
| 338 |
+
# Header with the exception type, python version, and date
|
| 339 |
+
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
|
| 340 |
+
date = time.ctime(time.time())
|
| 341 |
+
pid = 'PID: %i' % os.getpid()
|
| 342 |
+
|
| 343 |
+
head = '%s%s%s\n%s%s%s' % (
|
| 344 |
+
etype, ' ' * (75 - len(str(etype)) - len(date)),
|
| 345 |
+
date, pid, ' ' * (75 - len(str(pid)) - len(pyver)),
|
| 346 |
+
pyver)
|
| 347 |
+
|
| 348 |
+
# Drop topmost frames if requested
|
| 349 |
+
records = _fixed_getframes(etb, context, tb_offset)
|
| 350 |
+
|
| 351 |
+
# Get (safely) a string form of the exception info
|
| 352 |
+
try:
|
| 353 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 354 |
+
except BaseException:
|
| 355 |
+
# User exception is improperly defined.
|
| 356 |
+
etype, evalue = str, sys.exc_info()[:2]
|
| 357 |
+
etype_str, evalue_str = map(str, (etype, evalue))
|
| 358 |
+
# ... and format it
|
| 359 |
+
exception = ['%s: %s' % (etype_str, evalue_str)]
|
| 360 |
+
frames = format_records(records)
|
| 361 |
+
return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
###############################################################################
|
| 365 |
+
def format_outer_frames(context=5, stack_start=None, stack_end=None,
|
| 366 |
+
ignore_ipython=True):
|
| 367 |
+
LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
|
| 368 |
+
records = inspect.getouterframes(inspect.currentframe())
|
| 369 |
+
output = list()
|
| 370 |
+
|
| 371 |
+
for i, (frame, filename, line_no, func_name, lines, index) \
|
| 372 |
+
in enumerate(records):
|
| 373 |
+
# Look inside the frame's globals dictionary for __file__, which should
|
| 374 |
+
# be better.
|
| 375 |
+
better_fn = frame.f_globals.get('__file__', None)
|
| 376 |
+
if isinstance(better_fn, str):
|
| 377 |
+
# Check the type just in case someone did something weird with
|
| 378 |
+
# __file__. It might also be None if the error occurred during
|
| 379 |
+
# import.
|
| 380 |
+
filename = better_fn
|
| 381 |
+
if filename.endswith('.pyc'):
|
| 382 |
+
filename = filename[:-4] + '.py'
|
| 383 |
+
if ignore_ipython:
|
| 384 |
+
# Hack to avoid printing the internals of IPython
|
| 385 |
+
if (os.path.basename(filename) in ('iplib.py', 'py3compat.py')
|
| 386 |
+
and func_name in ('execfile', 'safe_execfile', 'runcode')):
|
| 387 |
+
break
|
| 388 |
+
maybe_start = line_no - 1 - context // 2
|
| 389 |
+
start = max(maybe_start, 0)
|
| 390 |
+
end = start + context
|
| 391 |
+
lines = linecache.getlines(filename)[start:end]
|
| 392 |
+
buf = list(records[i])
|
| 393 |
+
buf[LNUM_POS] = line_no
|
| 394 |
+
buf[INDEX_POS] = line_no - 1 - start
|
| 395 |
+
buf[LINES_POS] = lines
|
| 396 |
+
output.append(tuple(buf))
|
| 397 |
+
return '\n'.join(format_records(output[stack_end:stack_start:-1]))
|
runtime/Lib/site-packages/joblib/_deprecated_my_exceptions.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Exceptions
|
| 3 |
+
|
| 4 |
+
This module is deprecated and will be removed in joblib 0.16.
|
| 5 |
+
"""
|
| 6 |
+
# Author: Gael Varoquaux < gael dot varoquaux at normalesup dot org >
|
| 7 |
+
# Copyright: 2010, Gael Varoquaux
|
| 8 |
+
# License: BSD 3 clause
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class JoblibException(Exception):
|
| 12 |
+
"""A simple exception with an error message that you can get to."""
|
| 13 |
+
def __init__(self, *args):
|
| 14 |
+
# We need to implement __init__ so that it is picked in the
|
| 15 |
+
# multiple heritance hierarchy in the class created in
|
| 16 |
+
# _mk_exception. Note: in Python 2, if you implement __init__
|
| 17 |
+
# in your exception class you need to set .args correctly,
|
| 18 |
+
# otherwise you can dump an exception instance with pickle but
|
| 19 |
+
# not load it (at load time an empty .args will be passed to
|
| 20 |
+
# the constructor). Also we want to be explicit and not use
|
| 21 |
+
# 'super' here. Using 'super' can cause a sibling class method
|
| 22 |
+
# to be called and we have no control the sibling class method
|
| 23 |
+
# constructor signature in the exception returned by
|
| 24 |
+
# _mk_exception.
|
| 25 |
+
Exception.__init__(self, *args)
|
| 26 |
+
|
| 27 |
+
def __repr__(self):
|
| 28 |
+
if hasattr(self, 'args') and len(self.args) > 0:
|
| 29 |
+
message = self.args[0]
|
| 30 |
+
else:
|
| 31 |
+
message = ''
|
| 32 |
+
|
| 33 |
+
name = self.__class__.__name__
|
| 34 |
+
return '%s\n%s\n%s\n%s' % (name, 75 * '_', message, 75 * '_')
|
| 35 |
+
|
| 36 |
+
__str__ = __repr__
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TransportableException(JoblibException):
|
| 40 |
+
"""An exception containing all the info to wrap an original
|
| 41 |
+
exception and recreate it.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, message, etype):
|
| 45 |
+
# The next line set the .args correctly. This is needed to
|
| 46 |
+
# make the exception loadable with pickle
|
| 47 |
+
JoblibException.__init__(self, message, etype)
|
| 48 |
+
self.message = message
|
| 49 |
+
self.etype = etype
|
| 50 |
+
|
| 51 |
+
def unwrap(self, context_message=""):
|
| 52 |
+
report = """\
|
| 53 |
+
%s
|
| 54 |
+
---------------------------------------------------------------------------
|
| 55 |
+
Joblib worker traceback:
|
| 56 |
+
---------------------------------------------------------------------------
|
| 57 |
+
%s""" % (context_message, self.message)
|
| 58 |
+
# Unwrap the exception to a JoblibException
|
| 59 |
+
exception_type = _mk_exception(self.etype)[0]
|
| 60 |
+
return exception_type(report)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
_exception_mapping = dict()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _mk_exception(exception, name=None):
|
| 67 |
+
if issubclass(exception, JoblibException):
|
| 68 |
+
# No need to wrap recursively JoblibException
|
| 69 |
+
return exception, exception.__name__
|
| 70 |
+
|
| 71 |
+
# Create an exception inheriting from both JoblibException
|
| 72 |
+
# and that exception
|
| 73 |
+
if name is None:
|
| 74 |
+
name = exception.__name__
|
| 75 |
+
this_name = 'Joblib%s' % name
|
| 76 |
+
if this_name in _exception_mapping:
|
| 77 |
+
# Avoid creating twice the same exception
|
| 78 |
+
this_exception = _exception_mapping[this_name]
|
| 79 |
+
else:
|
| 80 |
+
if exception is Exception:
|
| 81 |
+
# JoblibException is already a subclass of Exception. No
|
| 82 |
+
# need to use multiple inheritance
|
| 83 |
+
return JoblibException, this_name
|
| 84 |
+
try:
|
| 85 |
+
this_exception = type(
|
| 86 |
+
this_name, (JoblibException, exception), {})
|
| 87 |
+
_exception_mapping[this_name] = this_exception
|
| 88 |
+
except TypeError:
|
| 89 |
+
# This happens if "Cannot create a consistent method
|
| 90 |
+
# resolution order", e.g. because 'exception' is a
|
| 91 |
+
# subclass of JoblibException or 'exception' is not an
|
| 92 |
+
# acceptable base class
|
| 93 |
+
this_exception = JoblibException
|
| 94 |
+
|
| 95 |
+
return this_exception, this_name
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _mk_common_exceptions():
|
| 99 |
+
namespace = dict()
|
| 100 |
+
import builtins as _builtin_exceptions
|
| 101 |
+
common_exceptions = filter(
|
| 102 |
+
lambda x: x.endswith('Error'),
|
| 103 |
+
dir(_builtin_exceptions))
|
| 104 |
+
|
| 105 |
+
for name in common_exceptions:
|
| 106 |
+
obj = getattr(_builtin_exceptions, name)
|
| 107 |
+
if isinstance(obj, type) and issubclass(obj, BaseException):
|
| 108 |
+
this_obj, this_name = _mk_exception(obj, name=name)
|
| 109 |
+
namespace[this_name] = this_obj
|
| 110 |
+
return namespace
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Updating module locals so that the exceptions pickle right. AFAIK this
|
| 114 |
+
# works only at module-creation time
|
| 115 |
+
locals().update(_mk_common_exceptions())
|
runtime/Lib/site-packages/joblib/_memmapping_reducer.py
ADDED
|
@@ -0,0 +1,668 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Reducer using memory mapping for numpy arrays
|
| 3 |
+
"""
|
| 4 |
+
# Author: Thomas Moreau <thomas.moreau.2010@gmail.com>
|
| 5 |
+
# Copyright: 2017, Thomas Moreau
|
| 6 |
+
# License: BSD 3 clause
|
| 7 |
+
|
| 8 |
+
from mmap import mmap
|
| 9 |
+
import errno
|
| 10 |
+
import os
|
| 11 |
+
import stat
|
| 12 |
+
import threading
|
| 13 |
+
import atexit
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
import warnings
|
| 17 |
+
import weakref
|
| 18 |
+
from uuid import uuid4
|
| 19 |
+
from multiprocessing import util
|
| 20 |
+
|
| 21 |
+
from pickle import whichmodule, loads, dumps, HIGHEST_PROTOCOL, PicklingError
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
WindowsError
|
| 25 |
+
except NameError:
|
| 26 |
+
WindowsError = type(None)
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
import numpy as np
|
| 30 |
+
from numpy.lib.stride_tricks import as_strided
|
| 31 |
+
except ImportError:
|
| 32 |
+
np = None
|
| 33 |
+
|
| 34 |
+
from .numpy_pickle import dump, load, load_temporary_memmap
|
| 35 |
+
from .backports import make_memmap
|
| 36 |
+
from .disk import delete_folder
|
| 37 |
+
from .externals.loky.backend import resource_tracker
|
| 38 |
+
|
| 39 |
+
# Some system have a ramdisk mounted by default, we can use it instead of /tmp
|
| 40 |
+
# as the default folder to dump big arrays to share with subprocesses.
|
| 41 |
+
SYSTEM_SHARED_MEM_FS = '/dev/shm'
|
| 42 |
+
|
| 43 |
+
# Minimal number of bytes available on SYSTEM_SHARED_MEM_FS to consider using
|
| 44 |
+
# it as the default folder to dump big arrays to share with subprocesses.
|
| 45 |
+
SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(2e9)
|
| 46 |
+
|
| 47 |
+
# Folder and file permissions to chmod temporary files generated by the
|
| 48 |
+
# memmapping pool. Only the owner of the Python process can access the
|
| 49 |
+
# temporary files and folder.
|
| 50 |
+
FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
|
| 51 |
+
FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR
|
| 52 |
+
|
| 53 |
+
# Set used in joblib workers, referencing the filenames of temporary memmaps
|
| 54 |
+
# created by joblib to speed up data communication. In child processes, we add
|
| 55 |
+
# a finalizer to these memmaps that sends a maybe_unlink call to the
|
| 56 |
+
# resource_tracker, in order to free main memory as fast as possible.
|
| 57 |
+
JOBLIB_MMAPS = set()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _log_and_unlink(filename):
|
| 61 |
+
from .externals.loky.backend.resource_tracker import _resource_tracker
|
| 62 |
+
util.debug(
|
| 63 |
+
"[FINALIZER CALL] object mapping to {} about to be deleted,"
|
| 64 |
+
" decrementing the refcount of the file (pid: {})".format(
|
| 65 |
+
os.path.basename(filename), os.getpid()))
|
| 66 |
+
_resource_tracker.maybe_unlink(filename, "file")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def add_maybe_unlink_finalizer(memmap):
|
| 70 |
+
util.debug(
|
| 71 |
+
"[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})"
|
| 72 |
+
"".format(type(memmap), id(memmap), os.path.basename(memmap.filename),
|
| 73 |
+
os.getpid()))
|
| 74 |
+
weakref.finalize(memmap, _log_and_unlink, memmap.filename)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def unlink_file(filename):
|
| 78 |
+
"""Wrapper around os.unlink with a retry mechanism.
|
| 79 |
+
|
| 80 |
+
The retry mechanism has been implemented primarily to overcome a race
|
| 81 |
+
condition happening during the finalizer of a np.memmap: when a process
|
| 82 |
+
holding the last reference to a mmap-backed np.memmap/np.array is about to
|
| 83 |
+
delete this array (and close the reference), it sends a maybe_unlink
|
| 84 |
+
request to the resource_tracker. This request can be processed faster than
|
| 85 |
+
it takes for the last reference of the memmap to be closed, yielding (on
|
| 86 |
+
Windows) a PermissionError in the resource_tracker loop.
|
| 87 |
+
"""
|
| 88 |
+
NUM_RETRIES = 10
|
| 89 |
+
for retry_no in range(1, NUM_RETRIES + 1):
|
| 90 |
+
try:
|
| 91 |
+
os.unlink(filename)
|
| 92 |
+
break
|
| 93 |
+
except PermissionError:
|
| 94 |
+
util.debug(
|
| 95 |
+
'[ResourceTracker] tried to unlink {}, got '
|
| 96 |
+
'PermissionError'.format(filename)
|
| 97 |
+
)
|
| 98 |
+
if retry_no == NUM_RETRIES:
|
| 99 |
+
raise
|
| 100 |
+
else:
|
| 101 |
+
time.sleep(.2)
|
| 102 |
+
except FileNotFoundError:
|
| 103 |
+
# In case of a race condition when deleting the temporary folder,
|
| 104 |
+
# avoid noisy FileNotFoundError exception in the resource tracker.
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
resource_tracker._CLEANUP_FUNCS['file'] = unlink_file
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class _WeakArrayKeyMap:
|
| 112 |
+
"""A variant of weakref.WeakKeyDictionary for unhashable numpy arrays.
|
| 113 |
+
|
| 114 |
+
This datastructure will be used with numpy arrays as obj keys, therefore we
|
| 115 |
+
do not use the __get__ / __set__ methods to avoid any conflict with the
|
| 116 |
+
numpy fancy indexing syntax.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self):
|
| 120 |
+
self._data = {}
|
| 121 |
+
|
| 122 |
+
def get(self, obj):
|
| 123 |
+
ref, val = self._data[id(obj)]
|
| 124 |
+
if ref() is not obj:
|
| 125 |
+
# In case of race condition with on_destroy: could never be
|
| 126 |
+
# triggered by the joblib tests with CPython.
|
| 127 |
+
raise KeyError(obj)
|
| 128 |
+
return val
|
| 129 |
+
|
| 130 |
+
def set(self, obj, value):
|
| 131 |
+
key = id(obj)
|
| 132 |
+
try:
|
| 133 |
+
ref, _ = self._data[key]
|
| 134 |
+
if ref() is not obj:
|
| 135 |
+
# In case of race condition with on_destroy: could never be
|
| 136 |
+
# triggered by the joblib tests with CPython.
|
| 137 |
+
raise KeyError(obj)
|
| 138 |
+
except KeyError:
|
| 139 |
+
# Insert the new entry in the mapping along with a weakref
|
| 140 |
+
# callback to automatically delete the entry from the mapping
|
| 141 |
+
# as soon as the object used as key is garbage collected.
|
| 142 |
+
def on_destroy(_):
|
| 143 |
+
del self._data[key]
|
| 144 |
+
ref = weakref.ref(obj, on_destroy)
|
| 145 |
+
self._data[key] = ref, value
|
| 146 |
+
|
| 147 |
+
def __getstate__(self):
|
| 148 |
+
raise PicklingError("_WeakArrayKeyMap is not pickleable")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
###############################################################################
|
| 152 |
+
# Support for efficient transient pickling of numpy data structures
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _get_backing_memmap(a):
|
| 156 |
+
"""Recursively look up the original np.memmap instance base if any."""
|
| 157 |
+
b = getattr(a, 'base', None)
|
| 158 |
+
if b is None:
|
| 159 |
+
# TODO: check scipy sparse datastructure if scipy is installed
|
| 160 |
+
# a nor its descendants do not have a memmap base
|
| 161 |
+
return None
|
| 162 |
+
|
| 163 |
+
elif isinstance(b, mmap):
|
| 164 |
+
# a is already a real memmap instance.
|
| 165 |
+
return a
|
| 166 |
+
|
| 167 |
+
else:
|
| 168 |
+
# Recursive exploration of the base ancestry
|
| 169 |
+
return _get_backing_memmap(b)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _get_temp_dir(pool_folder_name, temp_folder=None):
|
| 173 |
+
"""Get the full path to a subfolder inside the temporary folder.
|
| 174 |
+
|
| 175 |
+
Parameters
|
| 176 |
+
----------
|
| 177 |
+
pool_folder_name : str
|
| 178 |
+
Sub-folder name used for the serialization of a pool instance.
|
| 179 |
+
|
| 180 |
+
temp_folder: str, optional
|
| 181 |
+
Folder to be used by the pool for memmapping large arrays
|
| 182 |
+
for sharing memory with worker processes. If None, this will try in
|
| 183 |
+
order:
|
| 184 |
+
|
| 185 |
+
- a folder pointed by the JOBLIB_TEMP_FOLDER environment
|
| 186 |
+
variable,
|
| 187 |
+
- /dev/shm if the folder exists and is writable: this is a
|
| 188 |
+
RAMdisk filesystem available by default on modern Linux
|
| 189 |
+
distributions,
|
| 190 |
+
- the default system temporary folder that can be
|
| 191 |
+
overridden with TMP, TMPDIR or TEMP environment
|
| 192 |
+
variables, typically /tmp under Unix operating systems.
|
| 193 |
+
|
| 194 |
+
Returns
|
| 195 |
+
-------
|
| 196 |
+
pool_folder : str
|
| 197 |
+
full path to the temporary folder
|
| 198 |
+
use_shared_mem : bool
|
| 199 |
+
whether the temporary folder is written to the system shared memory
|
| 200 |
+
folder or some other temporary folder.
|
| 201 |
+
"""
|
| 202 |
+
use_shared_mem = False
|
| 203 |
+
if temp_folder is None:
|
| 204 |
+
temp_folder = os.environ.get('JOBLIB_TEMP_FOLDER', None)
|
| 205 |
+
if temp_folder is None:
|
| 206 |
+
if os.path.exists(SYSTEM_SHARED_MEM_FS):
|
| 207 |
+
try:
|
| 208 |
+
shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS)
|
| 209 |
+
available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail
|
| 210 |
+
if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE:
|
| 211 |
+
# Try to see if we have write access to the shared mem
|
| 212 |
+
# folder only if it is reasonably large (that is 2GB or
|
| 213 |
+
# more).
|
| 214 |
+
temp_folder = SYSTEM_SHARED_MEM_FS
|
| 215 |
+
pool_folder = os.path.join(temp_folder, pool_folder_name)
|
| 216 |
+
if not os.path.exists(pool_folder):
|
| 217 |
+
os.makedirs(pool_folder)
|
| 218 |
+
use_shared_mem = True
|
| 219 |
+
except (IOError, OSError):
|
| 220 |
+
# Missing rights in the /dev/shm partition, fallback to regular
|
| 221 |
+
# temp folder.
|
| 222 |
+
temp_folder = None
|
| 223 |
+
if temp_folder is None:
|
| 224 |
+
# Fallback to the default tmp folder, typically /tmp
|
| 225 |
+
temp_folder = tempfile.gettempdir()
|
| 226 |
+
temp_folder = os.path.abspath(os.path.expanduser(temp_folder))
|
| 227 |
+
pool_folder = os.path.join(temp_folder, pool_folder_name)
|
| 228 |
+
return pool_folder, use_shared_mem
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def has_shareable_memory(a):
|
| 232 |
+
"""Return True if a is backed by some mmap buffer directly or not."""
|
| 233 |
+
return _get_backing_memmap(a) is not None
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _strided_from_memmap(filename, dtype, mode, offset, order, shape, strides,
|
| 237 |
+
total_buffer_len, unlink_on_gc_collect):
|
| 238 |
+
"""Reconstruct an array view on a memory mapped file."""
|
| 239 |
+
if mode == 'w+':
|
| 240 |
+
# Do not zero the original data when unpickling
|
| 241 |
+
mode = 'r+'
|
| 242 |
+
|
| 243 |
+
if strides is None:
|
| 244 |
+
# Simple, contiguous memmap
|
| 245 |
+
return make_memmap(
|
| 246 |
+
filename, dtype=dtype, shape=shape, mode=mode, offset=offset,
|
| 247 |
+
order=order, unlink_on_gc_collect=unlink_on_gc_collect
|
| 248 |
+
)
|
| 249 |
+
else:
|
| 250 |
+
# For non-contiguous data, memmap the total enclosing buffer and then
|
| 251 |
+
# extract the non-contiguous view with the stride-tricks API
|
| 252 |
+
base = make_memmap(
|
| 253 |
+
filename, dtype=dtype, shape=total_buffer_len, offset=offset,
|
| 254 |
+
mode=mode, order=order, unlink_on_gc_collect=unlink_on_gc_collect
|
| 255 |
+
)
|
| 256 |
+
return as_strided(base, shape=shape, strides=strides)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _reduce_memmap_backed(a, m):
|
| 260 |
+
"""Pickling reduction for memmap backed arrays.
|
| 261 |
+
|
| 262 |
+
a is expected to be an instance of np.ndarray (or np.memmap)
|
| 263 |
+
m is expected to be an instance of np.memmap on the top of the ``base``
|
| 264 |
+
attribute ancestry of a. ``m.base`` should be the real python mmap object.
|
| 265 |
+
"""
|
| 266 |
+
# offset that comes from the striding differences between a and m
|
| 267 |
+
util.debug('[MEMMAP REDUCE] reducing a memmap-backed array '
|
| 268 |
+
'(shape, {}, pid: {})'.format(a.shape, os.getpid()))
|
| 269 |
+
a_start, a_end = np.byte_bounds(a)
|
| 270 |
+
m_start = np.byte_bounds(m)[0]
|
| 271 |
+
offset = a_start - m_start
|
| 272 |
+
|
| 273 |
+
# offset from the backing memmap
|
| 274 |
+
offset += m.offset
|
| 275 |
+
|
| 276 |
+
if m.flags['F_CONTIGUOUS']:
|
| 277 |
+
order = 'F'
|
| 278 |
+
else:
|
| 279 |
+
# The backing memmap buffer is necessarily contiguous hence C if not
|
| 280 |
+
# Fortran
|
| 281 |
+
order = 'C'
|
| 282 |
+
|
| 283 |
+
if a.flags['F_CONTIGUOUS'] or a.flags['C_CONTIGUOUS']:
|
| 284 |
+
# If the array is a contiguous view, no need to pass the strides
|
| 285 |
+
strides = None
|
| 286 |
+
total_buffer_len = None
|
| 287 |
+
else:
|
| 288 |
+
# Compute the total number of items to map from which the strided
|
| 289 |
+
# view will be extracted.
|
| 290 |
+
strides = a.strides
|
| 291 |
+
total_buffer_len = (a_end - a_start) // a.itemsize
|
| 292 |
+
|
| 293 |
+
return (_strided_from_memmap,
|
| 294 |
+
(m.filename, a.dtype, m.mode, offset, order, a.shape, strides,
|
| 295 |
+
total_buffer_len, False))
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def reduce_array_memmap_backward(a):
|
| 299 |
+
"""reduce a np.array or a np.memmap from a child process"""
|
| 300 |
+
m = _get_backing_memmap(a)
|
| 301 |
+
if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS:
|
| 302 |
+
# if a is backed by a memmaped file, reconstruct a using the
|
| 303 |
+
# memmaped file.
|
| 304 |
+
return _reduce_memmap_backed(a, m)
|
| 305 |
+
else:
|
| 306 |
+
# a is either a regular (not memmap-backed) numpy array, or an array
|
| 307 |
+
# backed by a shared temporary file created by joblib. In the latter
|
| 308 |
+
# case, in order to limit the lifespan of these temporary files, we
|
| 309 |
+
# serialize the memmap as a regular numpy array, and decref the
|
| 310 |
+
# file backing the memmap (done implicitly in a previously registered
|
| 311 |
+
# finalizer, see ``unlink_on_gc_collect`` for more details)
|
| 312 |
+
return (
|
| 313 |
+
loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL), )
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class ArrayMemmapForwardReducer(object):
|
| 318 |
+
"""Reducer callable to dump large arrays to memmap files.
|
| 319 |
+
|
| 320 |
+
Parameters
|
| 321 |
+
----------
|
| 322 |
+
max_nbytes: int
|
| 323 |
+
Threshold to trigger memmapping of large arrays to files created
|
| 324 |
+
a folder.
|
| 325 |
+
temp_folder_resolver: callable
|
| 326 |
+
An callable in charge of resolving a temporary folder name where files
|
| 327 |
+
for backing memmapped arrays are created.
|
| 328 |
+
mmap_mode: 'r', 'r+' or 'c'
|
| 329 |
+
Mode for the created memmap datastructure. See the documentation of
|
| 330 |
+
numpy.memmap for more details. Note: 'w+' is coerced to 'r+'
|
| 331 |
+
automatically to avoid zeroing the data on unpickling.
|
| 332 |
+
verbose: int, optional, 0 by default
|
| 333 |
+
If verbose > 0, memmap creations are logged.
|
| 334 |
+
If verbose > 1, both memmap creations, reuse and array pickling are
|
| 335 |
+
logged.
|
| 336 |
+
prewarm: bool, optional, False by default.
|
| 337 |
+
Force a read on newly memmapped array to make sure that OS pre-cache it
|
| 338 |
+
memory. This can be useful to avoid concurrent disk access when the
|
| 339 |
+
same data array is passed to different worker processes.
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
def __init__(self, max_nbytes, temp_folder_resolver, mmap_mode,
|
| 343 |
+
unlink_on_gc_collect, verbose=0, prewarm=True):
|
| 344 |
+
self._max_nbytes = max_nbytes
|
| 345 |
+
self._temp_folder_resolver = temp_folder_resolver
|
| 346 |
+
self._mmap_mode = mmap_mode
|
| 347 |
+
self.verbose = int(verbose)
|
| 348 |
+
if prewarm == "auto":
|
| 349 |
+
self._prewarm = not self._temp_folder.startswith(
|
| 350 |
+
SYSTEM_SHARED_MEM_FS
|
| 351 |
+
)
|
| 352 |
+
else:
|
| 353 |
+
self._prewarm = prewarm
|
| 354 |
+
self._prewarm = prewarm
|
| 355 |
+
self._memmaped_arrays = _WeakArrayKeyMap()
|
| 356 |
+
self._temporary_memmaped_filenames = set()
|
| 357 |
+
self._unlink_on_gc_collect = unlink_on_gc_collect
|
| 358 |
+
|
| 359 |
+
@property
|
| 360 |
+
def _temp_folder(self):
|
| 361 |
+
return self._temp_folder_resolver()
|
| 362 |
+
|
| 363 |
+
def __reduce__(self):
|
| 364 |
+
# The ArrayMemmapForwardReducer is passed to the children processes: it
|
| 365 |
+
# needs to be pickled but the _WeakArrayKeyMap need to be skipped as
|
| 366 |
+
# it's only guaranteed to be consistent with the parent process memory
|
| 367 |
+
# garbage collection.
|
| 368 |
+
# Although this reducer is pickled, it is not needed in its destination
|
| 369 |
+
# process (child processes), as we only use this reducer to send
|
| 370 |
+
# memmaps from the parent process to the children processes. For this
|
| 371 |
+
# reason, we can afford skipping the resolver, (which would otherwise
|
| 372 |
+
# be unpicklable), and pass it as None instead.
|
| 373 |
+
args = (self._max_nbytes, None, self._mmap_mode,
|
| 374 |
+
self._unlink_on_gc_collect)
|
| 375 |
+
kwargs = {
|
| 376 |
+
'verbose': self.verbose,
|
| 377 |
+
'prewarm': self._prewarm,
|
| 378 |
+
}
|
| 379 |
+
return ArrayMemmapForwardReducer, args, kwargs
|
| 380 |
+
|
| 381 |
+
def __call__(self, a):
|
| 382 |
+
m = _get_backing_memmap(a)
|
| 383 |
+
if m is not None and isinstance(m, np.memmap):
|
| 384 |
+
# a is already backed by a memmap file, let's reuse it directly
|
| 385 |
+
return _reduce_memmap_backed(a, m)
|
| 386 |
+
|
| 387 |
+
if (not a.dtype.hasobject and self._max_nbytes is not None and
|
| 388 |
+
a.nbytes > self._max_nbytes):
|
| 389 |
+
# check that the folder exists (lazily create the pool temp folder
|
| 390 |
+
# if required)
|
| 391 |
+
try:
|
| 392 |
+
os.makedirs(self._temp_folder)
|
| 393 |
+
os.chmod(self._temp_folder, FOLDER_PERMISSIONS)
|
| 394 |
+
except OSError as e:
|
| 395 |
+
if e.errno != errno.EEXIST:
|
| 396 |
+
raise e
|
| 397 |
+
|
| 398 |
+
try:
|
| 399 |
+
basename = self._memmaped_arrays.get(a)
|
| 400 |
+
except KeyError:
|
| 401 |
+
# Generate a new unique random filename. The process and thread
|
| 402 |
+
# ids are only useful for debugging purpose and to make it
|
| 403 |
+
# easier to cleanup orphaned files in case of hard process
|
| 404 |
+
# kill (e.g. by "kill -9" or segfault).
|
| 405 |
+
basename = "{}-{}-{}.pkl".format(
|
| 406 |
+
os.getpid(), id(threading.current_thread()), uuid4().hex)
|
| 407 |
+
self._memmaped_arrays.set(a, basename)
|
| 408 |
+
filename = os.path.join(self._temp_folder, basename)
|
| 409 |
+
|
| 410 |
+
# In case the same array with the same content is passed several
|
| 411 |
+
# times to the pool subprocess children, serialize it only once
|
| 412 |
+
|
| 413 |
+
is_new_memmap = filename not in self._temporary_memmaped_filenames
|
| 414 |
+
|
| 415 |
+
# add the memmap to the list of temporary memmaps created by joblib
|
| 416 |
+
self._temporary_memmaped_filenames.add(filename)
|
| 417 |
+
|
| 418 |
+
if self._unlink_on_gc_collect:
|
| 419 |
+
# Bump reference count of the memmap by 1 to account for
|
| 420 |
+
# shared usage of the memmap by a child process. The
|
| 421 |
+
# corresponding decref call will be executed upon calling
|
| 422 |
+
# resource_tracker.maybe_unlink, registered as a finalizer in
|
| 423 |
+
# the child.
|
| 424 |
+
# the incref/decref calls here are only possible when the child
|
| 425 |
+
# and the parent share the same resource_tracker. It is not the
|
| 426 |
+
# case for the multiprocessing backend, but it does not matter
|
| 427 |
+
# because unlinking a memmap from a child process is only
|
| 428 |
+
# useful to control the memory usage of long-lasting child
|
| 429 |
+
# processes, while the multiprocessing-based pools terminate
|
| 430 |
+
# their workers at the end of a map() call.
|
| 431 |
+
resource_tracker.register(filename, "file")
|
| 432 |
+
|
| 433 |
+
if is_new_memmap:
|
| 434 |
+
# Incref each temporary memmap created by joblib one extra
|
| 435 |
+
# time. This means that these memmaps will only be deleted
|
| 436 |
+
# once an extra maybe_unlink() is called, which is done once
|
| 437 |
+
# all the jobs have completed (or been canceled) in the
|
| 438 |
+
# Parallel._terminate_backend() method.
|
| 439 |
+
resource_tracker.register(filename, "file")
|
| 440 |
+
|
| 441 |
+
if not os.path.exists(filename):
|
| 442 |
+
util.debug(
|
| 443 |
+
"[ARRAY DUMP] Pickling new array (shape={}, dtype={}) "
|
| 444 |
+
"creating a new memmap at {}".format(
|
| 445 |
+
a.shape, a.dtype, filename))
|
| 446 |
+
for dumped_filename in dump(a, filename):
|
| 447 |
+
os.chmod(dumped_filename, FILE_PERMISSIONS)
|
| 448 |
+
|
| 449 |
+
if self._prewarm:
|
| 450 |
+
# Warm up the data by accessing it. This operation ensures
|
| 451 |
+
# that the disk access required to create the memmapping
|
| 452 |
+
# file are performed in the reducing process and avoids
|
| 453 |
+
# concurrent memmap creation in multiple children
|
| 454 |
+
# processes.
|
| 455 |
+
load(filename, mmap_mode=self._mmap_mode).max()
|
| 456 |
+
|
| 457 |
+
else:
|
| 458 |
+
util.debug(
|
| 459 |
+
"[ARRAY DUMP] Pickling known array (shape={}, dtype={}) "
|
| 460 |
+
"reusing memmap file: {}".format(
|
| 461 |
+
a.shape, a.dtype, os.path.basename(filename)))
|
| 462 |
+
|
| 463 |
+
# The worker process will use joblib.load to memmap the data
|
| 464 |
+
return (
|
| 465 |
+
(load_temporary_memmap, (filename, self._mmap_mode,
|
| 466 |
+
self._unlink_on_gc_collect))
|
| 467 |
+
)
|
| 468 |
+
else:
|
| 469 |
+
# do not convert a into memmap, let pickler do its usual copy with
|
| 470 |
+
# the default system pickler
|
| 471 |
+
util.debug(
|
| 472 |
+
'[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={}, '
|
| 473 |
+
' dtype={}).'.format(a.shape, a.dtype))
|
| 474 |
+
return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),))
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def get_memmapping_reducers(
|
| 478 |
+
forward_reducers=None, backward_reducers=None,
|
| 479 |
+
temp_folder_resolver=None, max_nbytes=1e6, mmap_mode='r', verbose=0,
|
| 480 |
+
prewarm=False, unlink_on_gc_collect=True, **kwargs):
|
| 481 |
+
"""Construct a pair of memmapping reducer linked to a tmpdir.
|
| 482 |
+
|
| 483 |
+
This function manage the creation and the clean up of the temporary folders
|
| 484 |
+
underlying the memory maps and should be use to get the reducers necessary
|
| 485 |
+
to construct joblib pool or executor.
|
| 486 |
+
"""
|
| 487 |
+
if forward_reducers is None:
|
| 488 |
+
forward_reducers = dict()
|
| 489 |
+
if backward_reducers is None:
|
| 490 |
+
backward_reducers = dict()
|
| 491 |
+
|
| 492 |
+
if np is not None:
|
| 493 |
+
# Register smart numpy.ndarray reducers that detects memmap backed
|
| 494 |
+
# arrays and that is also able to dump to memmap large in-memory
|
| 495 |
+
# arrays over the max_nbytes threshold
|
| 496 |
+
forward_reduce_ndarray = ArrayMemmapForwardReducer(
|
| 497 |
+
max_nbytes, temp_folder_resolver, mmap_mode, unlink_on_gc_collect,
|
| 498 |
+
verbose, prewarm=prewarm)
|
| 499 |
+
forward_reducers[np.ndarray] = forward_reduce_ndarray
|
| 500 |
+
forward_reducers[np.memmap] = forward_reduce_ndarray
|
| 501 |
+
|
| 502 |
+
# Communication from child process to the parent process always
|
| 503 |
+
# pickles in-memory numpy.ndarray without dumping them as memmap
|
| 504 |
+
# to avoid confusing the caller and make it tricky to collect the
|
| 505 |
+
# temporary folder
|
| 506 |
+
backward_reducers[np.ndarray] = reduce_array_memmap_backward
|
| 507 |
+
backward_reducers[np.memmap] = reduce_array_memmap_backward
|
| 508 |
+
|
| 509 |
+
return forward_reducers, backward_reducers
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
class TemporaryResourcesManager(object):
|
| 513 |
+
"""Stateful object able to manage temporary folder and pickles
|
| 514 |
+
|
| 515 |
+
It exposes:
|
| 516 |
+
- a per-context folder name resolving API that memmap-based reducers will
|
| 517 |
+
rely on to know where to pickle the temporary memmaps
|
| 518 |
+
- a temporary file/folder management API that internally uses the
|
| 519 |
+
resource_tracker.
|
| 520 |
+
"""
|
| 521 |
+
|
| 522 |
+
def __init__(self, temp_folder_root=None, context_id=None):
|
| 523 |
+
self._current_temp_folder = None
|
| 524 |
+
self._temp_folder_root = temp_folder_root
|
| 525 |
+
self._use_shared_mem = None
|
| 526 |
+
self._cached_temp_folders = dict()
|
| 527 |
+
self._id = uuid4().hex
|
| 528 |
+
self._finalizers = {}
|
| 529 |
+
if context_id is None:
|
| 530 |
+
# It would be safer to not assign a default context id (less silent
|
| 531 |
+
# bugs), but doing this while maintaining backward compatibility
|
| 532 |
+
# with the previous, context-unaware version get_memmaping_executor
|
| 533 |
+
# exposes exposes too many low-level details.
|
| 534 |
+
context_id = uuid4().hex
|
| 535 |
+
self.set_current_context(context_id)
|
| 536 |
+
|
| 537 |
+
def set_current_context(self, context_id):
|
| 538 |
+
self._current_context_id = context_id
|
| 539 |
+
self.register_new_context(context_id)
|
| 540 |
+
|
| 541 |
+
def register_new_context(self, context_id):
|
| 542 |
+
# Prepare a sub-folder name specific to a context (usually a unique id
|
| 543 |
+
# generated by each instance of the Parallel class). Do not create in
|
| 544 |
+
# advance to spare FS write access if no array is to be dumped).
|
| 545 |
+
if context_id in self._cached_temp_folders:
|
| 546 |
+
return
|
| 547 |
+
else:
|
| 548 |
+
# During its lifecycle, one Parallel object can have several
|
| 549 |
+
# executors associated to it (for instance, if a loky worker raises
|
| 550 |
+
# an exception, joblib shutdowns the executor and instantly
|
| 551 |
+
# recreates a new one before raising the error - see
|
| 552 |
+
# ``ensure_ready``. Because we don't want two executors tied to
|
| 553 |
+
# the same Parallel object (and thus the same context id) to
|
| 554 |
+
# register/use/delete the same folder, we also add an id specific
|
| 555 |
+
# to the current Manager (and thus specific to its associated
|
| 556 |
+
# executor) to the folder name.
|
| 557 |
+
new_folder_name = (
|
| 558 |
+
"joblib_memmapping_folder_{}_{}_{}".format(
|
| 559 |
+
os.getpid(), self._id, context_id)
|
| 560 |
+
)
|
| 561 |
+
new_folder_path, _ = _get_temp_dir(
|
| 562 |
+
new_folder_name, self._temp_folder_root
|
| 563 |
+
)
|
| 564 |
+
self.register_folder_finalizer(new_folder_path, context_id)
|
| 565 |
+
self._cached_temp_folders[context_id] = new_folder_path
|
| 566 |
+
|
| 567 |
+
def resolve_temp_folder_name(self):
|
| 568 |
+
"""Return a folder name specific to the currently activated context"""
|
| 569 |
+
return self._cached_temp_folders[self._current_context_id]
|
| 570 |
+
|
| 571 |
+
def _unregister_context(self, context_id=None):
|
| 572 |
+
if context_id is None:
|
| 573 |
+
for context_id in list(self._cached_temp_folders):
|
| 574 |
+
self._unregister_context(context_id)
|
| 575 |
+
else:
|
| 576 |
+
temp_folder = self._cached_temp_folders[context_id]
|
| 577 |
+
finalizer = self._finalizers[context_id]
|
| 578 |
+
|
| 579 |
+
resource_tracker.unregister(temp_folder, "folder")
|
| 580 |
+
atexit.unregister(finalizer)
|
| 581 |
+
|
| 582 |
+
self._cached_temp_folders.pop(context_id)
|
| 583 |
+
self._finalizers.pop(context_id)
|
| 584 |
+
|
| 585 |
+
# resource management API
|
| 586 |
+
|
| 587 |
+
def register_folder_finalizer(self, pool_subfolder, context_id):
|
| 588 |
+
# Register the garbage collector at program exit in case caller forgets
|
| 589 |
+
# to call terminate explicitly: note we do not pass any reference to
|
| 590 |
+
# ensure that this callback won't prevent garbage collection of
|
| 591 |
+
# parallel instance and related file handler resources such as POSIX
|
| 592 |
+
# semaphores and pipes
|
| 593 |
+
pool_module_name = whichmodule(delete_folder, 'delete_folder')
|
| 594 |
+
resource_tracker.register(pool_subfolder, "folder")
|
| 595 |
+
|
| 596 |
+
def _cleanup():
|
| 597 |
+
# In some cases the Python runtime seems to set delete_folder to
|
| 598 |
+
# None just before exiting when accessing the delete_folder
|
| 599 |
+
# function from the closure namespace. So instead we reimport
|
| 600 |
+
# the delete_folder function explicitly.
|
| 601 |
+
# https://github.com/joblib/joblib/issues/328
|
| 602 |
+
# We cannot just use from 'joblib.pool import delete_folder'
|
| 603 |
+
# because joblib should only use relative imports to allow
|
| 604 |
+
# easy vendoring.
|
| 605 |
+
delete_folder = __import__(
|
| 606 |
+
pool_module_name, fromlist=['delete_folder']).delete_folder
|
| 607 |
+
try:
|
| 608 |
+
delete_folder(pool_subfolder, allow_non_empty=True)
|
| 609 |
+
resource_tracker.unregister(pool_subfolder, "folder")
|
| 610 |
+
except OSError:
|
| 611 |
+
warnings.warn("Failed to delete temporary folder: {}"
|
| 612 |
+
.format(pool_subfolder))
|
| 613 |
+
|
| 614 |
+
self._finalizers[context_id] = atexit.register(_cleanup)
|
| 615 |
+
|
| 616 |
+
def _unlink_temporary_resources(self, context_id=None):
|
| 617 |
+
"""Unlink temporary resources created by a process-based pool"""
|
| 618 |
+
if context_id is None:
|
| 619 |
+
# iterate over a copy of the cache keys because
|
| 620 |
+
# unlink_temporary_resources further deletes an entry in this
|
| 621 |
+
# cache
|
| 622 |
+
for context_id in self._cached_temp_folders.copy():
|
| 623 |
+
self._unlink_temporary_resources(context_id)
|
| 624 |
+
else:
|
| 625 |
+
temp_folder = self._cached_temp_folders[context_id]
|
| 626 |
+
if os.path.exists(temp_folder):
|
| 627 |
+
for filename in os.listdir(temp_folder):
|
| 628 |
+
resource_tracker.maybe_unlink(
|
| 629 |
+
os.path.join(temp_folder, filename), "file"
|
| 630 |
+
)
|
| 631 |
+
self._try_delete_folder(
|
| 632 |
+
allow_non_empty=False, context_id=context_id
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
def _unregister_temporary_resources(self, context_id=None):
|
| 636 |
+
"""Unregister temporary resources created by a process-based pool"""
|
| 637 |
+
if context_id is None:
|
| 638 |
+
for context_id in self._cached_temp_folders:
|
| 639 |
+
self._unregister_temporary_resources(context_id)
|
| 640 |
+
else:
|
| 641 |
+
temp_folder = self._cached_temp_folders[context_id]
|
| 642 |
+
if os.path.exists(temp_folder):
|
| 643 |
+
for filename in os.listdir(temp_folder):
|
| 644 |
+
resource_tracker.unregister(
|
| 645 |
+
os.path.join(temp_folder, filename), "file"
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
def _try_delete_folder(self, allow_non_empty, context_id=None):
|
| 649 |
+
if context_id is None:
|
| 650 |
+
# ditto
|
| 651 |
+
for context_id in self._cached_temp_folders.copy():
|
| 652 |
+
self._try_delete_folder(
|
| 653 |
+
allow_non_empty=allow_non_empty, context_id=context_id
|
| 654 |
+
)
|
| 655 |
+
else:
|
| 656 |
+
temp_folder = self._cached_temp_folders[context_id]
|
| 657 |
+
try:
|
| 658 |
+
delete_folder(
|
| 659 |
+
temp_folder, allow_non_empty=allow_non_empty
|
| 660 |
+
)
|
| 661 |
+
# Now that this folder is deleted, we can forget about it
|
| 662 |
+
self._unregister_context(context_id)
|
| 663 |
+
|
| 664 |
+
except OSError:
|
| 665 |
+
# Temporary folder cannot be deleted right now. No need to
|
| 666 |
+
# handle it though, as this folder will be cleaned up by an
|
| 667 |
+
# atexit finalizer registered by the memmapping_reducer.
|
| 668 |
+
pass
|
runtime/Lib/site-packages/joblib/_multiprocessing_helpers.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper module to factorize the conditional multiprocessing import logic
|
| 2 |
+
|
| 3 |
+
We use a distinct module to simplify import statements and avoid introducing
|
| 4 |
+
circular dependencies (for instance for the assert_spawning name).
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# Obtain possible configuration from the environment, assuming 1 (on)
|
| 11 |
+
# by default, upon 0 set to None. Should instructively fail if some non
|
| 12 |
+
# 0/1 value is set.
|
| 13 |
+
mp = int(os.environ.get('JOBLIB_MULTIPROCESSING', 1)) or None
|
| 14 |
+
if mp:
|
| 15 |
+
try:
|
| 16 |
+
import multiprocessing as mp
|
| 17 |
+
import _multiprocessing # noqa
|
| 18 |
+
except ImportError:
|
| 19 |
+
mp = None
|
| 20 |
+
|
| 21 |
+
# 2nd stage: validate that locking is available on the system and
|
| 22 |
+
# issue a warning if not
|
| 23 |
+
if mp is not None:
|
| 24 |
+
try:
|
| 25 |
+
# try to create a named semaphore using SemLock to make sure they are
|
| 26 |
+
# available on this platform. We use the low level object
|
| 27 |
+
# _multiprocessing.SemLock to avoid spawning a resource tracker on
|
| 28 |
+
# Unix system or changing the default backend.
|
| 29 |
+
import tempfile
|
| 30 |
+
from _multiprocessing import SemLock
|
| 31 |
+
|
| 32 |
+
_rand = tempfile._RandomNameSequence()
|
| 33 |
+
for i in range(100):
|
| 34 |
+
try:
|
| 35 |
+
name = '/joblib-{}-{}' .format(
|
| 36 |
+
os.getpid(), next(_rand))
|
| 37 |
+
_sem = SemLock(0, 0, 1, name=name, unlink=True)
|
| 38 |
+
del _sem # cleanup
|
| 39 |
+
break
|
| 40 |
+
except FileExistsError as e: # pragma: no cover
|
| 41 |
+
if i >= 99:
|
| 42 |
+
raise FileExistsError(
|
| 43 |
+
'cannot find name for semaphore') from e
|
| 44 |
+
except (FileExistsError, AttributeError, ImportError, OSError) as e:
|
| 45 |
+
mp = None
|
| 46 |
+
warnings.warn('%s. joblib will operate in serial mode' % (e,))
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# 3rd stage: backward compat for the assert_spawning helper
|
| 50 |
+
if mp is not None:
|
| 51 |
+
from multiprocessing.context import assert_spawning
|
| 52 |
+
else:
|
| 53 |
+
assert_spawning = None
|
runtime/Lib/site-packages/joblib/_parallel_backends.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Backends for embarrassingly parallel code.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import gc
|
| 6 |
+
import os
|
| 7 |
+
import warnings
|
| 8 |
+
import threading
|
| 9 |
+
import functools
|
| 10 |
+
import contextlib
|
| 11 |
+
from abc import ABCMeta, abstractmethod
|
| 12 |
+
|
| 13 |
+
from .my_exceptions import WorkerInterrupt
|
| 14 |
+
from ._multiprocessing_helpers import mp
|
| 15 |
+
|
| 16 |
+
if mp is not None:
|
| 17 |
+
from .pool import MemmappingPool
|
| 18 |
+
from multiprocessing.pool import ThreadPool
|
| 19 |
+
from .executor import get_memmapping_executor
|
| 20 |
+
|
| 21 |
+
# Compat between concurrent.futures and multiprocessing TimeoutError
|
| 22 |
+
from multiprocessing import TimeoutError
|
| 23 |
+
from concurrent.futures._base import TimeoutError as CfTimeoutError
|
| 24 |
+
from .externals.loky import process_executor, cpu_count
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ParallelBackendBase(metaclass=ABCMeta):
|
| 28 |
+
"""Helper abc which defines all methods a ParallelBackend must implement"""
|
| 29 |
+
|
| 30 |
+
supports_timeout = False
|
| 31 |
+
supports_inner_max_num_threads = False
|
| 32 |
+
nesting_level = None
|
| 33 |
+
|
| 34 |
+
def __init__(self, nesting_level=None, inner_max_num_threads=None,
|
| 35 |
+
**kwargs):
|
| 36 |
+
super().__init__(**kwargs)
|
| 37 |
+
self.nesting_level = nesting_level
|
| 38 |
+
self.inner_max_num_threads = inner_max_num_threads
|
| 39 |
+
|
| 40 |
+
MAX_NUM_THREADS_VARS = [
|
| 41 |
+
'OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
|
| 42 |
+
'BLIS_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMBA_NUM_THREADS',
|
| 43 |
+
'NUMEXPR_NUM_THREADS',
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
TBB_ENABLE_IPC_VAR = "ENABLE_IPC"
|
| 47 |
+
|
| 48 |
+
@abstractmethod
|
| 49 |
+
def effective_n_jobs(self, n_jobs):
|
| 50 |
+
"""Determine the number of jobs that can actually run in parallel
|
| 51 |
+
|
| 52 |
+
n_jobs is the number of workers requested by the callers. Passing
|
| 53 |
+
n_jobs=-1 means requesting all available workers for instance matching
|
| 54 |
+
the number of CPU cores on the worker host(s).
|
| 55 |
+
|
| 56 |
+
This method should return a guesstimate of the number of workers that
|
| 57 |
+
can actually perform work concurrently. The primary use case is to make
|
| 58 |
+
it possible for the caller to know in how many chunks to slice the
|
| 59 |
+
work.
|
| 60 |
+
|
| 61 |
+
In general working on larger data chunks is more efficient (less
|
| 62 |
+
scheduling overhead and better use of CPU cache prefetching heuristics)
|
| 63 |
+
as long as all the workers have enough work to do.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
@abstractmethod
|
| 67 |
+
def apply_async(self, func, callback=None):
|
| 68 |
+
"""Schedule a func to be run"""
|
| 69 |
+
|
| 70 |
+
def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
|
| 71 |
+
**backend_args):
|
| 72 |
+
"""Reconfigure the backend and return the number of workers.
|
| 73 |
+
|
| 74 |
+
This makes it possible to reuse an existing backend instance for
|
| 75 |
+
successive independent calls to Parallel with different parameters.
|
| 76 |
+
"""
|
| 77 |
+
self.parallel = parallel
|
| 78 |
+
return self.effective_n_jobs(n_jobs)
|
| 79 |
+
|
| 80 |
+
def start_call(self):
|
| 81 |
+
"""Call-back method called at the beginning of a Parallel call"""
|
| 82 |
+
|
| 83 |
+
def stop_call(self):
|
| 84 |
+
"""Call-back method called at the end of a Parallel call"""
|
| 85 |
+
|
| 86 |
+
def terminate(self):
|
| 87 |
+
"""Shutdown the workers and free the shared memory."""
|
| 88 |
+
|
| 89 |
+
def compute_batch_size(self):
|
| 90 |
+
"""Determine the optimal batch size"""
|
| 91 |
+
return 1
|
| 92 |
+
|
| 93 |
+
def batch_completed(self, batch_size, duration):
|
| 94 |
+
"""Callback indicate how long it took to run a batch"""
|
| 95 |
+
|
| 96 |
+
def get_exceptions(self):
|
| 97 |
+
"""List of exception types to be captured."""
|
| 98 |
+
return []
|
| 99 |
+
|
| 100 |
+
def abort_everything(self, ensure_ready=True):
|
| 101 |
+
"""Abort any running tasks
|
| 102 |
+
|
| 103 |
+
This is called when an exception has been raised when executing a tasks
|
| 104 |
+
and all the remaining tasks will be ignored and can therefore be
|
| 105 |
+
aborted to spare computation resources.
|
| 106 |
+
|
| 107 |
+
If ensure_ready is True, the backend should be left in an operating
|
| 108 |
+
state as future tasks might be re-submitted via that same backend
|
| 109 |
+
instance.
|
| 110 |
+
|
| 111 |
+
If ensure_ready is False, the implementer of this method can decide
|
| 112 |
+
to leave the backend in a closed / terminated state as no new task
|
| 113 |
+
are expected to be submitted to this backend.
|
| 114 |
+
|
| 115 |
+
Setting ensure_ready to False is an optimization that can be leveraged
|
| 116 |
+
when aborting tasks via killing processes from a local process pool
|
| 117 |
+
managed by the backend it-self: if we expect no new tasks, there is no
|
| 118 |
+
point in re-creating new workers.
|
| 119 |
+
"""
|
| 120 |
+
# Does nothing by default: to be overridden in subclasses when
|
| 121 |
+
# canceling tasks is possible.
|
| 122 |
+
pass
|
| 123 |
+
|
| 124 |
+
def get_nested_backend(self):
|
| 125 |
+
"""Backend instance to be used by nested Parallel calls.
|
| 126 |
+
|
| 127 |
+
By default a thread-based backend is used for the first level of
|
| 128 |
+
nesting. Beyond, switch to sequential backend to avoid spawning too
|
| 129 |
+
many threads on the host.
|
| 130 |
+
"""
|
| 131 |
+
nesting_level = getattr(self, 'nesting_level', 0) + 1
|
| 132 |
+
if nesting_level > 1:
|
| 133 |
+
return SequentialBackend(nesting_level=nesting_level), None
|
| 134 |
+
else:
|
| 135 |
+
return ThreadingBackend(nesting_level=nesting_level), None
|
| 136 |
+
|
| 137 |
+
@contextlib.contextmanager
|
| 138 |
+
def retrieval_context(self):
|
| 139 |
+
"""Context manager to manage an execution context.
|
| 140 |
+
|
| 141 |
+
Calls to Parallel.retrieve will be made inside this context.
|
| 142 |
+
|
| 143 |
+
By default, this does nothing. It may be useful for subclasses to
|
| 144 |
+
handle nested parallelism. In particular, it may be required to avoid
|
| 145 |
+
deadlocks if a backend manages a fixed number of workers, when those
|
| 146 |
+
workers may be asked to do nested Parallel calls. Without
|
| 147 |
+
'retrieval_context' this could lead to deadlock, as all the workers
|
| 148 |
+
managed by the backend may be "busy" waiting for the nested parallel
|
| 149 |
+
calls to finish, but the backend has no free workers to execute those
|
| 150 |
+
tasks.
|
| 151 |
+
"""
|
| 152 |
+
yield
|
| 153 |
+
|
| 154 |
+
def _prepare_worker_env(self, n_jobs):
|
| 155 |
+
"""Return environment variables limiting threadpools in external libs.
|
| 156 |
+
|
| 157 |
+
This function return a dict containing environment variables to pass
|
| 158 |
+
when creating a pool of process. These environment variables limit the
|
| 159 |
+
number of threads to `n_threads` for OpenMP, MKL, Accelerated and
|
| 160 |
+
OpenBLAS libraries in the child processes.
|
| 161 |
+
"""
|
| 162 |
+
explicit_n_threads = self.inner_max_num_threads
|
| 163 |
+
default_n_threads = str(max(cpu_count() // n_jobs, 1))
|
| 164 |
+
|
| 165 |
+
# Set the inner environment variables to self.inner_max_num_threads if
|
| 166 |
+
# it is given. Else, default to cpu_count // n_jobs unless the variable
|
| 167 |
+
# is already present in the parent process environment.
|
| 168 |
+
env = {}
|
| 169 |
+
for var in self.MAX_NUM_THREADS_VARS:
|
| 170 |
+
if explicit_n_threads is None:
|
| 171 |
+
var_value = os.environ.get(var, None)
|
| 172 |
+
if var_value is None:
|
| 173 |
+
var_value = default_n_threads
|
| 174 |
+
else:
|
| 175 |
+
var_value = str(explicit_n_threads)
|
| 176 |
+
|
| 177 |
+
env[var] = var_value
|
| 178 |
+
|
| 179 |
+
if self.TBB_ENABLE_IPC_VAR not in os.environ:
|
| 180 |
+
# To avoid over-subscription when using TBB, let the TBB schedulers
|
| 181 |
+
# use Inter Process Communication to coordinate:
|
| 182 |
+
env[self.TBB_ENABLE_IPC_VAR] = "1"
|
| 183 |
+
return env
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def in_main_thread():
|
| 187 |
+
return isinstance(threading.current_thread(), threading._MainThread)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class SequentialBackend(ParallelBackendBase):
|
| 191 |
+
"""A ParallelBackend which will execute all batches sequentially.
|
| 192 |
+
|
| 193 |
+
Does not use/create any threading objects, and hence has minimal
|
| 194 |
+
overhead. Used when n_jobs == 1.
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
uses_threads = True
|
| 198 |
+
supports_sharedmem = True
|
| 199 |
+
|
| 200 |
+
def effective_n_jobs(self, n_jobs):
|
| 201 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 202 |
+
if n_jobs == 0:
|
| 203 |
+
raise ValueError('n_jobs == 0 in Parallel has no meaning')
|
| 204 |
+
return 1
|
| 205 |
+
|
| 206 |
+
def apply_async(self, func, callback=None):
|
| 207 |
+
"""Schedule a func to be run"""
|
| 208 |
+
result = ImmediateResult(func)
|
| 209 |
+
if callback:
|
| 210 |
+
callback(result)
|
| 211 |
+
return result
|
| 212 |
+
|
| 213 |
+
def get_nested_backend(self):
|
| 214 |
+
# import is not top level to avoid cyclic import errors.
|
| 215 |
+
from .parallel import get_active_backend
|
| 216 |
+
|
| 217 |
+
# SequentialBackend should neither change the nesting level, the
|
| 218 |
+
# default backend or the number of jobs. Just return the current one.
|
| 219 |
+
return get_active_backend()
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class PoolManagerMixin(object):
|
| 223 |
+
"""A helper class for managing pool of workers."""
|
| 224 |
+
|
| 225 |
+
_pool = None
|
| 226 |
+
|
| 227 |
+
def effective_n_jobs(self, n_jobs):
|
| 228 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 229 |
+
if n_jobs == 0:
|
| 230 |
+
raise ValueError('n_jobs == 0 in Parallel has no meaning')
|
| 231 |
+
elif mp is None or n_jobs is None:
|
| 232 |
+
# multiprocessing is not available or disabled, fallback
|
| 233 |
+
# to sequential mode
|
| 234 |
+
return 1
|
| 235 |
+
elif n_jobs < 0:
|
| 236 |
+
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
|
| 237 |
+
return n_jobs
|
| 238 |
+
|
| 239 |
+
def terminate(self):
|
| 240 |
+
"""Shutdown the process or thread pool"""
|
| 241 |
+
if self._pool is not None:
|
| 242 |
+
self._pool.close()
|
| 243 |
+
self._pool.terminate() # terminate does a join()
|
| 244 |
+
self._pool = None
|
| 245 |
+
|
| 246 |
+
def _get_pool(self):
|
| 247 |
+
"""Used by apply_async to make it possible to implement lazy init"""
|
| 248 |
+
return self._pool
|
| 249 |
+
|
| 250 |
+
def apply_async(self, func, callback=None):
|
| 251 |
+
"""Schedule a func to be run"""
|
| 252 |
+
return self._get_pool().apply_async(
|
| 253 |
+
SafeFunction(func), callback=callback)
|
| 254 |
+
|
| 255 |
+
def abort_everything(self, ensure_ready=True):
|
| 256 |
+
"""Shutdown the pool and restart a new one with the same parameters"""
|
| 257 |
+
self.terminate()
|
| 258 |
+
if ensure_ready:
|
| 259 |
+
self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel,
|
| 260 |
+
**self.parallel._backend_args)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class AutoBatchingMixin(object):
|
| 264 |
+
"""A helper class for automagically batching jobs."""
|
| 265 |
+
|
| 266 |
+
# In seconds, should be big enough to hide multiprocessing dispatching
|
| 267 |
+
# overhead.
|
| 268 |
+
# This settings was found by running benchmarks/bench_auto_batching.py
|
| 269 |
+
# with various parameters on various platforms.
|
| 270 |
+
MIN_IDEAL_BATCH_DURATION = .2
|
| 271 |
+
|
| 272 |
+
# Should not be too high to avoid stragglers: long jobs running alone
|
| 273 |
+
# on a single worker while other workers have no work to process any more.
|
| 274 |
+
MAX_IDEAL_BATCH_DURATION = 2
|
| 275 |
+
|
| 276 |
+
# Batching counters default values
|
| 277 |
+
_DEFAULT_EFFECTIVE_BATCH_SIZE = 1
|
| 278 |
+
_DEFAULT_SMOOTHED_BATCH_DURATION = 0.0
|
| 279 |
+
|
| 280 |
+
def __init__(self, **kwargs):
|
| 281 |
+
super().__init__(**kwargs)
|
| 282 |
+
self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
|
| 283 |
+
self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 284 |
+
|
| 285 |
+
def compute_batch_size(self):
|
| 286 |
+
"""Determine the optimal batch size"""
|
| 287 |
+
old_batch_size = self._effective_batch_size
|
| 288 |
+
batch_duration = self._smoothed_batch_duration
|
| 289 |
+
if (batch_duration > 0 and
|
| 290 |
+
batch_duration < self.MIN_IDEAL_BATCH_DURATION):
|
| 291 |
+
# The current batch size is too small: the duration of the
|
| 292 |
+
# processing of a batch of task is not large enough to hide
|
| 293 |
+
# the scheduling overhead.
|
| 294 |
+
ideal_batch_size = int(old_batch_size *
|
| 295 |
+
self.MIN_IDEAL_BATCH_DURATION /
|
| 296 |
+
batch_duration)
|
| 297 |
+
# Multiply by two to limit oscilations between min and max.
|
| 298 |
+
ideal_batch_size *= 2
|
| 299 |
+
|
| 300 |
+
# dont increase the batch size too fast to limit huge batch sizes
|
| 301 |
+
# potentially leading to starving worker
|
| 302 |
+
batch_size = min(2 * old_batch_size, ideal_batch_size)
|
| 303 |
+
|
| 304 |
+
batch_size = max(batch_size, 1)
|
| 305 |
+
|
| 306 |
+
self._effective_batch_size = batch_size
|
| 307 |
+
if self.parallel.verbose >= 10:
|
| 308 |
+
self.parallel._print(
|
| 309 |
+
"Batch computation too fast (%.4fs.) "
|
| 310 |
+
"Setting batch_size=%d.", (batch_duration, batch_size))
|
| 311 |
+
elif (batch_duration > self.MAX_IDEAL_BATCH_DURATION and
|
| 312 |
+
old_batch_size >= 2):
|
| 313 |
+
# The current batch size is too big. If we schedule overly long
|
| 314 |
+
# running batches some CPUs might wait with nothing left to do
|
| 315 |
+
# while a couple of CPUs a left processing a few long running
|
| 316 |
+
# batches. Better reduce the batch size a bit to limit the
|
| 317 |
+
# likelihood of scheduling such stragglers.
|
| 318 |
+
|
| 319 |
+
# decrease the batch size quickly to limit potential starving
|
| 320 |
+
ideal_batch_size = int(
|
| 321 |
+
old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration
|
| 322 |
+
)
|
| 323 |
+
# Multiply by two to limit oscilations between min and max.
|
| 324 |
+
batch_size = max(2 * ideal_batch_size, 1)
|
| 325 |
+
self._effective_batch_size = batch_size
|
| 326 |
+
if self.parallel.verbose >= 10:
|
| 327 |
+
self.parallel._print(
|
| 328 |
+
"Batch computation too slow (%.4fs.) "
|
| 329 |
+
"Setting batch_size=%d.", (batch_duration, batch_size))
|
| 330 |
+
else:
|
| 331 |
+
# No batch size adjustment
|
| 332 |
+
batch_size = old_batch_size
|
| 333 |
+
|
| 334 |
+
if batch_size != old_batch_size:
|
| 335 |
+
# Reset estimation of the smoothed mean batch duration: this
|
| 336 |
+
# estimate is updated in the multiprocessing apply_async
|
| 337 |
+
# CallBack as long as the batch_size is constant. Therefore
|
| 338 |
+
# we need to reset the estimate whenever we re-tune the batch
|
| 339 |
+
# size.
|
| 340 |
+
self._smoothed_batch_duration = \
|
| 341 |
+
self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 342 |
+
|
| 343 |
+
return batch_size
|
| 344 |
+
|
| 345 |
+
def batch_completed(self, batch_size, duration):
|
| 346 |
+
"""Callback indicate how long it took to run a batch"""
|
| 347 |
+
if batch_size == self._effective_batch_size:
|
| 348 |
+
# Update the smoothed streaming estimate of the duration of a batch
|
| 349 |
+
# from dispatch to completion
|
| 350 |
+
old_duration = self._smoothed_batch_duration
|
| 351 |
+
if old_duration == self._DEFAULT_SMOOTHED_BATCH_DURATION:
|
| 352 |
+
# First record of duration for this batch size after the last
|
| 353 |
+
# reset.
|
| 354 |
+
new_duration = duration
|
| 355 |
+
else:
|
| 356 |
+
# Update the exponentially weighted average of the duration of
|
| 357 |
+
# batch for the current effective size.
|
| 358 |
+
new_duration = 0.8 * old_duration + 0.2 * duration
|
| 359 |
+
self._smoothed_batch_duration = new_duration
|
| 360 |
+
|
| 361 |
+
def reset_batch_stats(self):
|
| 362 |
+
"""Reset batch statistics to default values.
|
| 363 |
+
|
| 364 |
+
This avoids interferences with future jobs.
|
| 365 |
+
"""
|
| 366 |
+
self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
|
| 367 |
+
self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class ThreadingBackend(PoolManagerMixin, ParallelBackendBase):
|
| 371 |
+
"""A ParallelBackend which will use a thread pool to execute batches in.
|
| 372 |
+
|
| 373 |
+
This is a low-overhead backend but it suffers from the Python Global
|
| 374 |
+
Interpreter Lock if the called function relies a lot on Python objects.
|
| 375 |
+
Mostly useful when the execution bottleneck is a compiled extension that
|
| 376 |
+
explicitly releases the GIL (for instance a Cython loop wrapped in a "with
|
| 377 |
+
nogil" block or an expensive call to a library such as NumPy).
|
| 378 |
+
|
| 379 |
+
The actual thread pool is lazily initialized: the actual thread pool
|
| 380 |
+
construction is delayed to the first call to apply_async.
|
| 381 |
+
|
| 382 |
+
ThreadingBackend is used as the default backend for nested calls.
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
supports_timeout = True
|
| 386 |
+
uses_threads = True
|
| 387 |
+
supports_sharedmem = True
|
| 388 |
+
|
| 389 |
+
def configure(self, n_jobs=1, parallel=None, **backend_args):
|
| 390 |
+
"""Build a process or thread pool and return the number of workers"""
|
| 391 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 392 |
+
if n_jobs == 1:
|
| 393 |
+
# Avoid unnecessary overhead and use sequential backend instead.
|
| 394 |
+
raise FallbackToBackend(
|
| 395 |
+
SequentialBackend(nesting_level=self.nesting_level))
|
| 396 |
+
self.parallel = parallel
|
| 397 |
+
self._n_jobs = n_jobs
|
| 398 |
+
return n_jobs
|
| 399 |
+
|
| 400 |
+
def _get_pool(self):
|
| 401 |
+
"""Lazily initialize the thread pool
|
| 402 |
+
|
| 403 |
+
The actual pool of worker threads is only initialized at the first
|
| 404 |
+
call to apply_async.
|
| 405 |
+
"""
|
| 406 |
+
if self._pool is None:
|
| 407 |
+
self._pool = ThreadPool(self._n_jobs)
|
| 408 |
+
return self._pool
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin,
|
| 412 |
+
ParallelBackendBase):
|
| 413 |
+
"""A ParallelBackend which will use a multiprocessing.Pool.
|
| 414 |
+
|
| 415 |
+
Will introduce some communication and memory overhead when exchanging
|
| 416 |
+
input and output data with the with the worker Python processes.
|
| 417 |
+
However, does not suffer from the Python Global Interpreter Lock.
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
supports_timeout = True
|
| 421 |
+
|
| 422 |
+
def effective_n_jobs(self, n_jobs):
|
| 423 |
+
"""Determine the number of jobs which are going to run in parallel.
|
| 424 |
+
|
| 425 |
+
This also checks if we are attempting to create a nested parallel
|
| 426 |
+
loop.
|
| 427 |
+
"""
|
| 428 |
+
if mp is None:
|
| 429 |
+
return 1
|
| 430 |
+
|
| 431 |
+
if mp.current_process().daemon:
|
| 432 |
+
# Daemonic processes cannot have children
|
| 433 |
+
if n_jobs != 1:
|
| 434 |
+
if inside_dask_worker():
|
| 435 |
+
msg = (
|
| 436 |
+
"Inside a Dask worker with daemon=True, "
|
| 437 |
+
"setting n_jobs=1.\nPossible work-arounds:\n"
|
| 438 |
+
"- dask.config.set("
|
| 439 |
+
"{'distributed.worker.daemon': False})"
|
| 440 |
+
"- set the environment variable "
|
| 441 |
+
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
|
| 442 |
+
"before creating your Dask cluster."
|
| 443 |
+
)
|
| 444 |
+
else:
|
| 445 |
+
msg = (
|
| 446 |
+
'Multiprocessing-backed parallel loops '
|
| 447 |
+
'cannot be nested, setting n_jobs=1'
|
| 448 |
+
)
|
| 449 |
+
warnings.warn(msg, stacklevel=3)
|
| 450 |
+
return 1
|
| 451 |
+
|
| 452 |
+
if process_executor._CURRENT_DEPTH > 0:
|
| 453 |
+
# Mixing loky and multiprocessing in nested loop is not supported
|
| 454 |
+
if n_jobs != 1:
|
| 455 |
+
warnings.warn(
|
| 456 |
+
'Multiprocessing-backed parallel loops cannot be nested,'
|
| 457 |
+
' below loky, setting n_jobs=1',
|
| 458 |
+
stacklevel=3)
|
| 459 |
+
return 1
|
| 460 |
+
|
| 461 |
+
elif not (self.in_main_thread() or self.nesting_level == 0):
|
| 462 |
+
# Prevent posix fork inside in non-main posix threads
|
| 463 |
+
if n_jobs != 1:
|
| 464 |
+
warnings.warn(
|
| 465 |
+
'Multiprocessing-backed parallel loops cannot be nested'
|
| 466 |
+
' below threads, setting n_jobs=1',
|
| 467 |
+
stacklevel=3)
|
| 468 |
+
return 1
|
| 469 |
+
|
| 470 |
+
return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs)
|
| 471 |
+
|
| 472 |
+
def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
|
| 473 |
+
**memmappingpool_args):
|
| 474 |
+
"""Build a process or thread pool and return the number of workers"""
|
| 475 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 476 |
+
if n_jobs == 1:
|
| 477 |
+
raise FallbackToBackend(
|
| 478 |
+
SequentialBackend(nesting_level=self.nesting_level))
|
| 479 |
+
|
| 480 |
+
# Make sure to free as much memory as possible before forking
|
| 481 |
+
gc.collect()
|
| 482 |
+
self._pool = MemmappingPool(n_jobs, **memmappingpool_args)
|
| 483 |
+
self.parallel = parallel
|
| 484 |
+
return n_jobs
|
| 485 |
+
|
| 486 |
+
def terminate(self):
|
| 487 |
+
"""Shutdown the process or thread pool"""
|
| 488 |
+
super(MultiprocessingBackend, self).terminate()
|
| 489 |
+
self.reset_batch_stats()
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class LokyBackend(AutoBatchingMixin, ParallelBackendBase):
|
| 493 |
+
"""Managing pool of workers with loky instead of multiprocessing."""
|
| 494 |
+
|
| 495 |
+
supports_timeout = True
|
| 496 |
+
supports_inner_max_num_threads = True
|
| 497 |
+
|
| 498 |
+
def configure(self, n_jobs=1, parallel=None, prefer=None, require=None,
|
| 499 |
+
idle_worker_timeout=300, **memmappingexecutor_args):
|
| 500 |
+
"""Build a process executor and return the number of workers"""
|
| 501 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 502 |
+
if n_jobs == 1:
|
| 503 |
+
raise FallbackToBackend(
|
| 504 |
+
SequentialBackend(nesting_level=self.nesting_level))
|
| 505 |
+
|
| 506 |
+
self._workers = get_memmapping_executor(
|
| 507 |
+
n_jobs, timeout=idle_worker_timeout,
|
| 508 |
+
env=self._prepare_worker_env(n_jobs=n_jobs),
|
| 509 |
+
context_id=parallel._id, **memmappingexecutor_args)
|
| 510 |
+
self.parallel = parallel
|
| 511 |
+
return n_jobs
|
| 512 |
+
|
| 513 |
+
def effective_n_jobs(self, n_jobs):
|
| 514 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 515 |
+
if n_jobs == 0:
|
| 516 |
+
raise ValueError('n_jobs == 0 in Parallel has no meaning')
|
| 517 |
+
elif mp is None or n_jobs is None:
|
| 518 |
+
# multiprocessing is not available or disabled, fallback
|
| 519 |
+
# to sequential mode
|
| 520 |
+
return 1
|
| 521 |
+
elif mp.current_process().daemon:
|
| 522 |
+
# Daemonic processes cannot have children
|
| 523 |
+
if n_jobs != 1:
|
| 524 |
+
if inside_dask_worker():
|
| 525 |
+
msg = (
|
| 526 |
+
"Inside a Dask worker with daemon=True, "
|
| 527 |
+
"setting n_jobs=1.\nPossible work-arounds:\n"
|
| 528 |
+
"- dask.config.set("
|
| 529 |
+
"{'distributed.worker.daemon': False})\n"
|
| 530 |
+
"- set the environment variable "
|
| 531 |
+
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
|
| 532 |
+
"before creating your Dask cluster."
|
| 533 |
+
)
|
| 534 |
+
else:
|
| 535 |
+
msg = (
|
| 536 |
+
'Loky-backed parallel loops cannot be called in a'
|
| 537 |
+
' multiprocessing, setting n_jobs=1'
|
| 538 |
+
)
|
| 539 |
+
warnings.warn(msg, stacklevel=3)
|
| 540 |
+
|
| 541 |
+
return 1
|
| 542 |
+
elif not (self.in_main_thread() or self.nesting_level == 0):
|
| 543 |
+
# Prevent posix fork inside in non-main posix threads
|
| 544 |
+
if n_jobs != 1:
|
| 545 |
+
warnings.warn(
|
| 546 |
+
'Loky-backed parallel loops cannot be nested below '
|
| 547 |
+
'threads, setting n_jobs=1',
|
| 548 |
+
stacklevel=3)
|
| 549 |
+
return 1
|
| 550 |
+
elif n_jobs < 0:
|
| 551 |
+
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
|
| 552 |
+
return n_jobs
|
| 553 |
+
|
| 554 |
+
def apply_async(self, func, callback=None):
|
| 555 |
+
"""Schedule a func to be run"""
|
| 556 |
+
future = self._workers.submit(SafeFunction(func))
|
| 557 |
+
future.get = functools.partial(self.wrap_future_result, future)
|
| 558 |
+
if callback is not None:
|
| 559 |
+
future.add_done_callback(callback)
|
| 560 |
+
return future
|
| 561 |
+
|
| 562 |
+
@staticmethod
|
| 563 |
+
def wrap_future_result(future, timeout=None):
|
| 564 |
+
"""Wrapper for Future.result to implement the same behaviour as
|
| 565 |
+
AsyncResults.get from multiprocessing."""
|
| 566 |
+
try:
|
| 567 |
+
return future.result(timeout=timeout)
|
| 568 |
+
except CfTimeoutError as e:
|
| 569 |
+
raise TimeoutError from e
|
| 570 |
+
|
| 571 |
+
def terminate(self):
|
| 572 |
+
if self._workers is not None:
|
| 573 |
+
# Don't terminate the workers as we want to reuse them in later
|
| 574 |
+
# calls, but cleanup the temporary resources that the Parallel call
|
| 575 |
+
# created. This 'hack' requires a private, low-level operation.
|
| 576 |
+
self._workers._temp_folder_manager._unlink_temporary_resources(
|
| 577 |
+
context_id=self.parallel._id
|
| 578 |
+
)
|
| 579 |
+
self._workers = None
|
| 580 |
+
|
| 581 |
+
self.reset_batch_stats()
|
| 582 |
+
|
| 583 |
+
def abort_everything(self, ensure_ready=True):
|
| 584 |
+
"""Shutdown the workers and restart a new one with the same parameters
|
| 585 |
+
"""
|
| 586 |
+
self._workers.terminate(kill_workers=True)
|
| 587 |
+
self._workers = None
|
| 588 |
+
|
| 589 |
+
if ensure_ready:
|
| 590 |
+
self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
class ImmediateResult(object):
|
| 594 |
+
def __init__(self, batch):
|
| 595 |
+
# Don't delay the application, to avoid keeping the input
|
| 596 |
+
# arguments in memory
|
| 597 |
+
self.results = batch()
|
| 598 |
+
|
| 599 |
+
def get(self):
|
| 600 |
+
return self.results
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class SafeFunction(object):
|
| 604 |
+
"""Wrapper that handles the serialization of exception tracebacks.
|
| 605 |
+
|
| 606 |
+
TODO python2_drop: check whether SafeFunction is still needed since we
|
| 607 |
+
dropped support for Python 2. If not needed anymore it should be
|
| 608 |
+
deprecated.
|
| 609 |
+
|
| 610 |
+
If an exception is triggered when calling the inner function, a copy of
|
| 611 |
+
the full traceback is captured to make it possible to serialize
|
| 612 |
+
it so that it can be rendered in a different Python process.
|
| 613 |
+
|
| 614 |
+
"""
|
| 615 |
+
def __init__(self, func):
|
| 616 |
+
self.func = func
|
| 617 |
+
|
| 618 |
+
def __call__(self, *args, **kwargs):
|
| 619 |
+
try:
|
| 620 |
+
return self.func(*args, **kwargs)
|
| 621 |
+
except KeyboardInterrupt as e:
|
| 622 |
+
# We capture the KeyboardInterrupt and reraise it as
|
| 623 |
+
# something different, as multiprocessing does not
|
| 624 |
+
# interrupt processing for a KeyboardInterrupt
|
| 625 |
+
raise WorkerInterrupt() from e
|
| 626 |
+
except BaseException:
|
| 627 |
+
# Rely on Python 3 built-in Remote Traceback reporting
|
| 628 |
+
raise
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class FallbackToBackend(Exception):
|
| 632 |
+
"""Raised when configuration should fallback to another backend"""
|
| 633 |
+
|
| 634 |
+
def __init__(self, backend):
|
| 635 |
+
self.backend = backend
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def inside_dask_worker():
|
| 639 |
+
"""Check whether the current function is executed inside a Dask worker.
|
| 640 |
+
"""
|
| 641 |
+
# This function can not be in joblib._dask because there would be a
|
| 642 |
+
# circular import:
|
| 643 |
+
# _dask imports _parallel_backend that imports _dask ...
|
| 644 |
+
try:
|
| 645 |
+
from distributed import get_worker
|
| 646 |
+
except ImportError:
|
| 647 |
+
return False
|
| 648 |
+
|
| 649 |
+
try:
|
| 650 |
+
get_worker()
|
| 651 |
+
return True
|
| 652 |
+
except ValueError:
|
| 653 |
+
return False
|
runtime/Lib/site-packages/joblib/_store_backends.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Storage providers backends for Memory caching."""
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
import os.path
|
| 6 |
+
import datetime
|
| 7 |
+
import json
|
| 8 |
+
import shutil
|
| 9 |
+
import warnings
|
| 10 |
+
import collections
|
| 11 |
+
import operator
|
| 12 |
+
import threading
|
| 13 |
+
from abc import ABCMeta, abstractmethod
|
| 14 |
+
|
| 15 |
+
from .backports import concurrency_safe_rename
|
| 16 |
+
from .disk import mkdirp, memstr_to_bytes, rm_subdirs
|
| 17 |
+
from . import numpy_pickle
|
| 18 |
+
|
| 19 |
+
CacheItemInfo = collections.namedtuple('CacheItemInfo',
|
| 20 |
+
'path size last_access')
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def concurrency_safe_write(object_to_write, filename, write_func):
|
| 24 |
+
"""Writes an object into a unique file in a concurrency-safe way."""
|
| 25 |
+
thread_id = id(threading.current_thread())
|
| 26 |
+
temporary_filename = '{}.thread-{}-pid-{}'.format(
|
| 27 |
+
filename, thread_id, os.getpid())
|
| 28 |
+
write_func(object_to_write, temporary_filename)
|
| 29 |
+
|
| 30 |
+
return temporary_filename
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class StoreBackendBase(metaclass=ABCMeta):
|
| 34 |
+
"""Helper Abstract Base Class which defines all methods that
|
| 35 |
+
a StorageBackend must implement."""
|
| 36 |
+
|
| 37 |
+
location = None
|
| 38 |
+
|
| 39 |
+
@abstractmethod
|
| 40 |
+
def _open_item(self, f, mode):
|
| 41 |
+
"""Opens an item on the store and return a file-like object.
|
| 42 |
+
|
| 43 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 44 |
+
|
| 45 |
+
Parameters
|
| 46 |
+
----------
|
| 47 |
+
f: a file-like object
|
| 48 |
+
The file-like object where an item is stored and retrieved
|
| 49 |
+
mode: string, optional
|
| 50 |
+
the mode in which the file-like object is opened allowed valued are
|
| 51 |
+
'rb', 'wb'
|
| 52 |
+
|
| 53 |
+
Returns
|
| 54 |
+
-------
|
| 55 |
+
a file-like object
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
@abstractmethod
|
| 59 |
+
def _item_exists(self, location):
|
| 60 |
+
"""Checks if an item location exists in the store.
|
| 61 |
+
|
| 62 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 63 |
+
|
| 64 |
+
Parameters
|
| 65 |
+
----------
|
| 66 |
+
location: string
|
| 67 |
+
The location of an item. On a filesystem, this corresponds to the
|
| 68 |
+
absolute path, including the filename, of a file.
|
| 69 |
+
|
| 70 |
+
Returns
|
| 71 |
+
-------
|
| 72 |
+
True if the item exists, False otherwise
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
@abstractmethod
|
| 76 |
+
def _move_item(self, src, dst):
|
| 77 |
+
"""Moves an item from src to dst in the store.
|
| 78 |
+
|
| 79 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 80 |
+
|
| 81 |
+
Parameters
|
| 82 |
+
----------
|
| 83 |
+
src: string
|
| 84 |
+
The source location of an item
|
| 85 |
+
dst: string
|
| 86 |
+
The destination location of an item
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
@abstractmethod
|
| 90 |
+
def create_location(self, location):
|
| 91 |
+
"""Creates a location on the store.
|
| 92 |
+
|
| 93 |
+
Parameters
|
| 94 |
+
----------
|
| 95 |
+
location: string
|
| 96 |
+
The location in the store. On a filesystem, this corresponds to a
|
| 97 |
+
directory.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
@abstractmethod
|
| 101 |
+
def clear_location(self, location):
|
| 102 |
+
"""Clears a location on the store.
|
| 103 |
+
|
| 104 |
+
Parameters
|
| 105 |
+
----------
|
| 106 |
+
location: string
|
| 107 |
+
The location in the store. On a filesystem, this corresponds to a
|
| 108 |
+
directory or a filename absolute path
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
@abstractmethod
|
| 112 |
+
def get_items(self):
|
| 113 |
+
"""Returns the whole list of items available in the store.
|
| 114 |
+
|
| 115 |
+
Returns
|
| 116 |
+
-------
|
| 117 |
+
The list of items identified by their ids (e.g filename in a
|
| 118 |
+
filesystem).
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
@abstractmethod
|
| 122 |
+
def configure(self, location, verbose=0, backend_options=dict()):
|
| 123 |
+
"""Configures the store.
|
| 124 |
+
|
| 125 |
+
Parameters
|
| 126 |
+
----------
|
| 127 |
+
location: string
|
| 128 |
+
The base location used by the store. On a filesystem, this
|
| 129 |
+
corresponds to a directory.
|
| 130 |
+
verbose: int
|
| 131 |
+
The level of verbosity of the store
|
| 132 |
+
backend_options: dict
|
| 133 |
+
Contains a dictionary of named parameters used to configure the
|
| 134 |
+
store backend.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class StoreBackendMixin(object):
|
| 139 |
+
"""Class providing all logic for managing the store in a generic way.
|
| 140 |
+
|
| 141 |
+
The StoreBackend subclass has to implement 3 methods: create_location,
|
| 142 |
+
clear_location and configure. The StoreBackend also has to provide
|
| 143 |
+
a private _open_item, _item_exists and _move_item methods. The _open_item
|
| 144 |
+
method has to have the same signature as the builtin open and return a
|
| 145 |
+
file-like object.
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
def load_item(self, path, verbose=1, msg=None):
|
| 149 |
+
"""Load an item from the store given its path as a list of
|
| 150 |
+
strings."""
|
| 151 |
+
full_path = os.path.join(self.location, *path)
|
| 152 |
+
|
| 153 |
+
if verbose > 1:
|
| 154 |
+
if verbose < 10:
|
| 155 |
+
print('{0}...'.format(msg))
|
| 156 |
+
else:
|
| 157 |
+
print('{0} from {1}'.format(msg, full_path))
|
| 158 |
+
|
| 159 |
+
mmap_mode = (None if not hasattr(self, 'mmap_mode')
|
| 160 |
+
else self.mmap_mode)
|
| 161 |
+
|
| 162 |
+
filename = os.path.join(full_path, 'output.pkl')
|
| 163 |
+
if not self._item_exists(filename):
|
| 164 |
+
raise KeyError("Non-existing item (may have been "
|
| 165 |
+
"cleared).\nFile %s does not exist" % filename)
|
| 166 |
+
|
| 167 |
+
# file-like object cannot be used when mmap_mode is set
|
| 168 |
+
if mmap_mode is None:
|
| 169 |
+
with self._open_item(filename, "rb") as f:
|
| 170 |
+
item = numpy_pickle.load(f)
|
| 171 |
+
else:
|
| 172 |
+
item = numpy_pickle.load(filename, mmap_mode=mmap_mode)
|
| 173 |
+
return item
|
| 174 |
+
|
| 175 |
+
def dump_item(self, path, item, verbose=1):
|
| 176 |
+
"""Dump an item in the store at the path given as a list of
|
| 177 |
+
strings."""
|
| 178 |
+
try:
|
| 179 |
+
item_path = os.path.join(self.location, *path)
|
| 180 |
+
if not self._item_exists(item_path):
|
| 181 |
+
self.create_location(item_path)
|
| 182 |
+
filename = os.path.join(item_path, 'output.pkl')
|
| 183 |
+
if verbose > 10:
|
| 184 |
+
print('Persisting in %s' % item_path)
|
| 185 |
+
|
| 186 |
+
def write_func(to_write, dest_filename):
|
| 187 |
+
with self._open_item(dest_filename, "wb") as f:
|
| 188 |
+
numpy_pickle.dump(to_write, f,
|
| 189 |
+
compress=self.compress)
|
| 190 |
+
|
| 191 |
+
self._concurrency_safe_write(item, filename, write_func)
|
| 192 |
+
except: # noqa: E722
|
| 193 |
+
" Race condition in the creation of the directory "
|
| 194 |
+
|
| 195 |
+
def clear_item(self, path):
|
| 196 |
+
"""Clear the item at the path, given as a list of strings."""
|
| 197 |
+
item_path = os.path.join(self.location, *path)
|
| 198 |
+
if self._item_exists(item_path):
|
| 199 |
+
self.clear_location(item_path)
|
| 200 |
+
|
| 201 |
+
def contains_item(self, path):
|
| 202 |
+
"""Check if there is an item at the path, given as a list of
|
| 203 |
+
strings"""
|
| 204 |
+
item_path = os.path.join(self.location, *path)
|
| 205 |
+
filename = os.path.join(item_path, 'output.pkl')
|
| 206 |
+
|
| 207 |
+
return self._item_exists(filename)
|
| 208 |
+
|
| 209 |
+
def get_item_info(self, path):
|
| 210 |
+
"""Return information about item."""
|
| 211 |
+
return {'location': os.path.join(self.location,
|
| 212 |
+
*path)}
|
| 213 |
+
|
| 214 |
+
def get_metadata(self, path):
|
| 215 |
+
"""Return actual metadata of an item."""
|
| 216 |
+
try:
|
| 217 |
+
item_path = os.path.join(self.location, *path)
|
| 218 |
+
filename = os.path.join(item_path, 'metadata.json')
|
| 219 |
+
with self._open_item(filename, 'rb') as f:
|
| 220 |
+
return json.loads(f.read().decode('utf-8'))
|
| 221 |
+
except: # noqa: E722
|
| 222 |
+
return {}
|
| 223 |
+
|
| 224 |
+
def store_metadata(self, path, metadata):
|
| 225 |
+
"""Store metadata of a computation."""
|
| 226 |
+
try:
|
| 227 |
+
item_path = os.path.join(self.location, *path)
|
| 228 |
+
self.create_location(item_path)
|
| 229 |
+
filename = os.path.join(item_path, 'metadata.json')
|
| 230 |
+
|
| 231 |
+
def write_func(to_write, dest_filename):
|
| 232 |
+
with self._open_item(dest_filename, "wb") as f:
|
| 233 |
+
f.write(json.dumps(to_write).encode('utf-8'))
|
| 234 |
+
|
| 235 |
+
self._concurrency_safe_write(metadata, filename, write_func)
|
| 236 |
+
except: # noqa: E722
|
| 237 |
+
pass
|
| 238 |
+
|
| 239 |
+
def contains_path(self, path):
|
| 240 |
+
"""Check cached function is available in store."""
|
| 241 |
+
func_path = os.path.join(self.location, *path)
|
| 242 |
+
return self.object_exists(func_path)
|
| 243 |
+
|
| 244 |
+
def clear_path(self, path):
|
| 245 |
+
"""Clear all items with a common path in the store."""
|
| 246 |
+
func_path = os.path.join(self.location, *path)
|
| 247 |
+
if self._item_exists(func_path):
|
| 248 |
+
self.clear_location(func_path)
|
| 249 |
+
|
| 250 |
+
def store_cached_func_code(self, path, func_code=None):
|
| 251 |
+
"""Store the code of the cached function."""
|
| 252 |
+
func_path = os.path.join(self.location, *path)
|
| 253 |
+
if not self._item_exists(func_path):
|
| 254 |
+
self.create_location(func_path)
|
| 255 |
+
|
| 256 |
+
if func_code is not None:
|
| 257 |
+
filename = os.path.join(func_path, "func_code.py")
|
| 258 |
+
with self._open_item(filename, 'wb') as f:
|
| 259 |
+
f.write(func_code.encode('utf-8'))
|
| 260 |
+
|
| 261 |
+
def get_cached_func_code(self, path):
|
| 262 |
+
"""Store the code of the cached function."""
|
| 263 |
+
path += ['func_code.py', ]
|
| 264 |
+
filename = os.path.join(self.location, *path)
|
| 265 |
+
try:
|
| 266 |
+
with self._open_item(filename, 'rb') as f:
|
| 267 |
+
return f.read().decode('utf-8')
|
| 268 |
+
except: # noqa: E722
|
| 269 |
+
raise
|
| 270 |
+
|
| 271 |
+
def get_cached_func_info(self, path):
|
| 272 |
+
"""Return information related to the cached function if it exists."""
|
| 273 |
+
return {'location': os.path.join(self.location, *path)}
|
| 274 |
+
|
| 275 |
+
def clear(self):
|
| 276 |
+
"""Clear the whole store content."""
|
| 277 |
+
self.clear_location(self.location)
|
| 278 |
+
|
| 279 |
+
def reduce_store_size(self, bytes_limit):
|
| 280 |
+
"""Reduce store size to keep it under the given bytes limit."""
|
| 281 |
+
items_to_delete = self._get_items_to_delete(bytes_limit)
|
| 282 |
+
|
| 283 |
+
for item in items_to_delete:
|
| 284 |
+
if self.verbose > 10:
|
| 285 |
+
print('Deleting item {0}'.format(item))
|
| 286 |
+
try:
|
| 287 |
+
self.clear_location(item.path)
|
| 288 |
+
except OSError:
|
| 289 |
+
# Even with ignore_errors=True shutil.rmtree can raise OSError
|
| 290 |
+
# with:
|
| 291 |
+
# [Errno 116] Stale file handle if another process has deleted
|
| 292 |
+
# the folder already.
|
| 293 |
+
pass
|
| 294 |
+
|
| 295 |
+
def _get_items_to_delete(self, bytes_limit):
|
| 296 |
+
"""Get items to delete to keep the store under a size limit."""
|
| 297 |
+
if isinstance(bytes_limit, str):
|
| 298 |
+
bytes_limit = memstr_to_bytes(bytes_limit)
|
| 299 |
+
|
| 300 |
+
items = self.get_items()
|
| 301 |
+
size = sum(item.size for item in items)
|
| 302 |
+
|
| 303 |
+
to_delete_size = size - bytes_limit
|
| 304 |
+
if to_delete_size < 0:
|
| 305 |
+
return []
|
| 306 |
+
|
| 307 |
+
# We want to delete first the cache items that were accessed a
|
| 308 |
+
# long time ago
|
| 309 |
+
items.sort(key=operator.attrgetter('last_access'))
|
| 310 |
+
|
| 311 |
+
items_to_delete = []
|
| 312 |
+
size_so_far = 0
|
| 313 |
+
|
| 314 |
+
for item in items:
|
| 315 |
+
if size_so_far > to_delete_size:
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
items_to_delete.append(item)
|
| 319 |
+
size_so_far += item.size
|
| 320 |
+
|
| 321 |
+
return items_to_delete
|
| 322 |
+
|
| 323 |
+
def _concurrency_safe_write(self, to_write, filename, write_func):
|
| 324 |
+
"""Writes an object into a file in a concurrency-safe way."""
|
| 325 |
+
temporary_filename = concurrency_safe_write(to_write,
|
| 326 |
+
filename, write_func)
|
| 327 |
+
self._move_item(temporary_filename, filename)
|
| 328 |
+
|
| 329 |
+
def __repr__(self):
|
| 330 |
+
"""Printable representation of the store location."""
|
| 331 |
+
return '{class_name}(location="{location}")'.format(
|
| 332 |
+
class_name=self.__class__.__name__, location=self.location)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin):
|
| 336 |
+
"""A StoreBackend used with local or network file systems."""
|
| 337 |
+
|
| 338 |
+
_open_item = staticmethod(open)
|
| 339 |
+
_item_exists = staticmethod(os.path.exists)
|
| 340 |
+
_move_item = staticmethod(concurrency_safe_rename)
|
| 341 |
+
|
| 342 |
+
def clear_location(self, location):
|
| 343 |
+
"""Delete location on store."""
|
| 344 |
+
if (location == self.location):
|
| 345 |
+
rm_subdirs(location)
|
| 346 |
+
else:
|
| 347 |
+
shutil.rmtree(location, ignore_errors=True)
|
| 348 |
+
|
| 349 |
+
def create_location(self, location):
|
| 350 |
+
"""Create object location on store"""
|
| 351 |
+
mkdirp(location)
|
| 352 |
+
|
| 353 |
+
def get_items(self):
|
| 354 |
+
"""Returns the whole list of items available in the store."""
|
| 355 |
+
items = []
|
| 356 |
+
|
| 357 |
+
for dirpath, _, filenames in os.walk(self.location):
|
| 358 |
+
is_cache_hash_dir = re.match('[a-f0-9]{32}',
|
| 359 |
+
os.path.basename(dirpath))
|
| 360 |
+
|
| 361 |
+
if is_cache_hash_dir:
|
| 362 |
+
output_filename = os.path.join(dirpath, 'output.pkl')
|
| 363 |
+
try:
|
| 364 |
+
last_access = os.path.getatime(output_filename)
|
| 365 |
+
except OSError:
|
| 366 |
+
try:
|
| 367 |
+
last_access = os.path.getatime(dirpath)
|
| 368 |
+
except OSError:
|
| 369 |
+
# The directory has already been deleted
|
| 370 |
+
continue
|
| 371 |
+
|
| 372 |
+
last_access = datetime.datetime.fromtimestamp(last_access)
|
| 373 |
+
try:
|
| 374 |
+
full_filenames = [os.path.join(dirpath, fn)
|
| 375 |
+
for fn in filenames]
|
| 376 |
+
dirsize = sum(os.path.getsize(fn)
|
| 377 |
+
for fn in full_filenames)
|
| 378 |
+
except OSError:
|
| 379 |
+
# Either output_filename or one of the files in
|
| 380 |
+
# dirpath does not exist any more. We assume this
|
| 381 |
+
# directory is being cleaned by another process already
|
| 382 |
+
continue
|
| 383 |
+
|
| 384 |
+
items.append(CacheItemInfo(dirpath, dirsize,
|
| 385 |
+
last_access))
|
| 386 |
+
|
| 387 |
+
return items
|
| 388 |
+
|
| 389 |
+
def configure(self, location, verbose=1, backend_options=None):
|
| 390 |
+
"""Configure the store backend.
|
| 391 |
+
|
| 392 |
+
For this backend, valid store options are 'compress' and 'mmap_mode'
|
| 393 |
+
"""
|
| 394 |
+
if backend_options is None:
|
| 395 |
+
backend_options = {}
|
| 396 |
+
|
| 397 |
+
# setup location directory
|
| 398 |
+
self.location = location
|
| 399 |
+
if not os.path.exists(self.location):
|
| 400 |
+
mkdirp(self.location)
|
| 401 |
+
|
| 402 |
+
# item can be stored compressed for faster I/O
|
| 403 |
+
self.compress = backend_options.get('compress', False)
|
| 404 |
+
|
| 405 |
+
# FileSystemStoreBackend can be used with mmap_mode options under
|
| 406 |
+
# certain conditions.
|
| 407 |
+
mmap_mode = backend_options.get('mmap_mode')
|
| 408 |
+
if self.compress and mmap_mode is not None:
|
| 409 |
+
warnings.warn('Compressed items cannot be memmapped in a '
|
| 410 |
+
'filesystem store. Option will be ignored.',
|
| 411 |
+
stacklevel=2)
|
| 412 |
+
|
| 413 |
+
self.mmap_mode = mmap_mode
|
| 414 |
+
self.verbose = verbose
|
runtime/Lib/site-packages/joblib/_utils.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://stackoverflow.com/a/9558001/2536294
|
| 2 |
+
|
| 3 |
+
import ast
|
| 4 |
+
import operator as op
|
| 5 |
+
|
| 6 |
+
# supported operators
|
| 7 |
+
operators = {
|
| 8 |
+
ast.Add: op.add,
|
| 9 |
+
ast.Sub: op.sub,
|
| 10 |
+
ast.Mult: op.mul,
|
| 11 |
+
ast.Div: op.truediv,
|
| 12 |
+
ast.FloorDiv: op.floordiv,
|
| 13 |
+
ast.Mod: op.mod,
|
| 14 |
+
ast.Pow: op.pow,
|
| 15 |
+
ast.USub: op.neg,
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def eval_expr(expr):
|
| 20 |
+
"""
|
| 21 |
+
>>> eval_expr('2*6')
|
| 22 |
+
12
|
| 23 |
+
>>> eval_expr('2**6')
|
| 24 |
+
64
|
| 25 |
+
>>> eval_expr('1 + 2*3**(4) / (6 + -7)')
|
| 26 |
+
-161.0
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
return eval_(ast.parse(expr, mode="eval").body)
|
| 30 |
+
except (TypeError, SyntaxError, KeyError) as e:
|
| 31 |
+
raise ValueError(
|
| 32 |
+
f"{expr!r} is not a valid or supported arithmetic expression."
|
| 33 |
+
) from e
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def eval_(node):
|
| 37 |
+
if isinstance(node, ast.Num): # <number>
|
| 38 |
+
return node.n
|
| 39 |
+
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
|
| 40 |
+
return operators[type(node.op)](eval_(node.left), eval_(node.right))
|
| 41 |
+
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
|
| 42 |
+
return operators[type(node.op)](eval_(node.operand))
|
| 43 |
+
else:
|
| 44 |
+
raise TypeError(node)
|
runtime/Lib/site-packages/joblib/backports.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
from os.path import basename
|
| 9 |
+
from multiprocessing import util
|
| 10 |
+
|
| 11 |
+
# Prior to joblib 1.2, joblib used to import LooseVersion from
|
| 12 |
+
# distutils.version. This import had a side-effect with setuptools that was
|
| 13 |
+
# implicitly required in sklearn.show_versions() to work without raising an
|
| 14 |
+
# exception for scikit-learn 1.0 and earlier. This has been fixed in
|
| 15 |
+
# scikit-learn 1.1 (not yet released at the time of writing), see:
|
| 16 |
+
# https://github.com/scikit-learn/scikit-learn/issues/22614
|
| 17 |
+
#
|
| 18 |
+
# To avoid unnecessary disruption for users who might update to joblib 1.2
|
| 19 |
+
# prior to a release of scikit-learn that includes the fix, let's keep on
|
| 20 |
+
# importing distutils here. TODO: Remove this for a future release of joblib,
|
| 21 |
+
# e.g. 6 months after the release of scikit-learn 1.1.
|
| 22 |
+
import distutils # noqa
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Version:
|
| 26 |
+
"""Backport from deprecated distutils
|
| 27 |
+
|
| 28 |
+
We maintain this backport to avoid introducing a new dependency on
|
| 29 |
+
`packaging`.
|
| 30 |
+
|
| 31 |
+
We might rexplore this choice in the future if all major Python projects
|
| 32 |
+
introduce a dependency on packaging anyway.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(self, vstring=None):
|
| 36 |
+
if vstring:
|
| 37 |
+
self.parse(vstring)
|
| 38 |
+
|
| 39 |
+
def __repr__(self):
|
| 40 |
+
return "%s ('%s')" % (self.__class__.__name__, str(self))
|
| 41 |
+
|
| 42 |
+
def __eq__(self, other):
|
| 43 |
+
c = self._cmp(other)
|
| 44 |
+
if c is NotImplemented:
|
| 45 |
+
return c
|
| 46 |
+
return c == 0
|
| 47 |
+
|
| 48 |
+
def __lt__(self, other):
|
| 49 |
+
c = self._cmp(other)
|
| 50 |
+
if c is NotImplemented:
|
| 51 |
+
return c
|
| 52 |
+
return c < 0
|
| 53 |
+
|
| 54 |
+
def __le__(self, other):
|
| 55 |
+
c = self._cmp(other)
|
| 56 |
+
if c is NotImplemented:
|
| 57 |
+
return c
|
| 58 |
+
return c <= 0
|
| 59 |
+
|
| 60 |
+
def __gt__(self, other):
|
| 61 |
+
c = self._cmp(other)
|
| 62 |
+
if c is NotImplemented:
|
| 63 |
+
return c
|
| 64 |
+
return c > 0
|
| 65 |
+
|
| 66 |
+
def __ge__(self, other):
|
| 67 |
+
c = self._cmp(other)
|
| 68 |
+
if c is NotImplemented:
|
| 69 |
+
return c
|
| 70 |
+
return c >= 0
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class LooseVersion(Version):
|
| 74 |
+
"""Backport from deprecated distutils
|
| 75 |
+
|
| 76 |
+
We maintain this backport to avoid introducing a new dependency on
|
| 77 |
+
`packaging`.
|
| 78 |
+
|
| 79 |
+
We might rexplore this choice in the future if all major Python projects
|
| 80 |
+
introduce a dependency on packaging anyway.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
|
| 84 |
+
|
| 85 |
+
def __init__(self, vstring=None):
|
| 86 |
+
if vstring:
|
| 87 |
+
self.parse(vstring)
|
| 88 |
+
|
| 89 |
+
def parse(self, vstring):
|
| 90 |
+
# I've given up on thinking I can reconstruct the version string
|
| 91 |
+
# from the parsed tuple -- so I just store the string here for
|
| 92 |
+
# use by __str__
|
| 93 |
+
self.vstring = vstring
|
| 94 |
+
components = [x for x in self.component_re.split(vstring)
|
| 95 |
+
if x and x != '.']
|
| 96 |
+
for i, obj in enumerate(components):
|
| 97 |
+
try:
|
| 98 |
+
components[i] = int(obj)
|
| 99 |
+
except ValueError:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
self.version = components
|
| 103 |
+
|
| 104 |
+
def __str__(self):
|
| 105 |
+
return self.vstring
|
| 106 |
+
|
| 107 |
+
def __repr__(self):
|
| 108 |
+
return "LooseVersion ('%s')" % str(self)
|
| 109 |
+
|
| 110 |
+
def _cmp(self, other):
|
| 111 |
+
if isinstance(other, str):
|
| 112 |
+
other = LooseVersion(other)
|
| 113 |
+
elif not isinstance(other, LooseVersion):
|
| 114 |
+
return NotImplemented
|
| 115 |
+
|
| 116 |
+
if self.version == other.version:
|
| 117 |
+
return 0
|
| 118 |
+
if self.version < other.version:
|
| 119 |
+
return -1
|
| 120 |
+
if self.version > other.version:
|
| 121 |
+
return 1
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
try:
|
| 125 |
+
import numpy as np
|
| 126 |
+
|
| 127 |
+
def make_memmap(filename, dtype='uint8', mode='r+', offset=0,
|
| 128 |
+
shape=None, order='C', unlink_on_gc_collect=False):
|
| 129 |
+
"""Custom memmap constructor compatible with numpy.memmap.
|
| 130 |
+
|
| 131 |
+
This function:
|
| 132 |
+
- is a backport the numpy memmap offset fix (See
|
| 133 |
+
https://github.com/numpy/numpy/pull/8443 for more details.
|
| 134 |
+
The numpy fix is available starting numpy 1.13)
|
| 135 |
+
- adds ``unlink_on_gc_collect``, which specifies explicitly whether
|
| 136 |
+
the process re-constructing the memmap owns a reference to the
|
| 137 |
+
underlying file. If set to True, it adds a finalizer to the
|
| 138 |
+
newly-created memmap that sends a maybe_unlink request for the
|
| 139 |
+
memmaped file to resource_tracker.
|
| 140 |
+
"""
|
| 141 |
+
util.debug(
|
| 142 |
+
"[MEMMAP READ] creating a memmap (shape {}, filename {}, "
|
| 143 |
+
"pid {})".format(shape, basename(filename), os.getpid())
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
mm = np.memmap(filename, dtype=dtype, mode=mode, offset=offset,
|
| 147 |
+
shape=shape, order=order)
|
| 148 |
+
if LooseVersion(np.__version__) < '1.13':
|
| 149 |
+
mm.offset = offset
|
| 150 |
+
if unlink_on_gc_collect:
|
| 151 |
+
from ._memmapping_reducer import add_maybe_unlink_finalizer
|
| 152 |
+
add_maybe_unlink_finalizer(mm)
|
| 153 |
+
return mm
|
| 154 |
+
except ImportError:
|
| 155 |
+
def make_memmap(filename, dtype='uint8', mode='r+', offset=0,
|
| 156 |
+
shape=None, order='C', unlink_on_gc_collect=False):
|
| 157 |
+
raise NotImplementedError(
|
| 158 |
+
"'joblib.backports.make_memmap' should not be used "
|
| 159 |
+
'if numpy is not installed.')
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
if os.name == 'nt':
|
| 163 |
+
# https://github.com/joblib/joblib/issues/540
|
| 164 |
+
access_denied_errors = (5, 13)
|
| 165 |
+
from os import replace
|
| 166 |
+
|
| 167 |
+
def concurrency_safe_rename(src, dst):
|
| 168 |
+
"""Renames ``src`` into ``dst`` overwriting ``dst`` if it exists.
|
| 169 |
+
|
| 170 |
+
On Windows os.replace can yield permission errors if executed by two
|
| 171 |
+
different processes.
|
| 172 |
+
"""
|
| 173 |
+
max_sleep_time = 1
|
| 174 |
+
total_sleep_time = 0
|
| 175 |
+
sleep_time = 0.001
|
| 176 |
+
while total_sleep_time < max_sleep_time:
|
| 177 |
+
try:
|
| 178 |
+
replace(src, dst)
|
| 179 |
+
break
|
| 180 |
+
except Exception as exc:
|
| 181 |
+
if getattr(exc, 'winerror', None) in access_denied_errors:
|
| 182 |
+
time.sleep(sleep_time)
|
| 183 |
+
total_sleep_time += sleep_time
|
| 184 |
+
sleep_time *= 2
|
| 185 |
+
else:
|
| 186 |
+
raise
|
| 187 |
+
else:
|
| 188 |
+
raise
|
| 189 |
+
else:
|
| 190 |
+
from os import replace as concurrency_safe_rename # noqa
|
runtime/Lib/site-packages/joblib/compressor.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classes and functions for managing compressors."""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import zlib
|
| 5 |
+
from joblib.backports import LooseVersion
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from threading import RLock
|
| 9 |
+
except ImportError:
|
| 10 |
+
from dummy_threading import RLock
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
import bz2
|
| 14 |
+
except ImportError:
|
| 15 |
+
bz2 = None
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
import lz4
|
| 19 |
+
from lz4.frame import LZ4FrameFile
|
| 20 |
+
except ImportError:
|
| 21 |
+
lz4 = None
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import lzma
|
| 25 |
+
except ImportError:
|
| 26 |
+
lzma = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
LZ4_NOT_INSTALLED_ERROR = ('LZ4 is not installed. Install it with pip: '
|
| 30 |
+
'https://python-lz4.readthedocs.io/')
|
| 31 |
+
|
| 32 |
+
# Registered compressors
|
| 33 |
+
_COMPRESSORS = {}
|
| 34 |
+
|
| 35 |
+
# Magic numbers of supported compression file formats.
|
| 36 |
+
_ZFILE_PREFIX = b'ZF' # used with pickle files created before 0.9.3.
|
| 37 |
+
_ZLIB_PREFIX = b'\x78'
|
| 38 |
+
_GZIP_PREFIX = b'\x1f\x8b'
|
| 39 |
+
_BZ2_PREFIX = b'BZ'
|
| 40 |
+
_XZ_PREFIX = b'\xfd\x37\x7a\x58\x5a'
|
| 41 |
+
_LZMA_PREFIX = b'\x5d\x00'
|
| 42 |
+
_LZ4_PREFIX = b'\x04\x22\x4D\x18'
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def register_compressor(compressor_name, compressor,
|
| 46 |
+
force=False):
|
| 47 |
+
"""Register a new compressor.
|
| 48 |
+
|
| 49 |
+
Parameters
|
| 50 |
+
-----------
|
| 51 |
+
compressor_name: str.
|
| 52 |
+
The name of the compressor.
|
| 53 |
+
compressor: CompressorWrapper
|
| 54 |
+
An instance of a 'CompressorWrapper'.
|
| 55 |
+
"""
|
| 56 |
+
global _COMPRESSORS
|
| 57 |
+
if not isinstance(compressor_name, str):
|
| 58 |
+
raise ValueError("Compressor name should be a string, "
|
| 59 |
+
"'{}' given.".format(compressor_name))
|
| 60 |
+
|
| 61 |
+
if not isinstance(compressor, CompressorWrapper):
|
| 62 |
+
raise ValueError("Compressor should implement the CompressorWrapper "
|
| 63 |
+
"interface, '{}' given.".format(compressor))
|
| 64 |
+
|
| 65 |
+
if (compressor.fileobj_factory is not None and
|
| 66 |
+
(not hasattr(compressor.fileobj_factory, 'read') or
|
| 67 |
+
not hasattr(compressor.fileobj_factory, 'write') or
|
| 68 |
+
not hasattr(compressor.fileobj_factory, 'seek') or
|
| 69 |
+
not hasattr(compressor.fileobj_factory, 'tell'))):
|
| 70 |
+
raise ValueError("Compressor 'fileobj_factory' attribute should "
|
| 71 |
+
"implement the file object interface, '{}' given."
|
| 72 |
+
.format(compressor.fileobj_factory))
|
| 73 |
+
|
| 74 |
+
if compressor_name in _COMPRESSORS and not force:
|
| 75 |
+
raise ValueError("Compressor '{}' already registered."
|
| 76 |
+
.format(compressor_name))
|
| 77 |
+
|
| 78 |
+
_COMPRESSORS[compressor_name] = compressor
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class CompressorWrapper():
|
| 82 |
+
"""A wrapper around a compressor file object.
|
| 83 |
+
|
| 84 |
+
Attributes
|
| 85 |
+
----------
|
| 86 |
+
obj: a file-like object
|
| 87 |
+
The object must implement the buffer interface and will be used
|
| 88 |
+
internally to compress/decompress the data.
|
| 89 |
+
prefix: bytestring
|
| 90 |
+
A bytestring corresponding to the magic number that identifies the
|
| 91 |
+
file format associated to the compressor.
|
| 92 |
+
extension: str
|
| 93 |
+
The file extension used to automatically select this compressor during
|
| 94 |
+
a dump to a file.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
def __init__(self, obj, prefix=b'', extension=''):
|
| 98 |
+
self.fileobj_factory = obj
|
| 99 |
+
self.prefix = prefix
|
| 100 |
+
self.extension = extension
|
| 101 |
+
|
| 102 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 103 |
+
"""Returns an instance of a compressor file object."""
|
| 104 |
+
if compresslevel is None:
|
| 105 |
+
return self.fileobj_factory(fileobj, 'wb')
|
| 106 |
+
else:
|
| 107 |
+
return self.fileobj_factory(fileobj, 'wb',
|
| 108 |
+
compresslevel=compresslevel)
|
| 109 |
+
|
| 110 |
+
def decompressor_file(self, fileobj):
|
| 111 |
+
"""Returns an instance of a decompressor file object."""
|
| 112 |
+
return self.fileobj_factory(fileobj, 'rb')
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class BZ2CompressorWrapper(CompressorWrapper):
|
| 116 |
+
|
| 117 |
+
prefix = _BZ2_PREFIX
|
| 118 |
+
extension = '.bz2'
|
| 119 |
+
|
| 120 |
+
def __init__(self):
|
| 121 |
+
if bz2 is not None:
|
| 122 |
+
self.fileobj_factory = bz2.BZ2File
|
| 123 |
+
else:
|
| 124 |
+
self.fileobj_factory = None
|
| 125 |
+
|
| 126 |
+
def _check_versions(self):
|
| 127 |
+
if bz2 is None:
|
| 128 |
+
raise ValueError('bz2 module is not compiled on your python '
|
| 129 |
+
'standard library.')
|
| 130 |
+
|
| 131 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 132 |
+
"""Returns an instance of a compressor file object."""
|
| 133 |
+
self._check_versions()
|
| 134 |
+
if compresslevel is None:
|
| 135 |
+
return self.fileobj_factory(fileobj, 'wb')
|
| 136 |
+
else:
|
| 137 |
+
return self.fileobj_factory(fileobj, 'wb',
|
| 138 |
+
compresslevel=compresslevel)
|
| 139 |
+
|
| 140 |
+
def decompressor_file(self, fileobj):
|
| 141 |
+
"""Returns an instance of a decompressor file object."""
|
| 142 |
+
self._check_versions()
|
| 143 |
+
fileobj = self.fileobj_factory(fileobj, 'rb')
|
| 144 |
+
return fileobj
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class LZMACompressorWrapper(CompressorWrapper):
|
| 148 |
+
|
| 149 |
+
prefix = _LZMA_PREFIX
|
| 150 |
+
extension = '.lzma'
|
| 151 |
+
_lzma_format_name = 'FORMAT_ALONE'
|
| 152 |
+
|
| 153 |
+
def __init__(self):
|
| 154 |
+
if lzma is not None:
|
| 155 |
+
self.fileobj_factory = lzma.LZMAFile
|
| 156 |
+
self._lzma_format = getattr(lzma, self._lzma_format_name)
|
| 157 |
+
else:
|
| 158 |
+
self.fileobj_factory = None
|
| 159 |
+
|
| 160 |
+
def _check_versions(self):
|
| 161 |
+
if lzma is None:
|
| 162 |
+
raise ValueError('lzma module is not compiled on your python '
|
| 163 |
+
'standard library.')
|
| 164 |
+
|
| 165 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 166 |
+
"""Returns an instance of a compressor file object."""
|
| 167 |
+
if compresslevel is None:
|
| 168 |
+
return self.fileobj_factory(fileobj, 'wb',
|
| 169 |
+
format=self._lzma_format)
|
| 170 |
+
else:
|
| 171 |
+
return self.fileobj_factory(fileobj, 'wb',
|
| 172 |
+
format=self._lzma_format,
|
| 173 |
+
preset=compresslevel)
|
| 174 |
+
|
| 175 |
+
def decompressor_file(self, fileobj):
|
| 176 |
+
"""Returns an instance of a decompressor file object."""
|
| 177 |
+
return lzma.LZMAFile(fileobj, 'rb')
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class XZCompressorWrapper(LZMACompressorWrapper):
|
| 181 |
+
|
| 182 |
+
prefix = _XZ_PREFIX
|
| 183 |
+
extension = '.xz'
|
| 184 |
+
_lzma_format_name = 'FORMAT_XZ'
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class LZ4CompressorWrapper(CompressorWrapper):
|
| 188 |
+
|
| 189 |
+
prefix = _LZ4_PREFIX
|
| 190 |
+
extension = '.lz4'
|
| 191 |
+
|
| 192 |
+
def __init__(self):
|
| 193 |
+
if lz4 is not None:
|
| 194 |
+
self.fileobj_factory = LZ4FrameFile
|
| 195 |
+
else:
|
| 196 |
+
self.fileobj_factory = None
|
| 197 |
+
|
| 198 |
+
def _check_versions(self):
|
| 199 |
+
if lz4 is None:
|
| 200 |
+
raise ValueError(LZ4_NOT_INSTALLED_ERROR)
|
| 201 |
+
lz4_version = lz4.__version__
|
| 202 |
+
if lz4_version.startswith("v"):
|
| 203 |
+
lz4_version = lz4_version[1:]
|
| 204 |
+
if LooseVersion(lz4_version) < LooseVersion('0.19'):
|
| 205 |
+
raise ValueError(LZ4_NOT_INSTALLED_ERROR)
|
| 206 |
+
|
| 207 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 208 |
+
"""Returns an instance of a compressor file object."""
|
| 209 |
+
self._check_versions()
|
| 210 |
+
if compresslevel is None:
|
| 211 |
+
return self.fileobj_factory(fileobj, 'wb')
|
| 212 |
+
else:
|
| 213 |
+
return self.fileobj_factory(fileobj, 'wb',
|
| 214 |
+
compression_level=compresslevel)
|
| 215 |
+
|
| 216 |
+
def decompressor_file(self, fileobj):
|
| 217 |
+
"""Returns an instance of a decompressor file object."""
|
| 218 |
+
self._check_versions()
|
| 219 |
+
return self.fileobj_factory(fileobj, 'rb')
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
###############################################################################
|
| 223 |
+
# base file compression/decompression object definition
|
| 224 |
+
_MODE_CLOSED = 0
|
| 225 |
+
_MODE_READ = 1
|
| 226 |
+
_MODE_READ_EOF = 2
|
| 227 |
+
_MODE_WRITE = 3
|
| 228 |
+
_BUFFER_SIZE = 8192
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class BinaryZlibFile(io.BufferedIOBase):
|
| 232 |
+
"""A file object providing transparent zlib (de)compression.
|
| 233 |
+
|
| 234 |
+
TODO python2_drop: is it still needed since we dropped Python 2 support A
|
| 235 |
+
BinaryZlibFile can act as a wrapper for an existing file object, or refer
|
| 236 |
+
directly to a named file on disk.
|
| 237 |
+
|
| 238 |
+
Note that BinaryZlibFile provides only a *binary* file interface: data read
|
| 239 |
+
is returned as bytes, and data to be written should be given as bytes.
|
| 240 |
+
|
| 241 |
+
This object is an adaptation of the BZ2File object and is compatible with
|
| 242 |
+
versions of python >= 2.7.
|
| 243 |
+
|
| 244 |
+
If filename is a str or bytes object, it gives the name
|
| 245 |
+
of the file to be opened. Otherwise, it should be a file object,
|
| 246 |
+
which will be used to read or write the compressed data.
|
| 247 |
+
|
| 248 |
+
mode can be 'rb' for reading (default) or 'wb' for (over)writing
|
| 249 |
+
|
| 250 |
+
If mode is 'wb', compresslevel can be a number between 1
|
| 251 |
+
and 9 specifying the level of compression: 1 produces the least
|
| 252 |
+
compression, and 9 produces the most compression. 3 is the default.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
wbits = zlib.MAX_WBITS
|
| 256 |
+
|
| 257 |
+
def __init__(self, filename, mode="rb", compresslevel=3):
|
| 258 |
+
# This lock must be recursive, so that BufferedIOBase's
|
| 259 |
+
# readline(), readlines() and writelines() don't deadlock.
|
| 260 |
+
self._lock = RLock()
|
| 261 |
+
self._fp = None
|
| 262 |
+
self._closefp = False
|
| 263 |
+
self._mode = _MODE_CLOSED
|
| 264 |
+
self._pos = 0
|
| 265 |
+
self._size = -1
|
| 266 |
+
self.compresslevel = compresslevel
|
| 267 |
+
|
| 268 |
+
if not isinstance(compresslevel, int) or not (1 <= compresslevel <= 9):
|
| 269 |
+
raise ValueError("'compresslevel' must be an integer "
|
| 270 |
+
"between 1 and 9. You provided 'compresslevel={}'"
|
| 271 |
+
.format(compresslevel))
|
| 272 |
+
|
| 273 |
+
if mode == "rb":
|
| 274 |
+
self._mode = _MODE_READ
|
| 275 |
+
self._decompressor = zlib.decompressobj(self.wbits)
|
| 276 |
+
self._buffer = b""
|
| 277 |
+
self._buffer_offset = 0
|
| 278 |
+
elif mode == "wb":
|
| 279 |
+
self._mode = _MODE_WRITE
|
| 280 |
+
self._compressor = zlib.compressobj(self.compresslevel,
|
| 281 |
+
zlib.DEFLATED, self.wbits,
|
| 282 |
+
zlib.DEF_MEM_LEVEL, 0)
|
| 283 |
+
else:
|
| 284 |
+
raise ValueError("Invalid mode: %r" % (mode,))
|
| 285 |
+
|
| 286 |
+
if isinstance(filename, str):
|
| 287 |
+
self._fp = io.open(filename, mode)
|
| 288 |
+
self._closefp = True
|
| 289 |
+
elif hasattr(filename, "read") or hasattr(filename, "write"):
|
| 290 |
+
self._fp = filename
|
| 291 |
+
else:
|
| 292 |
+
raise TypeError("filename must be a str or bytes object, "
|
| 293 |
+
"or a file")
|
| 294 |
+
|
| 295 |
+
def close(self):
|
| 296 |
+
"""Flush and close the file.
|
| 297 |
+
|
| 298 |
+
May be called more than once without error. Once the file is
|
| 299 |
+
closed, any other operation on it will raise a ValueError.
|
| 300 |
+
"""
|
| 301 |
+
with self._lock:
|
| 302 |
+
if self._mode == _MODE_CLOSED:
|
| 303 |
+
return
|
| 304 |
+
try:
|
| 305 |
+
if self._mode in (_MODE_READ, _MODE_READ_EOF):
|
| 306 |
+
self._decompressor = None
|
| 307 |
+
elif self._mode == _MODE_WRITE:
|
| 308 |
+
self._fp.write(self._compressor.flush())
|
| 309 |
+
self._compressor = None
|
| 310 |
+
finally:
|
| 311 |
+
try:
|
| 312 |
+
if self._closefp:
|
| 313 |
+
self._fp.close()
|
| 314 |
+
finally:
|
| 315 |
+
self._fp = None
|
| 316 |
+
self._closefp = False
|
| 317 |
+
self._mode = _MODE_CLOSED
|
| 318 |
+
self._buffer = b""
|
| 319 |
+
self._buffer_offset = 0
|
| 320 |
+
|
| 321 |
+
@property
|
| 322 |
+
def closed(self):
|
| 323 |
+
"""True if this file is closed."""
|
| 324 |
+
return self._mode == _MODE_CLOSED
|
| 325 |
+
|
| 326 |
+
def fileno(self):
|
| 327 |
+
"""Return the file descriptor for the underlying file."""
|
| 328 |
+
self._check_not_closed()
|
| 329 |
+
return self._fp.fileno()
|
| 330 |
+
|
| 331 |
+
def seekable(self):
|
| 332 |
+
"""Return whether the file supports seeking."""
|
| 333 |
+
return self.readable() and self._fp.seekable()
|
| 334 |
+
|
| 335 |
+
def readable(self):
|
| 336 |
+
"""Return whether the file was opened for reading."""
|
| 337 |
+
self._check_not_closed()
|
| 338 |
+
return self._mode in (_MODE_READ, _MODE_READ_EOF)
|
| 339 |
+
|
| 340 |
+
def writable(self):
|
| 341 |
+
"""Return whether the file was opened for writing."""
|
| 342 |
+
self._check_not_closed()
|
| 343 |
+
return self._mode == _MODE_WRITE
|
| 344 |
+
|
| 345 |
+
# Mode-checking helper functions.
|
| 346 |
+
|
| 347 |
+
def _check_not_closed(self):
|
| 348 |
+
if self.closed:
|
| 349 |
+
fname = getattr(self._fp, 'name', None)
|
| 350 |
+
msg = "I/O operation on closed file"
|
| 351 |
+
if fname is not None:
|
| 352 |
+
msg += " {}".format(fname)
|
| 353 |
+
msg += "."
|
| 354 |
+
raise ValueError(msg)
|
| 355 |
+
|
| 356 |
+
def _check_can_read(self):
|
| 357 |
+
if self._mode not in (_MODE_READ, _MODE_READ_EOF):
|
| 358 |
+
self._check_not_closed()
|
| 359 |
+
raise io.UnsupportedOperation("File not open for reading")
|
| 360 |
+
|
| 361 |
+
def _check_can_write(self):
|
| 362 |
+
if self._mode != _MODE_WRITE:
|
| 363 |
+
self._check_not_closed()
|
| 364 |
+
raise io.UnsupportedOperation("File not open for writing")
|
| 365 |
+
|
| 366 |
+
def _check_can_seek(self):
|
| 367 |
+
if self._mode not in (_MODE_READ, _MODE_READ_EOF):
|
| 368 |
+
self._check_not_closed()
|
| 369 |
+
raise io.UnsupportedOperation("Seeking is only supported "
|
| 370 |
+
"on files open for reading")
|
| 371 |
+
if not self._fp.seekable():
|
| 372 |
+
raise io.UnsupportedOperation("The underlying file object "
|
| 373 |
+
"does not support seeking")
|
| 374 |
+
|
| 375 |
+
# Fill the readahead buffer if it is empty. Returns False on EOF.
|
| 376 |
+
def _fill_buffer(self):
|
| 377 |
+
if self._mode == _MODE_READ_EOF:
|
| 378 |
+
return False
|
| 379 |
+
# Depending on the input data, our call to the decompressor may not
|
| 380 |
+
# return any data. In this case, try again after reading another block.
|
| 381 |
+
while self._buffer_offset == len(self._buffer):
|
| 382 |
+
try:
|
| 383 |
+
rawblock = (self._decompressor.unused_data or
|
| 384 |
+
self._fp.read(_BUFFER_SIZE))
|
| 385 |
+
if not rawblock:
|
| 386 |
+
raise EOFError
|
| 387 |
+
except EOFError:
|
| 388 |
+
# End-of-stream marker and end of file. We're good.
|
| 389 |
+
self._mode = _MODE_READ_EOF
|
| 390 |
+
self._size = self._pos
|
| 391 |
+
return False
|
| 392 |
+
else:
|
| 393 |
+
self._buffer = self._decompressor.decompress(rawblock)
|
| 394 |
+
self._buffer_offset = 0
|
| 395 |
+
return True
|
| 396 |
+
|
| 397 |
+
# Read data until EOF.
|
| 398 |
+
# If return_data is false, consume the data without returning it.
|
| 399 |
+
def _read_all(self, return_data=True):
|
| 400 |
+
# The loop assumes that _buffer_offset is 0. Ensure that this is true.
|
| 401 |
+
self._buffer = self._buffer[self._buffer_offset:]
|
| 402 |
+
self._buffer_offset = 0
|
| 403 |
+
|
| 404 |
+
blocks = []
|
| 405 |
+
while self._fill_buffer():
|
| 406 |
+
if return_data:
|
| 407 |
+
blocks.append(self._buffer)
|
| 408 |
+
self._pos += len(self._buffer)
|
| 409 |
+
self._buffer = b""
|
| 410 |
+
if return_data:
|
| 411 |
+
return b"".join(blocks)
|
| 412 |
+
|
| 413 |
+
# Read a block of up to n bytes.
|
| 414 |
+
# If return_data is false, consume the data without returning it.
|
| 415 |
+
def _read_block(self, n_bytes, return_data=True):
|
| 416 |
+
# If we have enough data buffered, return immediately.
|
| 417 |
+
end = self._buffer_offset + n_bytes
|
| 418 |
+
if end <= len(self._buffer):
|
| 419 |
+
data = self._buffer[self._buffer_offset: end]
|
| 420 |
+
self._buffer_offset = end
|
| 421 |
+
self._pos += len(data)
|
| 422 |
+
return data if return_data else None
|
| 423 |
+
|
| 424 |
+
# The loop assumes that _buffer_offset is 0. Ensure that this is true.
|
| 425 |
+
self._buffer = self._buffer[self._buffer_offset:]
|
| 426 |
+
self._buffer_offset = 0
|
| 427 |
+
|
| 428 |
+
blocks = []
|
| 429 |
+
while n_bytes > 0 and self._fill_buffer():
|
| 430 |
+
if n_bytes < len(self._buffer):
|
| 431 |
+
data = self._buffer[:n_bytes]
|
| 432 |
+
self._buffer_offset = n_bytes
|
| 433 |
+
else:
|
| 434 |
+
data = self._buffer
|
| 435 |
+
self._buffer = b""
|
| 436 |
+
if return_data:
|
| 437 |
+
blocks.append(data)
|
| 438 |
+
self._pos += len(data)
|
| 439 |
+
n_bytes -= len(data)
|
| 440 |
+
if return_data:
|
| 441 |
+
return b"".join(blocks)
|
| 442 |
+
|
| 443 |
+
def read(self, size=-1):
|
| 444 |
+
"""Read up to size uncompressed bytes from the file.
|
| 445 |
+
|
| 446 |
+
If size is negative or omitted, read until EOF is reached.
|
| 447 |
+
Returns b'' if the file is already at EOF.
|
| 448 |
+
"""
|
| 449 |
+
with self._lock:
|
| 450 |
+
self._check_can_read()
|
| 451 |
+
if size == 0:
|
| 452 |
+
return b""
|
| 453 |
+
elif size < 0:
|
| 454 |
+
return self._read_all()
|
| 455 |
+
else:
|
| 456 |
+
return self._read_block(size)
|
| 457 |
+
|
| 458 |
+
def readinto(self, b):
|
| 459 |
+
"""Read up to len(b) bytes into b.
|
| 460 |
+
|
| 461 |
+
Returns the number of bytes read (0 for EOF).
|
| 462 |
+
"""
|
| 463 |
+
with self._lock:
|
| 464 |
+
return io.BufferedIOBase.readinto(self, b)
|
| 465 |
+
|
| 466 |
+
def write(self, data):
|
| 467 |
+
"""Write a byte string to the file.
|
| 468 |
+
|
| 469 |
+
Returns the number of uncompressed bytes written, which is
|
| 470 |
+
always len(data). Note that due to buffering, the file on disk
|
| 471 |
+
may not reflect the data written until close() is called.
|
| 472 |
+
"""
|
| 473 |
+
with self._lock:
|
| 474 |
+
self._check_can_write()
|
| 475 |
+
# Convert data type if called by io.BufferedWriter.
|
| 476 |
+
if isinstance(data, memoryview):
|
| 477 |
+
data = data.tobytes()
|
| 478 |
+
|
| 479 |
+
compressed = self._compressor.compress(data)
|
| 480 |
+
self._fp.write(compressed)
|
| 481 |
+
self._pos += len(data)
|
| 482 |
+
return len(data)
|
| 483 |
+
|
| 484 |
+
# Rewind the file to the beginning of the data stream.
|
| 485 |
+
def _rewind(self):
|
| 486 |
+
self._fp.seek(0, 0)
|
| 487 |
+
self._mode = _MODE_READ
|
| 488 |
+
self._pos = 0
|
| 489 |
+
self._decompressor = zlib.decompressobj(self.wbits)
|
| 490 |
+
self._buffer = b""
|
| 491 |
+
self._buffer_offset = 0
|
| 492 |
+
|
| 493 |
+
def seek(self, offset, whence=0):
|
| 494 |
+
"""Change the file position.
|
| 495 |
+
|
| 496 |
+
The new position is specified by offset, relative to the
|
| 497 |
+
position indicated by whence. Values for whence are:
|
| 498 |
+
|
| 499 |
+
0: start of stream (default); offset must not be negative
|
| 500 |
+
1: current stream position
|
| 501 |
+
2: end of stream; offset must not be positive
|
| 502 |
+
|
| 503 |
+
Returns the new file position.
|
| 504 |
+
|
| 505 |
+
Note that seeking is emulated, so depending on the parameters,
|
| 506 |
+
this operation may be extremely slow.
|
| 507 |
+
"""
|
| 508 |
+
with self._lock:
|
| 509 |
+
self._check_can_seek()
|
| 510 |
+
|
| 511 |
+
# Recalculate offset as an absolute file position.
|
| 512 |
+
if whence == 0:
|
| 513 |
+
pass
|
| 514 |
+
elif whence == 1:
|
| 515 |
+
offset = self._pos + offset
|
| 516 |
+
elif whence == 2:
|
| 517 |
+
# Seeking relative to EOF - we need to know the file's size.
|
| 518 |
+
if self._size < 0:
|
| 519 |
+
self._read_all(return_data=False)
|
| 520 |
+
offset = self._size + offset
|
| 521 |
+
else:
|
| 522 |
+
raise ValueError("Invalid value for whence: %s" % (whence,))
|
| 523 |
+
|
| 524 |
+
# Make it so that offset is the number of bytes to skip forward.
|
| 525 |
+
if offset < self._pos:
|
| 526 |
+
self._rewind()
|
| 527 |
+
else:
|
| 528 |
+
offset -= self._pos
|
| 529 |
+
|
| 530 |
+
# Read and discard data until we reach the desired position.
|
| 531 |
+
self._read_block(offset, return_data=False)
|
| 532 |
+
|
| 533 |
+
return self._pos
|
| 534 |
+
|
| 535 |
+
def tell(self):
|
| 536 |
+
"""Return the current file position."""
|
| 537 |
+
with self._lock:
|
| 538 |
+
self._check_not_closed()
|
| 539 |
+
return self._pos
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class ZlibCompressorWrapper(CompressorWrapper):
|
| 543 |
+
|
| 544 |
+
def __init__(self):
|
| 545 |
+
CompressorWrapper.__init__(self, obj=BinaryZlibFile,
|
| 546 |
+
prefix=_ZLIB_PREFIX, extension='.z')
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class BinaryGzipFile(BinaryZlibFile):
|
| 550 |
+
"""A file object providing transparent gzip (de)compression.
|
| 551 |
+
|
| 552 |
+
If filename is a str or bytes object, it gives the name
|
| 553 |
+
of the file to be opened. Otherwise, it should be a file object,
|
| 554 |
+
which will be used to read or write the compressed data.
|
| 555 |
+
|
| 556 |
+
mode can be 'rb' for reading (default) or 'wb' for (over)writing
|
| 557 |
+
|
| 558 |
+
If mode is 'wb', compresslevel can be a number between 1
|
| 559 |
+
and 9 specifying the level of compression: 1 produces the least
|
| 560 |
+
compression, and 9 produces the most compression. 3 is the default.
|
| 561 |
+
"""
|
| 562 |
+
|
| 563 |
+
wbits = 31 # zlib compressor/decompressor wbits value for gzip format.
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class GzipCompressorWrapper(CompressorWrapper):
|
| 567 |
+
|
| 568 |
+
def __init__(self):
|
| 569 |
+
CompressorWrapper.__init__(self, obj=BinaryGzipFile,
|
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7 |
+
# Copyright (c) 2010 Gael Varoquaux
|
| 8 |
+
# License: BSD Style, 3 clauses.
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
import errno
|
| 15 |
+
import shutil
|
| 16 |
+
|
| 17 |
+
from multiprocessing import util
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
WindowsError
|
| 22 |
+
except NameError:
|
| 23 |
+
WindowsError = OSError
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def disk_used(path):
|
| 27 |
+
""" Return the disk usage in a directory."""
|
| 28 |
+
size = 0
|
| 29 |
+
for file in os.listdir(path) + ['.']:
|
| 30 |
+
stat = os.stat(os.path.join(path, file))
|
| 31 |
+
if hasattr(stat, 'st_blocks'):
|
| 32 |
+
size += stat.st_blocks * 512
|
| 33 |
+
else:
|
| 34 |
+
# on some platform st_blocks is not available (e.g., Windows)
|
| 35 |
+
# approximate by rounding to next multiple of 512
|
| 36 |
+
size += (stat.st_size // 512 + 1) * 512
|
| 37 |
+
# We need to convert to int to avoid having longs on some systems (we
|
| 38 |
+
# don't want longs to avoid problems we SQLite)
|
| 39 |
+
return int(size / 1024.)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def memstr_to_bytes(text):
|
| 43 |
+
""" Convert a memory text to its value in bytes.
|
| 44 |
+
"""
|
| 45 |
+
kilo = 1024
|
| 46 |
+
units = dict(K=kilo, M=kilo ** 2, G=kilo ** 3)
|
| 47 |
+
try:
|
| 48 |
+
size = int(units[text[-1]] * float(text[:-1]))
|
| 49 |
+
except (KeyError, ValueError) as e:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"Invalid literal for size give: %s (type %s) should be "
|
| 52 |
+
"alike '10G', '500M', '50K'." % (text, type(text))) from e
|
| 53 |
+
return size
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def mkdirp(d):
|
| 57 |
+
"""Ensure directory d exists (like mkdir -p on Unix)
|
| 58 |
+
No guarantee that the directory is writable.
|
| 59 |
+
"""
|
| 60 |
+
try:
|
| 61 |
+
os.makedirs(d)
|
| 62 |
+
except OSError as e:
|
| 63 |
+
if e.errno != errno.EEXIST:
|
| 64 |
+
raise
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# if a rmtree operation fails in rm_subdirs, wait for this much time (in secs),
|
| 68 |
+
# then retry up to RM_SUBDIRS_N_RETRY times. If it still fails, raise the
|
| 69 |
+
# exception. this mechanism ensures that the sub-process gc have the time to
|
| 70 |
+
# collect and close the memmaps before we fail.
|
| 71 |
+
RM_SUBDIRS_RETRY_TIME = 0.1
|
| 72 |
+
RM_SUBDIRS_N_RETRY = 10
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def rm_subdirs(path, onerror=None):
|
| 76 |
+
"""Remove all subdirectories in this path.
|
| 77 |
+
|
| 78 |
+
The directory indicated by `path` is left in place, and its subdirectories
|
| 79 |
+
are erased.
|
| 80 |
+
|
| 81 |
+
If onerror is set, it is called to handle the error with arguments (func,
|
| 82 |
+
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
|
| 83 |
+
path is the argument to that function that caused it to fail; and
|
| 84 |
+
exc_info is a tuple returned by sys.exc_info(). If onerror is None,
|
| 85 |
+
an exception is raised.
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
# NOTE this code is adapted from the one in shutil.rmtree, and is
|
| 89 |
+
# just as fast
|
| 90 |
+
|
| 91 |
+
names = []
|
| 92 |
+
try:
|
| 93 |
+
names = os.listdir(path)
|
| 94 |
+
except os.error:
|
| 95 |
+
if onerror is not None:
|
| 96 |
+
onerror(os.listdir, path, sys.exc_info())
|
| 97 |
+
else:
|
| 98 |
+
raise
|
| 99 |
+
|
| 100 |
+
for name in names:
|
| 101 |
+
fullname = os.path.join(path, name)
|
| 102 |
+
delete_folder(fullname, onerror=onerror)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def delete_folder(folder_path, onerror=None, allow_non_empty=True):
|
| 106 |
+
"""Utility function to cleanup a temporary folder if it still exists."""
|
| 107 |
+
if os.path.isdir(folder_path):
|
| 108 |
+
if onerror is not None:
|
| 109 |
+
shutil.rmtree(folder_path, False, onerror)
|
| 110 |
+
else:
|
| 111 |
+
# allow the rmtree to fail once, wait and re-try.
|
| 112 |
+
# if the error is raised again, fail
|
| 113 |
+
err_count = 0
|
| 114 |
+
while True:
|
| 115 |
+
files = os.listdir(folder_path)
|
| 116 |
+
try:
|
| 117 |
+
if len(files) == 0 or allow_non_empty:
|
| 118 |
+
shutil.rmtree(
|
| 119 |
+
folder_path, ignore_errors=False, onerror=None
|
| 120 |
+
)
|
| 121 |
+
util.debug(
|
| 122 |
+
"Successfully deleted {}".format(folder_path))
|
| 123 |
+
break
|
| 124 |
+
else:
|
| 125 |
+
raise OSError(
|
| 126 |
+
"Expected empty folder {} but got {} "
|
| 127 |
+
"files.".format(folder_path, len(files))
|
| 128 |
+
)
|
| 129 |
+
except (OSError, WindowsError):
|
| 130 |
+
err_count += 1
|
| 131 |
+
if err_count > RM_SUBDIRS_N_RETRY:
|
| 132 |
+
# the folder cannot be deleted right now. It maybe
|
| 133 |
+
# because some temporary files have not been deleted
|
| 134 |
+
# yet.
|
| 135 |
+
raise
|
| 136 |
+
time.sleep(RM_SUBDIRS_RETRY_TIME)
|
runtime/Lib/site-packages/joblib/executor.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility function to construct a loky.ReusableExecutor with custom pickler.
|
| 2 |
+
|
| 3 |
+
This module provides efficient ways of working with data stored in
|
| 4 |
+
shared memory with numpy.memmap arrays without inducing any memory
|
| 5 |
+
copy between the parent and child processes.
|
| 6 |
+
"""
|
| 7 |
+
# Author: Thomas Moreau <thomas.moreau.2010@gmail.com>
|
| 8 |
+
# Copyright: 2017, Thomas Moreau
|
| 9 |
+
# License: BSD 3 clause
|
| 10 |
+
|
| 11 |
+
from ._memmapping_reducer import get_memmapping_reducers
|
| 12 |
+
from ._memmapping_reducer import TemporaryResourcesManager
|
| 13 |
+
from .externals.loky.reusable_executor import _ReusablePoolExecutor
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_executor_args = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_memmapping_executor(n_jobs, **kwargs):
|
| 20 |
+
return MemmappingExecutor.get_memmapping_executor(n_jobs, **kwargs)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class MemmappingExecutor(_ReusablePoolExecutor):
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def get_memmapping_executor(cls, n_jobs, timeout=300, initializer=None,
|
| 27 |
+
initargs=(), env=None, temp_folder=None,
|
| 28 |
+
context_id=None, **backend_args):
|
| 29 |
+
"""Factory for ReusableExecutor with automatic memmapping for large numpy
|
| 30 |
+
arrays.
|
| 31 |
+
"""
|
| 32 |
+
global _executor_args
|
| 33 |
+
# Check if we can reuse the executor here instead of deferring the test
|
| 34 |
+
# to loky as the reducers are objects that changes at each call.
|
| 35 |
+
executor_args = backend_args.copy()
|
| 36 |
+
executor_args.update(env if env else {})
|
| 37 |
+
executor_args.update(dict(
|
| 38 |
+
timeout=timeout, initializer=initializer, initargs=initargs))
|
| 39 |
+
reuse = _executor_args is None or _executor_args == executor_args
|
| 40 |
+
_executor_args = executor_args
|
| 41 |
+
|
| 42 |
+
manager = TemporaryResourcesManager(temp_folder)
|
| 43 |
+
|
| 44 |
+
# reducers access the temporary folder in which to store temporary
|
| 45 |
+
# pickles through a call to manager.resolve_temp_folder_name. resolving
|
| 46 |
+
# the folder name dynamically is useful to use different folders across
|
| 47 |
+
# calls of a same reusable executor
|
| 48 |
+
job_reducers, result_reducers = get_memmapping_reducers(
|
| 49 |
+
unlink_on_gc_collect=True,
|
| 50 |
+
temp_folder_resolver=manager.resolve_temp_folder_name,
|
| 51 |
+
**backend_args)
|
| 52 |
+
_executor, executor_is_reused = super().get_reusable_executor(
|
| 53 |
+
n_jobs, job_reducers=job_reducers, result_reducers=result_reducers,
|
| 54 |
+
reuse=reuse, timeout=timeout, initializer=initializer,
|
| 55 |
+
initargs=initargs, env=env
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
if not executor_is_reused:
|
| 59 |
+
# Only set a _temp_folder_manager for new executors. Reused
|
| 60 |
+
# executors already have a _temporary_folder_manager that must not
|
| 61 |
+
# be re-assigned like that because it is referenced in various
|
| 62 |
+
# places in the reducing machinery of the executor.
|
| 63 |
+
_executor._temp_folder_manager = manager
|
| 64 |
+
|
| 65 |
+
if context_id is not None:
|
| 66 |
+
# Only register the specified context once we know which manager
|
| 67 |
+
# the current executor is using, in order to not register an atexit
|
| 68 |
+
# finalizer twice for the same folder.
|
| 69 |
+
_executor._temp_folder_manager.register_new_context(context_id)
|
| 70 |
+
|
| 71 |
+
return _executor
|
| 72 |
+
|
| 73 |
+
def terminate(self, kill_workers=False):
|
| 74 |
+
self.shutdown(kill_workers=kill_workers)
|
| 75 |
+
if kill_workers:
|
| 76 |
+
# When workers are killed in such a brutal manner, they cannot
|
| 77 |
+
# execute the finalizer of their shared memmaps. The refcount of
|
| 78 |
+
# those memmaps may be off by an unknown number, so instead of
|
| 79 |
+
# decref'ing them, we delete the whole temporary folder, and
|
| 80 |
+
# unregister them. There is no risk of PermissionError at folder
|
| 81 |
+
# deletion because because at this point, all child processes are
|
| 82 |
+
# dead, so all references to temporary memmaps are closed.
|
| 83 |
+
|
| 84 |
+
# unregister temporary resources from all contexts
|
| 85 |
+
with self._submit_resize_lock:
|
| 86 |
+
self._temp_folder_manager._unregister_temporary_resources()
|
| 87 |
+
self._temp_folder_manager._try_delete_folder(
|
| 88 |
+
allow_non_empty=True
|
| 89 |
+
)
|
| 90 |
+
else:
|
| 91 |
+
self._temp_folder_manager._unlink_temporary_resources()
|
| 92 |
+
self._temp_folder_manager._try_delete_folder(allow_non_empty=True)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def _temp_folder(self):
|
| 96 |
+
# Legacy property in tests. could be removed if we refactored the
|
| 97 |
+
# memmapping tests. SHOULD ONLY BE USED IN TESTS!
|
| 98 |
+
# We cache this property because it is called late in the tests - at
|
| 99 |
+
# this point, all context have been unregistered, and
|
| 100 |
+
# resolve_temp_folder_name raises an error.
|
| 101 |
+
if getattr(self, '_cached_temp_folder', None) is not None:
|
| 102 |
+
return self._cached_temp_folder
|
| 103 |
+
else:
|
| 104 |
+
self._cached_temp_folder = self._temp_folder_manager.resolve_temp_folder_name() # noqa
|
| 105 |
+
return self._cached_temp_folder
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class _TestingMemmappingExecutor(MemmappingExecutor):
|
| 109 |
+
"""Wrapper around ReusableExecutor to ease memmapping testing with Pool
|
| 110 |
+
and Executor. This is only for testing purposes.
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
def apply_async(self, func, args):
|
| 114 |
+
"""Schedule a func to be run"""
|
| 115 |
+
future = self.submit(func, *args)
|
| 116 |
+
future.get = future.result
|
| 117 |
+
return future
|
| 118 |
+
|
| 119 |
+
def map(self, f, *args):
|
| 120 |
+
return list(super().map(f, *args))
|
runtime/Lib/site-packages/joblib/externals/__init__.py
ADDED
|
File without changes
|
runtime/Lib/site-packages/joblib/externals/cloudpickle/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .cloudpickle import * # noqa
|
| 2 |
+
from .cloudpickle_fast import CloudPickler, dumps, dump # noqa
|
| 3 |
+
|
| 4 |
+
# Conform to the convention used by python serialization libraries, which
|
| 5 |
+
# expose their Pickler subclass at top-level under the "Pickler" name.
|
| 6 |
+
Pickler = CloudPickler
|
| 7 |
+
|
| 8 |
+
__version__ = '2.2.0'
|
runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle.py
ADDED
|
@@ -0,0 +1,948 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This class is defined to override standard pickle functionality
|
| 3 |
+
|
| 4 |
+
The goals of it follow:
|
| 5 |
+
-Serialize lambdas and nested functions to compiled byte code
|
| 6 |
+
-Deal with main module correctly
|
| 7 |
+
-Deal with other non-serializable objects
|
| 8 |
+
|
| 9 |
+
It does not include an unpickler, as standard python unpickling suffices.
|
| 10 |
+
|
| 11 |
+
This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
|
| 12 |
+
<https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
|
| 13 |
+
|
| 14 |
+
Copyright (c) 2012, Regents of the University of California.
|
| 15 |
+
Copyright (c) 2009 `PiCloud, Inc. <https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
|
| 16 |
+
All rights reserved.
|
| 17 |
+
|
| 18 |
+
Redistribution and use in source and binary forms, with or without
|
| 19 |
+
modification, are permitted provided that the following conditions
|
| 20 |
+
are met:
|
| 21 |
+
* Redistributions of source code must retain the above copyright
|
| 22 |
+
notice, this list of conditions and the following disclaimer.
|
| 23 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 24 |
+
notice, this list of conditions and the following disclaimer in the
|
| 25 |
+
documentation and/or other materials provided with the distribution.
|
| 26 |
+
* Neither the name of the University of California, Berkeley nor the
|
| 27 |
+
names of its contributors may be used to endorse or promote
|
| 28 |
+
products derived from this software without specific prior written
|
| 29 |
+
permission.
|
| 30 |
+
|
| 31 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 32 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 33 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 34 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 35 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 36 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 37 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 38 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 39 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 40 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 41 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
import builtins
|
| 45 |
+
import dis
|
| 46 |
+
import opcode
|
| 47 |
+
import platform
|
| 48 |
+
import sys
|
| 49 |
+
import types
|
| 50 |
+
import weakref
|
| 51 |
+
import uuid
|
| 52 |
+
import threading
|
| 53 |
+
import typing
|
| 54 |
+
import warnings
|
| 55 |
+
|
| 56 |
+
from .compat import pickle
|
| 57 |
+
from collections import OrderedDict
|
| 58 |
+
from typing import ClassVar, Generic, Union, Tuple, Callable
|
| 59 |
+
from pickle import _getattribute
|
| 60 |
+
from importlib._bootstrap import _find_spec
|
| 61 |
+
|
| 62 |
+
try: # pragma: no branch
|
| 63 |
+
import typing_extensions as _typing_extensions
|
| 64 |
+
from typing_extensions import Literal, Final
|
| 65 |
+
except ImportError:
|
| 66 |
+
_typing_extensions = Literal = Final = None
|
| 67 |
+
|
| 68 |
+
if sys.version_info >= (3, 8):
|
| 69 |
+
from types import CellType
|
| 70 |
+
else:
|
| 71 |
+
def f():
|
| 72 |
+
a = 1
|
| 73 |
+
|
| 74 |
+
def g():
|
| 75 |
+
return a
|
| 76 |
+
return g
|
| 77 |
+
CellType = type(f().__closure__[0])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# cloudpickle is meant for inter process communication: we expect all
|
| 81 |
+
# communicating processes to run the same Python version hence we favor
|
| 82 |
+
# communication speed over compatibility:
|
| 83 |
+
DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
|
| 84 |
+
|
| 85 |
+
# Names of modules whose resources should be treated as dynamic.
|
| 86 |
+
_PICKLE_BY_VALUE_MODULES = set()
|
| 87 |
+
|
| 88 |
+
# Track the provenance of reconstructed dynamic classes to make it possible to
|
| 89 |
+
# reconstruct instances from the matching singleton class definition when
|
| 90 |
+
# appropriate and preserve the usual "isinstance" semantics of Python objects.
|
| 91 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
|
| 92 |
+
_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
|
| 93 |
+
_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
|
| 94 |
+
|
| 95 |
+
PYPY = platform.python_implementation() == "PyPy"
|
| 96 |
+
|
| 97 |
+
builtin_code_type = None
|
| 98 |
+
if PYPY:
|
| 99 |
+
# builtin-code objects only exist in pypy
|
| 100 |
+
builtin_code_type = type(float.__new__.__code__)
|
| 101 |
+
|
| 102 |
+
_extract_code_globals_cache = weakref.WeakKeyDictionary()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _get_or_create_tracker_id(class_def):
|
| 106 |
+
with _DYNAMIC_CLASS_TRACKER_LOCK:
|
| 107 |
+
class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
|
| 108 |
+
if class_tracker_id is None:
|
| 109 |
+
class_tracker_id = uuid.uuid4().hex
|
| 110 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
|
| 111 |
+
_DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
|
| 112 |
+
return class_tracker_id
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _lookup_class_or_track(class_tracker_id, class_def):
|
| 116 |
+
if class_tracker_id is not None:
|
| 117 |
+
with _DYNAMIC_CLASS_TRACKER_LOCK:
|
| 118 |
+
class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
|
| 119 |
+
class_tracker_id, class_def)
|
| 120 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
|
| 121 |
+
return class_def
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def register_pickle_by_value(module):
|
| 125 |
+
"""Register a module to make it functions and classes picklable by value.
|
| 126 |
+
|
| 127 |
+
By default, functions and classes that are attributes of an importable
|
| 128 |
+
module are to be pickled by reference, that is relying on re-importing
|
| 129 |
+
the attribute from the module at load time.
|
| 130 |
+
|
| 131 |
+
If `register_pickle_by_value(module)` is called, all its functions and
|
| 132 |
+
classes are subsequently to be pickled by value, meaning that they can
|
| 133 |
+
be loaded in Python processes where the module is not importable.
|
| 134 |
+
|
| 135 |
+
This is especially useful when developing a module in a distributed
|
| 136 |
+
execution environment: restarting the client Python process with the new
|
| 137 |
+
source code is enough: there is no need to re-install the new version
|
| 138 |
+
of the module on all the worker nodes nor to restart the workers.
|
| 139 |
+
|
| 140 |
+
Note: this feature is considered experimental. See the cloudpickle
|
| 141 |
+
README.md file for more details and limitations.
|
| 142 |
+
"""
|
| 143 |
+
if not isinstance(module, types.ModuleType):
|
| 144 |
+
raise ValueError(
|
| 145 |
+
f"Input should be a module object, got {str(module)} instead"
|
| 146 |
+
)
|
| 147 |
+
# In the future, cloudpickle may need a way to access any module registered
|
| 148 |
+
# for pickling by value in order to introspect relative imports inside
|
| 149 |
+
# functions pickled by value. (see
|
| 150 |
+
# https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633).
|
| 151 |
+
# This access can be ensured by checking that module is present in
|
| 152 |
+
# sys.modules at registering time and assuming that it will still be in
|
| 153 |
+
# there when accessed during pickling. Another alternative would be to
|
| 154 |
+
# store a weakref to the module. Even though cloudpickle does not implement
|
| 155 |
+
# this introspection yet, in order to avoid a possible breaking change
|
| 156 |
+
# later, we still enforce the presence of module inside sys.modules.
|
| 157 |
+
if module.__name__ not in sys.modules:
|
| 158 |
+
raise ValueError(
|
| 159 |
+
f"{module} was not imported correctly, have you used an "
|
| 160 |
+
f"`import` statement to access it?"
|
| 161 |
+
)
|
| 162 |
+
_PICKLE_BY_VALUE_MODULES.add(module.__name__)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def unregister_pickle_by_value(module):
|
| 166 |
+
"""Unregister that the input module should be pickled by value."""
|
| 167 |
+
if not isinstance(module, types.ModuleType):
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"Input should be a module object, got {str(module)} instead"
|
| 170 |
+
)
|
| 171 |
+
if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
|
| 172 |
+
raise ValueError(f"{module} is not registered for pickle by value")
|
| 173 |
+
else:
|
| 174 |
+
_PICKLE_BY_VALUE_MODULES.remove(module.__name__)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def list_registry_pickle_by_value():
|
| 178 |
+
return _PICKLE_BY_VALUE_MODULES.copy()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _is_registered_pickle_by_value(module):
|
| 182 |
+
module_name = module.__name__
|
| 183 |
+
if module_name in _PICKLE_BY_VALUE_MODULES:
|
| 184 |
+
return True
|
| 185 |
+
while True:
|
| 186 |
+
parent_name = module_name.rsplit(".", 1)[0]
|
| 187 |
+
if parent_name == module_name:
|
| 188 |
+
break
|
| 189 |
+
if parent_name in _PICKLE_BY_VALUE_MODULES:
|
| 190 |
+
return True
|
| 191 |
+
module_name = parent_name
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _whichmodule(obj, name):
|
| 196 |
+
"""Find the module an object belongs to.
|
| 197 |
+
|
| 198 |
+
This function differs from ``pickle.whichmodule`` in two ways:
|
| 199 |
+
- it does not mangle the cases where obj's module is __main__ and obj was
|
| 200 |
+
not found in any module.
|
| 201 |
+
- Errors arising during module introspection are ignored, as those errors
|
| 202 |
+
are considered unwanted side effects.
|
| 203 |
+
"""
|
| 204 |
+
if sys.version_info[:2] < (3, 7) and isinstance(obj, typing.TypeVar): # pragma: no branch # noqa
|
| 205 |
+
# Workaround bug in old Python versions: prior to Python 3.7,
|
| 206 |
+
# T.__module__ would always be set to "typing" even when the TypeVar T
|
| 207 |
+
# would be defined in a different module.
|
| 208 |
+
if name is not None and getattr(typing, name, None) is obj:
|
| 209 |
+
# Built-in TypeVar defined in typing such as AnyStr
|
| 210 |
+
return 'typing'
|
| 211 |
+
else:
|
| 212 |
+
# User defined or third-party TypeVar: __module__ attribute is
|
| 213 |
+
# irrelevant, thus trigger a exhaustive search for obj in all
|
| 214 |
+
# modules.
|
| 215 |
+
module_name = None
|
| 216 |
+
else:
|
| 217 |
+
module_name = getattr(obj, '__module__', None)
|
| 218 |
+
|
| 219 |
+
if module_name is not None:
|
| 220 |
+
return module_name
|
| 221 |
+
# Protect the iteration by using a copy of sys.modules against dynamic
|
| 222 |
+
# modules that trigger imports of other modules upon calls to getattr or
|
| 223 |
+
# other threads importing at the same time.
|
| 224 |
+
for module_name, module in sys.modules.copy().items():
|
| 225 |
+
# Some modules such as coverage can inject non-module objects inside
|
| 226 |
+
# sys.modules
|
| 227 |
+
if (
|
| 228 |
+
module_name == '__main__' or
|
| 229 |
+
module is None or
|
| 230 |
+
not isinstance(module, types.ModuleType)
|
| 231 |
+
):
|
| 232 |
+
continue
|
| 233 |
+
try:
|
| 234 |
+
if _getattribute(module, name)[0] is obj:
|
| 235 |
+
return module_name
|
| 236 |
+
except Exception:
|
| 237 |
+
pass
|
| 238 |
+
return None
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _should_pickle_by_reference(obj, name=None):
|
| 242 |
+
"""Test whether an function or a class should be pickled by reference
|
| 243 |
+
|
| 244 |
+
Pickling by reference means by that the object (typically a function or a
|
| 245 |
+
class) is an attribute of a module that is assumed to be importable in the
|
| 246 |
+
target Python environment. Loading will therefore rely on importing the
|
| 247 |
+
module and then calling `getattr` on it to access the function or class.
|
| 248 |
+
|
| 249 |
+
Pickling by reference is the only option to pickle functions and classes
|
| 250 |
+
in the standard library. In cloudpickle the alternative option is to
|
| 251 |
+
pickle by value (for instance for interactively or locally defined
|
| 252 |
+
functions and classes or for attributes of modules that have been
|
| 253 |
+
explicitly registered to be pickled by value.
|
| 254 |
+
"""
|
| 255 |
+
if isinstance(obj, types.FunctionType) or issubclass(type(obj), type):
|
| 256 |
+
module_and_name = _lookup_module_and_qualname(obj, name=name)
|
| 257 |
+
if module_and_name is None:
|
| 258 |
+
return False
|
| 259 |
+
module, name = module_and_name
|
| 260 |
+
return not _is_registered_pickle_by_value(module)
|
| 261 |
+
|
| 262 |
+
elif isinstance(obj, types.ModuleType):
|
| 263 |
+
# We assume that sys.modules is primarily used as a cache mechanism for
|
| 264 |
+
# the Python import machinery. Checking if a module has been added in
|
| 265 |
+
# is sys.modules therefore a cheap and simple heuristic to tell us
|
| 266 |
+
# whether we can assume that a given module could be imported by name
|
| 267 |
+
# in another Python process.
|
| 268 |
+
if _is_registered_pickle_by_value(obj):
|
| 269 |
+
return False
|
| 270 |
+
return obj.__name__ in sys.modules
|
| 271 |
+
else:
|
| 272 |
+
raise TypeError(
|
| 273 |
+
"cannot check importability of {} instances".format(
|
| 274 |
+
type(obj).__name__)
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _lookup_module_and_qualname(obj, name=None):
|
| 279 |
+
if name is None:
|
| 280 |
+
name = getattr(obj, '__qualname__', None)
|
| 281 |
+
if name is None: # pragma: no cover
|
| 282 |
+
# This used to be needed for Python 2.7 support but is probably not
|
| 283 |
+
# needed anymore. However we keep the __name__ introspection in case
|
| 284 |
+
# users of cloudpickle rely on this old behavior for unknown reasons.
|
| 285 |
+
name = getattr(obj, '__name__', None)
|
| 286 |
+
|
| 287 |
+
module_name = _whichmodule(obj, name)
|
| 288 |
+
|
| 289 |
+
if module_name is None:
|
| 290 |
+
# In this case, obj.__module__ is None AND obj was not found in any
|
| 291 |
+
# imported module. obj is thus treated as dynamic.
|
| 292 |
+
return None
|
| 293 |
+
|
| 294 |
+
if module_name == "__main__":
|
| 295 |
+
return None
|
| 296 |
+
|
| 297 |
+
# Note: if module_name is in sys.modules, the corresponding module is
|
| 298 |
+
# assumed importable at unpickling time. See #357
|
| 299 |
+
module = sys.modules.get(module_name, None)
|
| 300 |
+
if module is None:
|
| 301 |
+
# The main reason why obj's module would not be imported is that this
|
| 302 |
+
# module has been dynamically created, using for example
|
| 303 |
+
# types.ModuleType. The other possibility is that module was removed
|
| 304 |
+
# from sys.modules after obj was created/imported. But this case is not
|
| 305 |
+
# supported, as the standard pickle does not support it either.
|
| 306 |
+
return None
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
obj2, parent = _getattribute(module, name)
|
| 310 |
+
except AttributeError:
|
| 311 |
+
# obj was not found inside the module it points to
|
| 312 |
+
return None
|
| 313 |
+
if obj2 is not obj:
|
| 314 |
+
return None
|
| 315 |
+
return module, name
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _extract_code_globals(co):
|
| 319 |
+
"""
|
| 320 |
+
Find all globals names read or written to by codeblock co
|
| 321 |
+
"""
|
| 322 |
+
out_names = _extract_code_globals_cache.get(co)
|
| 323 |
+
if out_names is None:
|
| 324 |
+
# We use a dict with None values instead of a set to get a
|
| 325 |
+
# deterministic order (assuming Python 3.6+) and avoid introducing
|
| 326 |
+
# non-deterministic pickle bytes as a results.
|
| 327 |
+
out_names = {name: None for name in _walk_global_ops(co)}
|
| 328 |
+
|
| 329 |
+
# Declaring a function inside another one using the "def ..."
|
| 330 |
+
# syntax generates a constant code object corresponding to the one
|
| 331 |
+
# of the nested function's As the nested function may itself need
|
| 332 |
+
# global variables, we need to introspect its code, extract its
|
| 333 |
+
# globals, (look for code object in it's co_consts attribute..) and
|
| 334 |
+
# add the result to code_globals
|
| 335 |
+
if co.co_consts:
|
| 336 |
+
for const in co.co_consts:
|
| 337 |
+
if isinstance(const, types.CodeType):
|
| 338 |
+
out_names.update(_extract_code_globals(const))
|
| 339 |
+
|
| 340 |
+
_extract_code_globals_cache[co] = out_names
|
| 341 |
+
|
| 342 |
+
return out_names
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _find_imported_submodules(code, top_level_dependencies):
|
| 346 |
+
"""
|
| 347 |
+
Find currently imported submodules used by a function.
|
| 348 |
+
|
| 349 |
+
Submodules used by a function need to be detected and referenced for the
|
| 350 |
+
function to work correctly at depickling time. Because submodules can be
|
| 351 |
+
referenced as attribute of their parent package (``package.submodule``), we
|
| 352 |
+
need a special introspection technique that does not rely on GLOBAL-related
|
| 353 |
+
opcodes to find references of them in a code object.
|
| 354 |
+
|
| 355 |
+
Example:
|
| 356 |
+
```
|
| 357 |
+
import concurrent.futures
|
| 358 |
+
import cloudpickle
|
| 359 |
+
def func():
|
| 360 |
+
x = concurrent.futures.ThreadPoolExecutor
|
| 361 |
+
if __name__ == '__main__':
|
| 362 |
+
cloudpickle.dumps(func)
|
| 363 |
+
```
|
| 364 |
+
The globals extracted by cloudpickle in the function's state include the
|
| 365 |
+
concurrent package, but not its submodule (here, concurrent.futures), which
|
| 366 |
+
is the module used by func. Find_imported_submodules will detect the usage
|
| 367 |
+
of concurrent.futures. Saving this module alongside with func will ensure
|
| 368 |
+
that calling func once depickled does not fail due to concurrent.futures
|
| 369 |
+
not being imported
|
| 370 |
+
"""
|
| 371 |
+
|
| 372 |
+
subimports = []
|
| 373 |
+
# check if any known dependency is an imported package
|
| 374 |
+
for x in top_level_dependencies:
|
| 375 |
+
if (isinstance(x, types.ModuleType) and
|
| 376 |
+
hasattr(x, '__package__') and x.__package__):
|
| 377 |
+
# check if the package has any currently loaded sub-imports
|
| 378 |
+
prefix = x.__name__ + '.'
|
| 379 |
+
# A concurrent thread could mutate sys.modules,
|
| 380 |
+
# make sure we iterate over a copy to avoid exceptions
|
| 381 |
+
for name in list(sys.modules):
|
| 382 |
+
# Older versions of pytest will add a "None" module to
|
| 383 |
+
# sys.modules.
|
| 384 |
+
if name is not None and name.startswith(prefix):
|
| 385 |
+
# check whether the function can address the sub-module
|
| 386 |
+
tokens = set(name[len(prefix):].split('.'))
|
| 387 |
+
if not tokens - set(code.co_names):
|
| 388 |
+
subimports.append(sys.modules[name])
|
| 389 |
+
return subimports
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def cell_set(cell, value):
|
| 393 |
+
"""Set the value of a closure cell.
|
| 394 |
+
|
| 395 |
+
The point of this function is to set the cell_contents attribute of a cell
|
| 396 |
+
after its creation. This operation is necessary in case the cell contains a
|
| 397 |
+
reference to the function the cell belongs to, as when calling the
|
| 398 |
+
function's constructor
|
| 399 |
+
``f = types.FunctionType(code, globals, name, argdefs, closure)``,
|
| 400 |
+
closure will not be able to contain the yet-to-be-created f.
|
| 401 |
+
|
| 402 |
+
In Python3.7, cell_contents is writeable, so setting the contents of a cell
|
| 403 |
+
can be done simply using
|
| 404 |
+
>>> cell.cell_contents = value
|
| 405 |
+
|
| 406 |
+
In earlier Python3 versions, the cell_contents attribute of a cell is read
|
| 407 |
+
only, but this limitation can be worked around by leveraging the Python 3
|
| 408 |
+
``nonlocal`` keyword.
|
| 409 |
+
|
| 410 |
+
In Python2 however, this attribute is read only, and there is no
|
| 411 |
+
``nonlocal`` keyword. For this reason, we need to come up with more
|
| 412 |
+
complicated hacks to set this attribute.
|
| 413 |
+
|
| 414 |
+
The chosen approach is to create a function with a STORE_DEREF opcode,
|
| 415 |
+
which sets the content of a closure variable. Typically:
|
| 416 |
+
|
| 417 |
+
>>> def inner(value):
|
| 418 |
+
... lambda: cell # the lambda makes cell a closure
|
| 419 |
+
... cell = value # cell is a closure, so this triggers a STORE_DEREF
|
| 420 |
+
|
| 421 |
+
(Note that in Python2, A STORE_DEREF can never be triggered from an inner
|
| 422 |
+
function. The function g for example here
|
| 423 |
+
>>> def f(var):
|
| 424 |
+
... def g():
|
| 425 |
+
... var += 1
|
| 426 |
+
... return g
|
| 427 |
+
|
| 428 |
+
will not modify the closure variable ``var```inplace, but instead try to
|
| 429 |
+
load a local variable var and increment it. As g does not assign the local
|
| 430 |
+
variable ``var`` any initial value, calling f(1)() will fail at runtime.)
|
| 431 |
+
|
| 432 |
+
Our objective is to set the value of a given cell ``cell``. So we need to
|
| 433 |
+
somewhat reference our ``cell`` object into the ``inner`` function so that
|
| 434 |
+
this object (and not the smoke cell of the lambda function) gets affected
|
| 435 |
+
by the STORE_DEREF operation.
|
| 436 |
+
|
| 437 |
+
In inner, ``cell`` is referenced as a cell variable (an enclosing variable
|
| 438 |
+
that is referenced by the inner function). If we create a new function
|
| 439 |
+
cell_set with the exact same code as ``inner``, but with ``cell`` marked as
|
| 440 |
+
a free variable instead, the STORE_DEREF will be applied on its closure -
|
| 441 |
+
``cell``, which we can specify explicitly during construction! The new
|
| 442 |
+
cell_set variable thus actually sets the contents of a specified cell!
|
| 443 |
+
|
| 444 |
+
Note: we do not make use of the ``nonlocal`` keyword to set the contents of
|
| 445 |
+
a cell in early python3 versions to limit possible syntax errors in case
|
| 446 |
+
test and checker libraries decide to parse the whole file.
|
| 447 |
+
"""
|
| 448 |
+
|
| 449 |
+
if sys.version_info[:2] >= (3, 7): # pragma: no branch
|
| 450 |
+
cell.cell_contents = value
|
| 451 |
+
else:
|
| 452 |
+
_cell_set = types.FunctionType(
|
| 453 |
+
_cell_set_template_code, {}, '_cell_set', (), (cell,),)
|
| 454 |
+
_cell_set(value)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _make_cell_set_template_code():
|
| 458 |
+
def _cell_set_factory(value):
|
| 459 |
+
lambda: cell
|
| 460 |
+
cell = value
|
| 461 |
+
|
| 462 |
+
co = _cell_set_factory.__code__
|
| 463 |
+
|
| 464 |
+
_cell_set_template_code = types.CodeType(
|
| 465 |
+
co.co_argcount,
|
| 466 |
+
co.co_kwonlyargcount, # Python 3 only argument
|
| 467 |
+
co.co_nlocals,
|
| 468 |
+
co.co_stacksize,
|
| 469 |
+
co.co_flags,
|
| 470 |
+
co.co_code,
|
| 471 |
+
co.co_consts,
|
| 472 |
+
co.co_names,
|
| 473 |
+
co.co_varnames,
|
| 474 |
+
co.co_filename,
|
| 475 |
+
co.co_name,
|
| 476 |
+
co.co_firstlineno,
|
| 477 |
+
co.co_lnotab,
|
| 478 |
+
co.co_cellvars, # co_freevars is initialized with co_cellvars
|
| 479 |
+
(), # co_cellvars is made empty
|
| 480 |
+
)
|
| 481 |
+
return _cell_set_template_code
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
if sys.version_info[:2] < (3, 7):
|
| 485 |
+
_cell_set_template_code = _make_cell_set_template_code()
|
| 486 |
+
|
| 487 |
+
# relevant opcodes
|
| 488 |
+
STORE_GLOBAL = opcode.opmap['STORE_GLOBAL']
|
| 489 |
+
DELETE_GLOBAL = opcode.opmap['DELETE_GLOBAL']
|
| 490 |
+
LOAD_GLOBAL = opcode.opmap['LOAD_GLOBAL']
|
| 491 |
+
GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL)
|
| 492 |
+
HAVE_ARGUMENT = dis.HAVE_ARGUMENT
|
| 493 |
+
EXTENDED_ARG = dis.EXTENDED_ARG
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
_BUILTIN_TYPE_NAMES = {}
|
| 497 |
+
for k, v in types.__dict__.items():
|
| 498 |
+
if type(v) is type:
|
| 499 |
+
_BUILTIN_TYPE_NAMES[v] = k
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _builtin_type(name):
|
| 503 |
+
if name == "ClassType": # pragma: no cover
|
| 504 |
+
# Backward compat to load pickle files generated with cloudpickle
|
| 505 |
+
# < 1.3 even if loading pickle files from older versions is not
|
| 506 |
+
# officially supported.
|
| 507 |
+
return type
|
| 508 |
+
return getattr(types, name)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _walk_global_ops(code):
|
| 512 |
+
"""
|
| 513 |
+
Yield referenced name for all global-referencing instructions in *code*.
|
| 514 |
+
"""
|
| 515 |
+
for instr in dis.get_instructions(code):
|
| 516 |
+
op = instr.opcode
|
| 517 |
+
if op in GLOBAL_OPS:
|
| 518 |
+
yield instr.argval
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def _extract_class_dict(cls):
|
| 522 |
+
"""Retrieve a copy of the dict of a class without the inherited methods"""
|
| 523 |
+
clsdict = dict(cls.__dict__) # copy dict proxy to a dict
|
| 524 |
+
if len(cls.__bases__) == 1:
|
| 525 |
+
inherited_dict = cls.__bases__[0].__dict__
|
| 526 |
+
else:
|
| 527 |
+
inherited_dict = {}
|
| 528 |
+
for base in reversed(cls.__bases__):
|
| 529 |
+
inherited_dict.update(base.__dict__)
|
| 530 |
+
to_remove = []
|
| 531 |
+
for name, value in clsdict.items():
|
| 532 |
+
try:
|
| 533 |
+
base_value = inherited_dict[name]
|
| 534 |
+
if value is base_value:
|
| 535 |
+
to_remove.append(name)
|
| 536 |
+
except KeyError:
|
| 537 |
+
pass
|
| 538 |
+
for name in to_remove:
|
| 539 |
+
clsdict.pop(name)
|
| 540 |
+
return clsdict
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
if sys.version_info[:2] < (3, 7): # pragma: no branch
|
| 544 |
+
def _is_parametrized_type_hint(obj):
|
| 545 |
+
# This is very cheap but might generate false positives. So try to
|
| 546 |
+
# narrow it down is good as possible.
|
| 547 |
+
type_module = getattr(type(obj), '__module__', None)
|
| 548 |
+
from_typing_extensions = type_module == 'typing_extensions'
|
| 549 |
+
from_typing = type_module == 'typing'
|
| 550 |
+
|
| 551 |
+
# general typing Constructs
|
| 552 |
+
is_typing = getattr(obj, '__origin__', None) is not None
|
| 553 |
+
|
| 554 |
+
# typing_extensions.Literal
|
| 555 |
+
is_literal = (
|
| 556 |
+
(getattr(obj, '__values__', None) is not None)
|
| 557 |
+
and from_typing_extensions
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
# typing_extensions.Final
|
| 561 |
+
is_final = (
|
| 562 |
+
(getattr(obj, '__type__', None) is not None)
|
| 563 |
+
and from_typing_extensions
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
# typing.ClassVar
|
| 567 |
+
is_classvar = (
|
| 568 |
+
(getattr(obj, '__type__', None) is not None) and from_typing
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
# typing.Union/Tuple for old Python 3.5
|
| 572 |
+
is_union = getattr(obj, '__union_params__', None) is not None
|
| 573 |
+
is_tuple = getattr(obj, '__tuple_params__', None) is not None
|
| 574 |
+
is_callable = (
|
| 575 |
+
getattr(obj, '__result__', None) is not None and
|
| 576 |
+
getattr(obj, '__args__', None) is not None
|
| 577 |
+
)
|
| 578 |
+
return any((is_typing, is_literal, is_final, is_classvar, is_union,
|
| 579 |
+
is_tuple, is_callable))
|
| 580 |
+
|
| 581 |
+
def _create_parametrized_type_hint(origin, args):
|
| 582 |
+
return origin[args]
|
| 583 |
+
else:
|
| 584 |
+
_is_parametrized_type_hint = None
|
| 585 |
+
_create_parametrized_type_hint = None
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def parametrized_type_hint_getinitargs(obj):
|
| 589 |
+
# The distorted type check sematic for typing construct becomes:
|
| 590 |
+
# ``type(obj) is type(TypeHint)``, which means "obj is a
|
| 591 |
+
# parametrized TypeHint"
|
| 592 |
+
if type(obj) is type(Literal): # pragma: no branch
|
| 593 |
+
initargs = (Literal, obj.__values__)
|
| 594 |
+
elif type(obj) is type(Final): # pragma: no branch
|
| 595 |
+
initargs = (Final, obj.__type__)
|
| 596 |
+
elif type(obj) is type(ClassVar):
|
| 597 |
+
initargs = (ClassVar, obj.__type__)
|
| 598 |
+
elif type(obj) is type(Generic):
|
| 599 |
+
initargs = (obj.__origin__, obj.__args__)
|
| 600 |
+
elif type(obj) is type(Union):
|
| 601 |
+
initargs = (Union, obj.__args__)
|
| 602 |
+
elif type(obj) is type(Tuple):
|
| 603 |
+
initargs = (Tuple, obj.__args__)
|
| 604 |
+
elif type(obj) is type(Callable):
|
| 605 |
+
(*args, result) = obj.__args__
|
| 606 |
+
if len(args) == 1 and args[0] is Ellipsis:
|
| 607 |
+
args = Ellipsis
|
| 608 |
+
else:
|
| 609 |
+
args = list(args)
|
| 610 |
+
initargs = (Callable, (args, result))
|
| 611 |
+
else: # pragma: no cover
|
| 612 |
+
raise pickle.PicklingError(
|
| 613 |
+
f"Cloudpickle Error: Unknown type {type(obj)}"
|
| 614 |
+
)
|
| 615 |
+
return initargs
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
# Tornado support
|
| 619 |
+
|
| 620 |
+
def is_tornado_coroutine(func):
|
| 621 |
+
"""
|
| 622 |
+
Return whether *func* is a Tornado coroutine function.
|
| 623 |
+
Running coroutines are not supported.
|
| 624 |
+
"""
|
| 625 |
+
if 'tornado.gen' not in sys.modules:
|
| 626 |
+
return False
|
| 627 |
+
gen = sys.modules['tornado.gen']
|
| 628 |
+
if not hasattr(gen, "is_coroutine_function"):
|
| 629 |
+
# Tornado version is too old
|
| 630 |
+
return False
|
| 631 |
+
return gen.is_coroutine_function(func)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def _rebuild_tornado_coroutine(func):
|
| 635 |
+
from tornado import gen
|
| 636 |
+
return gen.coroutine(func)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
# including pickles unloading functions in this namespace
|
| 640 |
+
load = pickle.load
|
| 641 |
+
loads = pickle.loads
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def subimport(name):
|
| 645 |
+
# We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is
|
| 646 |
+
# the name of a submodule, __import__ will return the top-level root module
|
| 647 |
+
# of this submodule. For instance, __import__('os.path') returns the `os`
|
| 648 |
+
# module.
|
| 649 |
+
__import__(name)
|
| 650 |
+
return sys.modules[name]
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def dynamic_subimport(name, vars):
|
| 654 |
+
mod = types.ModuleType(name)
|
| 655 |
+
mod.__dict__.update(vars)
|
| 656 |
+
mod.__dict__['__builtins__'] = builtins.__dict__
|
| 657 |
+
return mod
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def _gen_ellipsis():
|
| 661 |
+
return Ellipsis
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def _gen_not_implemented():
|
| 665 |
+
return NotImplemented
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def _get_cell_contents(cell):
|
| 669 |
+
try:
|
| 670 |
+
return cell.cell_contents
|
| 671 |
+
except ValueError:
|
| 672 |
+
# sentinel used by ``_fill_function`` which will leave the cell empty
|
| 673 |
+
return _empty_cell_value
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def instance(cls):
|
| 677 |
+
"""Create a new instance of a class.
|
| 678 |
+
|
| 679 |
+
Parameters
|
| 680 |
+
----------
|
| 681 |
+
cls : type
|
| 682 |
+
The class to create an instance of.
|
| 683 |
+
|
| 684 |
+
Returns
|
| 685 |
+
-------
|
| 686 |
+
instance : cls
|
| 687 |
+
A new instance of ``cls``.
|
| 688 |
+
"""
|
| 689 |
+
return cls()
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
@instance
|
| 693 |
+
class _empty_cell_value:
|
| 694 |
+
"""sentinel for empty closures
|
| 695 |
+
"""
|
| 696 |
+
@classmethod
|
| 697 |
+
def __reduce__(cls):
|
| 698 |
+
return cls.__name__
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def _fill_function(*args):
|
| 702 |
+
"""Fills in the rest of function data into the skeleton function object
|
| 703 |
+
|
| 704 |
+
The skeleton itself is create by _make_skel_func().
|
| 705 |
+
"""
|
| 706 |
+
if len(args) == 2:
|
| 707 |
+
func = args[0]
|
| 708 |
+
state = args[1]
|
| 709 |
+
elif len(args) == 5:
|
| 710 |
+
# Backwards compat for cloudpickle v0.4.0, after which the `module`
|
| 711 |
+
# argument was introduced
|
| 712 |
+
func = args[0]
|
| 713 |
+
keys = ['globals', 'defaults', 'dict', 'closure_values']
|
| 714 |
+
state = dict(zip(keys, args[1:]))
|
| 715 |
+
elif len(args) == 6:
|
| 716 |
+
# Backwards compat for cloudpickle v0.4.1, after which the function
|
| 717 |
+
# state was passed as a dict to the _fill_function it-self.
|
| 718 |
+
func = args[0]
|
| 719 |
+
keys = ['globals', 'defaults', 'dict', 'module', 'closure_values']
|
| 720 |
+
state = dict(zip(keys, args[1:]))
|
| 721 |
+
else:
|
| 722 |
+
raise ValueError(f'Unexpected _fill_value arguments: {args!r}')
|
| 723 |
+
|
| 724 |
+
# - At pickling time, any dynamic global variable used by func is
|
| 725 |
+
# serialized by value (in state['globals']).
|
| 726 |
+
# - At unpickling time, func's __globals__ attribute is initialized by
|
| 727 |
+
# first retrieving an empty isolated namespace that will be shared
|
| 728 |
+
# with other functions pickled from the same original module
|
| 729 |
+
# by the same CloudPickler instance and then updated with the
|
| 730 |
+
# content of state['globals'] to populate the shared isolated
|
| 731 |
+
# namespace with all the global variables that are specifically
|
| 732 |
+
# referenced for this function.
|
| 733 |
+
func.__globals__.update(state['globals'])
|
| 734 |
+
|
| 735 |
+
func.__defaults__ = state['defaults']
|
| 736 |
+
func.__dict__ = state['dict']
|
| 737 |
+
if 'annotations' in state:
|
| 738 |
+
func.__annotations__ = state['annotations']
|
| 739 |
+
if 'doc' in state:
|
| 740 |
+
func.__doc__ = state['doc']
|
| 741 |
+
if 'name' in state:
|
| 742 |
+
func.__name__ = state['name']
|
| 743 |
+
if 'module' in state:
|
| 744 |
+
func.__module__ = state['module']
|
| 745 |
+
if 'qualname' in state:
|
| 746 |
+
func.__qualname__ = state['qualname']
|
| 747 |
+
if 'kwdefaults' in state:
|
| 748 |
+
func.__kwdefaults__ = state['kwdefaults']
|
| 749 |
+
# _cloudpickle_subimports is a set of submodules that must be loaded for
|
| 750 |
+
# the pickled function to work correctly at unpickling time. Now that these
|
| 751 |
+
# submodules are depickled (hence imported), they can be removed from the
|
| 752 |
+
# object's state (the object state only served as a reference holder to
|
| 753 |
+
# these submodules)
|
| 754 |
+
if '_cloudpickle_submodules' in state:
|
| 755 |
+
state.pop('_cloudpickle_submodules')
|
| 756 |
+
|
| 757 |
+
cells = func.__closure__
|
| 758 |
+
if cells is not None:
|
| 759 |
+
for cell, value in zip(cells, state['closure_values']):
|
| 760 |
+
if value is not _empty_cell_value:
|
| 761 |
+
cell_set(cell, value)
|
| 762 |
+
|
| 763 |
+
return func
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
def _make_function(code, globals, name, argdefs, closure):
|
| 767 |
+
# Setting __builtins__ in globals is needed for nogil CPython.
|
| 768 |
+
globals["__builtins__"] = __builtins__
|
| 769 |
+
return types.FunctionType(code, globals, name, argdefs, closure)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
def _make_empty_cell():
|
| 773 |
+
if False:
|
| 774 |
+
# trick the compiler into creating an empty cell in our lambda
|
| 775 |
+
cell = None
|
| 776 |
+
raise AssertionError('this route should not be executed')
|
| 777 |
+
|
| 778 |
+
return (lambda: cell).__closure__[0]
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def _make_cell(value=_empty_cell_value):
|
| 782 |
+
cell = _make_empty_cell()
|
| 783 |
+
if value is not _empty_cell_value:
|
| 784 |
+
cell_set(cell, value)
|
| 785 |
+
return cell
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _make_skel_func(code, cell_count, base_globals=None):
|
| 789 |
+
""" Creates a skeleton function object that contains just the provided
|
| 790 |
+
code and the correct number of cells in func_closure. All other
|
| 791 |
+
func attributes (e.g. func_globals) are empty.
|
| 792 |
+
"""
|
| 793 |
+
# This function is deprecated and should be removed in cloudpickle 1.7
|
| 794 |
+
warnings.warn(
|
| 795 |
+
"A pickle file created using an old (<=1.4.1) version of cloudpickle "
|
| 796 |
+
"is currently being loaded. This is not supported by cloudpickle and "
|
| 797 |
+
"will break in cloudpickle 1.7", category=UserWarning
|
| 798 |
+
)
|
| 799 |
+
# This is backward-compatibility code: for cloudpickle versions between
|
| 800 |
+
# 0.5.4 and 0.7, base_globals could be a string or None. base_globals
|
| 801 |
+
# should now always be a dictionary.
|
| 802 |
+
if base_globals is None or isinstance(base_globals, str):
|
| 803 |
+
base_globals = {}
|
| 804 |
+
|
| 805 |
+
base_globals['__builtins__'] = __builtins__
|
| 806 |
+
|
| 807 |
+
closure = (
|
| 808 |
+
tuple(_make_empty_cell() for _ in range(cell_count))
|
| 809 |
+
if cell_count >= 0 else
|
| 810 |
+
None
|
| 811 |
+
)
|
| 812 |
+
return types.FunctionType(code, base_globals, None, None, closure)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def _make_skeleton_class(type_constructor, name, bases, type_kwargs,
|
| 816 |
+
class_tracker_id, extra):
|
| 817 |
+
"""Build dynamic class with an empty __dict__ to be filled once memoized
|
| 818 |
+
|
| 819 |
+
If class_tracker_id is not None, try to lookup an existing class definition
|
| 820 |
+
matching that id. If none is found, track a newly reconstructed class
|
| 821 |
+
definition under that id so that other instances stemming from the same
|
| 822 |
+
class id will also reuse this class definition.
|
| 823 |
+
|
| 824 |
+
The "extra" variable is meant to be a dict (or None) that can be used for
|
| 825 |
+
forward compatibility shall the need arise.
|
| 826 |
+
"""
|
| 827 |
+
skeleton_class = types.new_class(
|
| 828 |
+
name, bases, {'metaclass': type_constructor},
|
| 829 |
+
lambda ns: ns.update(type_kwargs)
|
| 830 |
+
)
|
| 831 |
+
return _lookup_class_or_track(class_tracker_id, skeleton_class)
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
def _rehydrate_skeleton_class(skeleton_class, class_dict):
|
| 835 |
+
"""Put attributes from `class_dict` back on `skeleton_class`.
|
| 836 |
+
|
| 837 |
+
See CloudPickler.save_dynamic_class for more info.
|
| 838 |
+
"""
|
| 839 |
+
registry = None
|
| 840 |
+
for attrname, attr in class_dict.items():
|
| 841 |
+
if attrname == "_abc_impl":
|
| 842 |
+
registry = attr
|
| 843 |
+
else:
|
| 844 |
+
setattr(skeleton_class, attrname, attr)
|
| 845 |
+
if registry is not None:
|
| 846 |
+
for subclass in registry:
|
| 847 |
+
skeleton_class.register(subclass)
|
| 848 |
+
|
| 849 |
+
return skeleton_class
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def _make_skeleton_enum(bases, name, qualname, members, module,
|
| 853 |
+
class_tracker_id, extra):
|
| 854 |
+
"""Build dynamic enum with an empty __dict__ to be filled once memoized
|
| 855 |
+
|
| 856 |
+
The creation of the enum class is inspired by the code of
|
| 857 |
+
EnumMeta._create_.
|
| 858 |
+
|
| 859 |
+
If class_tracker_id is not None, try to lookup an existing enum definition
|
| 860 |
+
matching that id. If none is found, track a newly reconstructed enum
|
| 861 |
+
definition under that id so that other instances stemming from the same
|
| 862 |
+
class id will also reuse this enum definition.
|
| 863 |
+
|
| 864 |
+
The "extra" variable is meant to be a dict (or None) that can be used for
|
| 865 |
+
forward compatibility shall the need arise.
|
| 866 |
+
"""
|
| 867 |
+
# enums always inherit from their base Enum class at the last position in
|
| 868 |
+
# the list of base classes:
|
| 869 |
+
enum_base = bases[-1]
|
| 870 |
+
metacls = enum_base.__class__
|
| 871 |
+
classdict = metacls.__prepare__(name, bases)
|
| 872 |
+
|
| 873 |
+
for member_name, member_value in members.items():
|
| 874 |
+
classdict[member_name] = member_value
|
| 875 |
+
enum_class = metacls.__new__(metacls, name, bases, classdict)
|
| 876 |
+
enum_class.__module__ = module
|
| 877 |
+
enum_class.__qualname__ = qualname
|
| 878 |
+
|
| 879 |
+
return _lookup_class_or_track(class_tracker_id, enum_class)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
def _make_typevar(name, bound, constraints, covariant, contravariant,
|
| 883 |
+
class_tracker_id):
|
| 884 |
+
tv = typing.TypeVar(
|
| 885 |
+
name, *constraints, bound=bound,
|
| 886 |
+
covariant=covariant, contravariant=contravariant
|
| 887 |
+
)
|
| 888 |
+
if class_tracker_id is not None:
|
| 889 |
+
return _lookup_class_or_track(class_tracker_id, tv)
|
| 890 |
+
else: # pragma: nocover
|
| 891 |
+
# Only for Python 3.5.3 compat.
|
| 892 |
+
return tv
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def _decompose_typevar(obj):
|
| 896 |
+
return (
|
| 897 |
+
obj.__name__, obj.__bound__, obj.__constraints__,
|
| 898 |
+
obj.__covariant__, obj.__contravariant__,
|
| 899 |
+
_get_or_create_tracker_id(obj),
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
|
| 903 |
+
def _typevar_reduce(obj):
|
| 904 |
+
# TypeVar instances require the module information hence why we
|
| 905 |
+
# are not using the _should_pickle_by_reference directly
|
| 906 |
+
module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
|
| 907 |
+
|
| 908 |
+
if module_and_name is None:
|
| 909 |
+
return (_make_typevar, _decompose_typevar(obj))
|
| 910 |
+
elif _is_registered_pickle_by_value(module_and_name[0]):
|
| 911 |
+
return (_make_typevar, _decompose_typevar(obj))
|
| 912 |
+
|
| 913 |
+
return (getattr, module_and_name)
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
def _get_bases(typ):
|
| 917 |
+
if '__orig_bases__' in getattr(typ, '__dict__', {}):
|
| 918 |
+
# For generic types (see PEP 560)
|
| 919 |
+
# Note that simply checking `hasattr(typ, '__orig_bases__')` is not
|
| 920 |
+
# correct. Subclasses of a fully-parameterized generic class does not
|
| 921 |
+
# have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
|
| 922 |
+
# will return True because it's defined in the base class.
|
| 923 |
+
bases_attr = '__orig_bases__'
|
| 924 |
+
else:
|
| 925 |
+
# For regular class objects
|
| 926 |
+
bases_attr = '__bases__'
|
| 927 |
+
return getattr(typ, bases_attr)
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
def _make_dict_keys(obj, is_ordered=False):
|
| 931 |
+
if is_ordered:
|
| 932 |
+
return OrderedDict.fromkeys(obj).keys()
|
| 933 |
+
else:
|
| 934 |
+
return dict.fromkeys(obj).keys()
|
| 935 |
+
|
| 936 |
+
|
| 937 |
+
def _make_dict_values(obj, is_ordered=False):
|
| 938 |
+
if is_ordered:
|
| 939 |
+
return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
|
| 940 |
+
else:
|
| 941 |
+
return {i: _ for i, _ in enumerate(obj)}.values()
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
def _make_dict_items(obj, is_ordered=False):
|
| 945 |
+
if is_ordered:
|
| 946 |
+
return OrderedDict(obj).items()
|
| 947 |
+
else:
|
| 948 |
+
return obj.items()
|
runtime/Lib/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
New, fast version of the CloudPickler.
|
| 3 |
+
|
| 4 |
+
This new CloudPickler class can now extend the fast C Pickler instead of the
|
| 5 |
+
previous Python implementation of the Pickler class. Because this functionality
|
| 6 |
+
is only available for Python versions 3.8+, a lot of backward-compatibility
|
| 7 |
+
code is also removed.
|
| 8 |
+
|
| 9 |
+
Note that the C Pickler subclassing API is CPython-specific. Therefore, some
|
| 10 |
+
guards present in cloudpickle.py that were written to handle PyPy specificities
|
| 11 |
+
are not present in cloudpickle_fast.py
|
| 12 |
+
"""
|
| 13 |
+
import _collections_abc
|
| 14 |
+
import abc
|
| 15 |
+
import copyreg
|
| 16 |
+
import io
|
| 17 |
+
import itertools
|
| 18 |
+
import logging
|
| 19 |
+
import sys
|
| 20 |
+
import struct
|
| 21 |
+
import types
|
| 22 |
+
import weakref
|
| 23 |
+
import typing
|
| 24 |
+
|
| 25 |
+
from enum import Enum
|
| 26 |
+
from collections import ChainMap, OrderedDict
|
| 27 |
+
|
| 28 |
+
from .compat import pickle, Pickler
|
| 29 |
+
from .cloudpickle import (
|
| 30 |
+
_extract_code_globals, _BUILTIN_TYPE_NAMES, DEFAULT_PROTOCOL,
|
| 31 |
+
_find_imported_submodules, _get_cell_contents, _should_pickle_by_reference,
|
| 32 |
+
_builtin_type, _get_or_create_tracker_id, _make_skeleton_class,
|
| 33 |
+
_make_skeleton_enum, _extract_class_dict, dynamic_subimport, subimport,
|
| 34 |
+
_typevar_reduce, _get_bases, _make_cell, _make_empty_cell, CellType,
|
| 35 |
+
_is_parametrized_type_hint, PYPY, cell_set,
|
| 36 |
+
parametrized_type_hint_getinitargs, _create_parametrized_type_hint,
|
| 37 |
+
builtin_code_type,
|
| 38 |
+
_make_dict_keys, _make_dict_values, _make_dict_items, _make_function,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if pickle.HIGHEST_PROTOCOL >= 5:
|
| 43 |
+
# Shorthands similar to pickle.dump/pickle.dumps
|
| 44 |
+
|
| 45 |
+
def dump(obj, file, protocol=None, buffer_callback=None):
|
| 46 |
+
"""Serialize obj as bytes streamed into file
|
| 47 |
+
|
| 48 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 49 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 50 |
+
speed between processes running the same Python version.
|
| 51 |
+
|
| 52 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 53 |
+
compatibility with older versions of Python.
|
| 54 |
+
"""
|
| 55 |
+
CloudPickler(
|
| 56 |
+
file, protocol=protocol, buffer_callback=buffer_callback
|
| 57 |
+
).dump(obj)
|
| 58 |
+
|
| 59 |
+
def dumps(obj, protocol=None, buffer_callback=None):
|
| 60 |
+
"""Serialize obj as a string of bytes allocated in memory
|
| 61 |
+
|
| 62 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 63 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 64 |
+
speed between processes running the same Python version.
|
| 65 |
+
|
| 66 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 67 |
+
compatibility with older versions of Python.
|
| 68 |
+
"""
|
| 69 |
+
with io.BytesIO() as file:
|
| 70 |
+
cp = CloudPickler(
|
| 71 |
+
file, protocol=protocol, buffer_callback=buffer_callback
|
| 72 |
+
)
|
| 73 |
+
cp.dump(obj)
|
| 74 |
+
return file.getvalue()
|
| 75 |
+
|
| 76 |
+
else:
|
| 77 |
+
# Shorthands similar to pickle.dump/pickle.dumps
|
| 78 |
+
def dump(obj, file, protocol=None):
|
| 79 |
+
"""Serialize obj as bytes streamed into file
|
| 80 |
+
|
| 81 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 82 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 83 |
+
speed between processes running the same Python version.
|
| 84 |
+
|
| 85 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 86 |
+
compatibility with older versions of Python.
|
| 87 |
+
"""
|
| 88 |
+
CloudPickler(file, protocol=protocol).dump(obj)
|
| 89 |
+
|
| 90 |
+
def dumps(obj, protocol=None):
|
| 91 |
+
"""Serialize obj as a string of bytes allocated in memory
|
| 92 |
+
|
| 93 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 94 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 95 |
+
speed between processes running the same Python version.
|
| 96 |
+
|
| 97 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 98 |
+
compatibility with older versions of Python.
|
| 99 |
+
"""
|
| 100 |
+
with io.BytesIO() as file:
|
| 101 |
+
cp = CloudPickler(file, protocol=protocol)
|
| 102 |
+
cp.dump(obj)
|
| 103 |
+
return file.getvalue()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
load, loads = pickle.load, pickle.loads
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
|
| 110 |
+
# -------------------------------------------------
|
| 111 |
+
|
| 112 |
+
def _class_getnewargs(obj):
|
| 113 |
+
type_kwargs = {}
|
| 114 |
+
if "__slots__" in obj.__dict__:
|
| 115 |
+
type_kwargs["__slots__"] = obj.__slots__
|
| 116 |
+
|
| 117 |
+
__dict__ = obj.__dict__.get('__dict__', None)
|
| 118 |
+
if isinstance(__dict__, property):
|
| 119 |
+
type_kwargs['__dict__'] = __dict__
|
| 120 |
+
|
| 121 |
+
return (type(obj), obj.__name__, _get_bases(obj), type_kwargs,
|
| 122 |
+
_get_or_create_tracker_id(obj), None)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _enum_getnewargs(obj):
|
| 126 |
+
members = {e.name: e.value for e in obj}
|
| 127 |
+
return (obj.__bases__, obj.__name__, obj.__qualname__, members,
|
| 128 |
+
obj.__module__, _get_or_create_tracker_id(obj), None)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# COLLECTION OF OBJECTS RECONSTRUCTORS
|
| 132 |
+
# ------------------------------------
|
| 133 |
+
def _file_reconstructor(retval):
|
| 134 |
+
return retval
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# COLLECTION OF OBJECTS STATE GETTERS
|
| 138 |
+
# -----------------------------------
|
| 139 |
+
def _function_getstate(func):
|
| 140 |
+
# - Put func's dynamic attributes (stored in func.__dict__) in state. These
|
| 141 |
+
# attributes will be restored at unpickling time using
|
| 142 |
+
# f.__dict__.update(state)
|
| 143 |
+
# - Put func's members into slotstate. Such attributes will be restored at
|
| 144 |
+
# unpickling time by iterating over slotstate and calling setattr(func,
|
| 145 |
+
# slotname, slotvalue)
|
| 146 |
+
slotstate = {
|
| 147 |
+
"__name__": func.__name__,
|
| 148 |
+
"__qualname__": func.__qualname__,
|
| 149 |
+
"__annotations__": func.__annotations__,
|
| 150 |
+
"__kwdefaults__": func.__kwdefaults__,
|
| 151 |
+
"__defaults__": func.__defaults__,
|
| 152 |
+
"__module__": func.__module__,
|
| 153 |
+
"__doc__": func.__doc__,
|
| 154 |
+
"__closure__": func.__closure__,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
f_globals_ref = _extract_code_globals(func.__code__)
|
| 158 |
+
f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in
|
| 159 |
+
func.__globals__}
|
| 160 |
+
|
| 161 |
+
closure_values = (
|
| 162 |
+
list(map(_get_cell_contents, func.__closure__))
|
| 163 |
+
if func.__closure__ is not None else ()
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# Extract currently-imported submodules used by func. Storing these modules
|
| 167 |
+
# in a smoke _cloudpickle_subimports attribute of the object's state will
|
| 168 |
+
# trigger the side effect of importing these modules at unpickling time
|
| 169 |
+
# (which is necessary for func to work correctly once depickled)
|
| 170 |
+
slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
|
| 171 |
+
func.__code__, itertools.chain(f_globals.values(), closure_values))
|
| 172 |
+
slotstate["__globals__"] = f_globals
|
| 173 |
+
|
| 174 |
+
state = func.__dict__
|
| 175 |
+
return state, slotstate
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _class_getstate(obj):
|
| 179 |
+
clsdict = _extract_class_dict(obj)
|
| 180 |
+
clsdict.pop('__weakref__', None)
|
| 181 |
+
|
| 182 |
+
if issubclass(type(obj), abc.ABCMeta):
|
| 183 |
+
# If obj is an instance of an ABCMeta subclass, don't pickle the
|
| 184 |
+
# cache/negative caches populated during isinstance/issubclass
|
| 185 |
+
# checks, but pickle the list of registered subclasses of obj.
|
| 186 |
+
clsdict.pop('_abc_cache', None)
|
| 187 |
+
clsdict.pop('_abc_negative_cache', None)
|
| 188 |
+
clsdict.pop('_abc_negative_cache_version', None)
|
| 189 |
+
registry = clsdict.pop('_abc_registry', None)
|
| 190 |
+
if registry is None:
|
| 191 |
+
# in Python3.7+, the abc caches and registered subclasses of a
|
| 192 |
+
# class are bundled into the single _abc_impl attribute
|
| 193 |
+
clsdict.pop('_abc_impl', None)
|
| 194 |
+
(registry, _, _, _) = abc._get_dump(obj)
|
| 195 |
+
|
| 196 |
+
clsdict["_abc_impl"] = [subclass_weakref()
|
| 197 |
+
for subclass_weakref in registry]
|
| 198 |
+
else:
|
| 199 |
+
# In the above if clause, registry is a set of weakrefs -- in
|
| 200 |
+
# this case, registry is a WeakSet
|
| 201 |
+
clsdict["_abc_impl"] = [type_ for type_ in registry]
|
| 202 |
+
|
| 203 |
+
if "__slots__" in clsdict:
|
| 204 |
+
# pickle string length optimization: member descriptors of obj are
|
| 205 |
+
# created automatically from obj's __slots__ attribute, no need to
|
| 206 |
+
# save them in obj's state
|
| 207 |
+
if isinstance(obj.__slots__, str):
|
| 208 |
+
clsdict.pop(obj.__slots__)
|
| 209 |
+
else:
|
| 210 |
+
for k in obj.__slots__:
|
| 211 |
+
clsdict.pop(k, None)
|
| 212 |
+
|
| 213 |
+
clsdict.pop('__dict__', None) # unpicklable property object
|
| 214 |
+
|
| 215 |
+
return (clsdict, {})
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _enum_getstate(obj):
|
| 219 |
+
clsdict, slotstate = _class_getstate(obj)
|
| 220 |
+
|
| 221 |
+
members = {e.name: e.value for e in obj}
|
| 222 |
+
# Cleanup the clsdict that will be passed to _rehydrate_skeleton_class:
|
| 223 |
+
# Those attributes are already handled by the metaclass.
|
| 224 |
+
for attrname in ["_generate_next_value_", "_member_names_",
|
| 225 |
+
"_member_map_", "_member_type_",
|
| 226 |
+
"_value2member_map_"]:
|
| 227 |
+
clsdict.pop(attrname, None)
|
| 228 |
+
for member in members:
|
| 229 |
+
clsdict.pop(member)
|
| 230 |
+
# Special handling of Enum subclasses
|
| 231 |
+
return clsdict, slotstate
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# COLLECTIONS OF OBJECTS REDUCERS
|
| 235 |
+
# -------------------------------
|
| 236 |
+
# A reducer is a function taking a single argument (obj), and that returns a
|
| 237 |
+
# tuple with all the necessary data to re-construct obj. Apart from a few
|
| 238 |
+
# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
|
| 239 |
+
# correctly pickle an object.
|
| 240 |
+
# While many built-in objects (Exceptions objects, instances of the "object"
|
| 241 |
+
# class, etc), are shipped with their own built-in reducer (invoked using
|
| 242 |
+
# obj.__reduce__), some do not. The following methods were created to "fill
|
| 243 |
+
# these holes".
|
| 244 |
+
|
| 245 |
+
def _code_reduce(obj):
|
| 246 |
+
"""codeobject reducer"""
|
| 247 |
+
# If you are not sure about the order of arguments, take a look at help
|
| 248 |
+
# of the specific type from types, for example:
|
| 249 |
+
# >>> from types import CodeType
|
| 250 |
+
# >>> help(CodeType)
|
| 251 |
+
if hasattr(obj, "co_exceptiontable"): # pragma: no branch
|
| 252 |
+
# Python 3.11 and later: there are some new attributes
|
| 253 |
+
# related to the enhanced exceptions.
|
| 254 |
+
args = (
|
| 255 |
+
obj.co_argcount, obj.co_posonlyargcount,
|
| 256 |
+
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
|
| 257 |
+
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
|
| 258 |
+
obj.co_varnames, obj.co_filename, obj.co_name, obj.co_qualname,
|
| 259 |
+
obj.co_firstlineno, obj.co_linetable, obj.co_exceptiontable,
|
| 260 |
+
obj.co_freevars, obj.co_cellvars,
|
| 261 |
+
)
|
| 262 |
+
elif hasattr(obj, "co_linetable"): # pragma: no branch
|
| 263 |
+
# Python 3.10 and later: obj.co_lnotab is deprecated and constructor
|
| 264 |
+
# expects obj.co_linetable instead.
|
| 265 |
+
args = (
|
| 266 |
+
obj.co_argcount, obj.co_posonlyargcount,
|
| 267 |
+
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
|
| 268 |
+
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
|
| 269 |
+
obj.co_varnames, obj.co_filename, obj.co_name,
|
| 270 |
+
obj.co_firstlineno, obj.co_linetable, obj.co_freevars,
|
| 271 |
+
obj.co_cellvars
|
| 272 |
+
)
|
| 273 |
+
elif hasattr(obj, "co_nmeta"): # pragma: no cover
|
| 274 |
+
# "nogil" Python: modified attributes from 3.9
|
| 275 |
+
args = (
|
| 276 |
+
obj.co_argcount, obj.co_posonlyargcount,
|
| 277 |
+
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_framesize,
|
| 278 |
+
obj.co_ndefaultargs, obj.co_nmeta,
|
| 279 |
+
obj.co_flags, obj.co_code, obj.co_consts,
|
| 280 |
+
obj.co_varnames, obj.co_filename, obj.co_name,
|
| 281 |
+
obj.co_firstlineno, obj.co_lnotab, obj.co_exc_handlers,
|
| 282 |
+
obj.co_jump_table, obj.co_freevars, obj.co_cellvars,
|
| 283 |
+
obj.co_free2reg, obj.co_cell2reg
|
| 284 |
+
)
|
| 285 |
+
elif hasattr(obj, "co_posonlyargcount"):
|
| 286 |
+
# Backward compat for 3.9 and older
|
| 287 |
+
args = (
|
| 288 |
+
obj.co_argcount, obj.co_posonlyargcount,
|
| 289 |
+
obj.co_kwonlyargcount, obj.co_nlocals, obj.co_stacksize,
|
| 290 |
+
obj.co_flags, obj.co_code, obj.co_consts, obj.co_names,
|
| 291 |
+
obj.co_varnames, obj.co_filename, obj.co_name,
|
| 292 |
+
obj.co_firstlineno, obj.co_lnotab, obj.co_freevars,
|
| 293 |
+
obj.co_cellvars
|
| 294 |
+
)
|
| 295 |
+
else:
|
| 296 |
+
# Backward compat for even older versions of Python
|
| 297 |
+
args = (
|
| 298 |
+
obj.co_argcount, obj.co_kwonlyargcount, obj.co_nlocals,
|
| 299 |
+
obj.co_stacksize, obj.co_flags, obj.co_code, obj.co_consts,
|
| 300 |
+
obj.co_names, obj.co_varnames, obj.co_filename,
|
| 301 |
+
obj.co_name, obj.co_firstlineno, obj.co_lnotab,
|
| 302 |
+
obj.co_freevars, obj.co_cellvars
|
| 303 |
+
)
|
| 304 |
+
return types.CodeType, args
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _cell_reduce(obj):
|
| 308 |
+
"""Cell (containing values of a function's free variables) reducer"""
|
| 309 |
+
try:
|
| 310 |
+
obj.cell_contents
|
| 311 |
+
except ValueError: # cell is empty
|
| 312 |
+
return _make_empty_cell, ()
|
| 313 |
+
else:
|
| 314 |
+
return _make_cell, (obj.cell_contents, )
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _classmethod_reduce(obj):
|
| 318 |
+
orig_func = obj.__func__
|
| 319 |
+
return type(obj), (orig_func,)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _file_reduce(obj):
|
| 323 |
+
"""Save a file"""
|
| 324 |
+
import io
|
| 325 |
+
|
| 326 |
+
if not hasattr(obj, "name") or not hasattr(obj, "mode"):
|
| 327 |
+
raise pickle.PicklingError(
|
| 328 |
+
"Cannot pickle files that do not map to an actual file"
|
| 329 |
+
)
|
| 330 |
+
if obj is sys.stdout:
|
| 331 |
+
return getattr, (sys, "stdout")
|
| 332 |
+
if obj is sys.stderr:
|
| 333 |
+
return getattr, (sys, "stderr")
|
| 334 |
+
if obj is sys.stdin:
|
| 335 |
+
raise pickle.PicklingError("Cannot pickle standard input")
|
| 336 |
+
if obj.closed:
|
| 337 |
+
raise pickle.PicklingError("Cannot pickle closed files")
|
| 338 |
+
if hasattr(obj, "isatty") and obj.isatty():
|
| 339 |
+
raise pickle.PicklingError(
|
| 340 |
+
"Cannot pickle files that map to tty objects"
|
| 341 |
+
)
|
| 342 |
+
if "r" not in obj.mode and "+" not in obj.mode:
|
| 343 |
+
raise pickle.PicklingError(
|
| 344 |
+
"Cannot pickle files that are not opened for reading: %s"
|
| 345 |
+
% obj.mode
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
name = obj.name
|
| 349 |
+
|
| 350 |
+
retval = io.StringIO()
|
| 351 |
+
|
| 352 |
+
try:
|
| 353 |
+
# Read the whole file
|
| 354 |
+
curloc = obj.tell()
|
| 355 |
+
obj.seek(0)
|
| 356 |
+
contents = obj.read()
|
| 357 |
+
obj.seek(curloc)
|
| 358 |
+
except IOError as e:
|
| 359 |
+
raise pickle.PicklingError(
|
| 360 |
+
"Cannot pickle file %s as it cannot be read" % name
|
| 361 |
+
) from e
|
| 362 |
+
retval.write(contents)
|
| 363 |
+
retval.seek(curloc)
|
| 364 |
+
|
| 365 |
+
retval.name = name
|
| 366 |
+
return _file_reconstructor, (retval,)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _getset_descriptor_reduce(obj):
|
| 370 |
+
return getattr, (obj.__objclass__, obj.__name__)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _mappingproxy_reduce(obj):
|
| 374 |
+
return types.MappingProxyType, (dict(obj),)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _memoryview_reduce(obj):
|
| 378 |
+
return bytes, (obj.tobytes(),)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _module_reduce(obj):
|
| 382 |
+
if _should_pickle_by_reference(obj):
|
| 383 |
+
return subimport, (obj.__name__,)
|
| 384 |
+
else:
|
| 385 |
+
# Some external libraries can populate the "__builtins__" entry of a
|
| 386 |
+
# module's `__dict__` with unpicklable objects (see #316). For that
|
| 387 |
+
# reason, we do not attempt to pickle the "__builtins__" entry, and
|
| 388 |
+
# restore a default value for it at unpickling time.
|
| 389 |
+
state = obj.__dict__.copy()
|
| 390 |
+
state.pop('__builtins__', None)
|
| 391 |
+
return dynamic_subimport, (obj.__name__, state)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _method_reduce(obj):
|
| 395 |
+
return (types.MethodType, (obj.__func__, obj.__self__))
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _logger_reduce(obj):
|
| 399 |
+
return logging.getLogger, (obj.name,)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _root_logger_reduce(obj):
|
| 403 |
+
return logging.getLogger, ()
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _property_reduce(obj):
|
| 407 |
+
return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _weakset_reduce(obj):
|
| 411 |
+
return weakref.WeakSet, (list(obj),)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def _dynamic_class_reduce(obj):
|
| 415 |
+
"""
|
| 416 |
+
Save a class that can't be stored as module global.
|
| 417 |
+
|
| 418 |
+
This method is used to serialize classes that are defined inside
|
| 419 |
+
functions, or that otherwise can't be serialized as attribute lookups
|
| 420 |
+
from global modules.
|
| 421 |
+
"""
|
| 422 |
+
if Enum is not None and issubclass(obj, Enum):
|
| 423 |
+
return (
|
| 424 |
+
_make_skeleton_enum, _enum_getnewargs(obj), _enum_getstate(obj),
|
| 425 |
+
None, None, _class_setstate
|
| 426 |
+
)
|
| 427 |
+
else:
|
| 428 |
+
return (
|
| 429 |
+
_make_skeleton_class, _class_getnewargs(obj), _class_getstate(obj),
|
| 430 |
+
None, None, _class_setstate
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _class_reduce(obj):
|
| 435 |
+
"""Select the reducer depending on the dynamic nature of the class obj"""
|
| 436 |
+
if obj is type(None): # noqa
|
| 437 |
+
return type, (None,)
|
| 438 |
+
elif obj is type(Ellipsis):
|
| 439 |
+
return type, (Ellipsis,)
|
| 440 |
+
elif obj is type(NotImplemented):
|
| 441 |
+
return type, (NotImplemented,)
|
| 442 |
+
elif obj in _BUILTIN_TYPE_NAMES:
|
| 443 |
+
return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
|
| 444 |
+
elif not _should_pickle_by_reference(obj):
|
| 445 |
+
return _dynamic_class_reduce(obj)
|
| 446 |
+
return NotImplemented
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _dict_keys_reduce(obj):
|
| 450 |
+
# Safer not to ship the full dict as sending the rest might
|
| 451 |
+
# be unintended and could potentially cause leaking of
|
| 452 |
+
# sensitive information
|
| 453 |
+
return _make_dict_keys, (list(obj), )
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _dict_values_reduce(obj):
|
| 457 |
+
# Safer not to ship the full dict as sending the rest might
|
| 458 |
+
# be unintended and could potentially cause leaking of
|
| 459 |
+
# sensitive information
|
| 460 |
+
return _make_dict_values, (list(obj), )
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _dict_items_reduce(obj):
|
| 464 |
+
return _make_dict_items, (dict(obj), )
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def _odict_keys_reduce(obj):
|
| 468 |
+
# Safer not to ship the full dict as sending the rest might
|
| 469 |
+
# be unintended and could potentially cause leaking of
|
| 470 |
+
# sensitive information
|
| 471 |
+
return _make_dict_keys, (list(obj), True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _odict_values_reduce(obj):
|
| 475 |
+
# Safer not to ship the full dict as sending the rest might
|
| 476 |
+
# be unintended and could potentially cause leaking of
|
| 477 |
+
# sensitive information
|
| 478 |
+
return _make_dict_values, (list(obj), True)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def _odict_items_reduce(obj):
|
| 482 |
+
return _make_dict_items, (dict(obj), True)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
# COLLECTIONS OF OBJECTS STATE SETTERS
|
| 486 |
+
# ------------------------------------
|
| 487 |
+
# state setters are called at unpickling time, once the object is created and
|
| 488 |
+
# it has to be updated to how it was at unpickling time.
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _function_setstate(obj, state):
|
| 492 |
+
"""Update the state of a dynamic function.
|
| 493 |
+
|
| 494 |
+
As __closure__ and __globals__ are readonly attributes of a function, we
|
| 495 |
+
cannot rely on the native setstate routine of pickle.load_build, that calls
|
| 496 |
+
setattr on items of the slotstate. Instead, we have to modify them inplace.
|
| 497 |
+
"""
|
| 498 |
+
state, slotstate = state
|
| 499 |
+
obj.__dict__.update(state)
|
| 500 |
+
|
| 501 |
+
obj_globals = slotstate.pop("__globals__")
|
| 502 |
+
obj_closure = slotstate.pop("__closure__")
|
| 503 |
+
# _cloudpickle_subimports is a set of submodules that must be loaded for
|
| 504 |
+
# the pickled function to work correctly at unpickling time. Now that these
|
| 505 |
+
# submodules are depickled (hence imported), they can be removed from the
|
| 506 |
+
# object's state (the object state only served as a reference holder to
|
| 507 |
+
# these submodules)
|
| 508 |
+
slotstate.pop("_cloudpickle_submodules")
|
| 509 |
+
|
| 510 |
+
obj.__globals__.update(obj_globals)
|
| 511 |
+
obj.__globals__["__builtins__"] = __builtins__
|
| 512 |
+
|
| 513 |
+
if obj_closure is not None:
|
| 514 |
+
for i, cell in enumerate(obj_closure):
|
| 515 |
+
try:
|
| 516 |
+
value = cell.cell_contents
|
| 517 |
+
except ValueError: # cell is empty
|
| 518 |
+
continue
|
| 519 |
+
cell_set(obj.__closure__[i], value)
|
| 520 |
+
|
| 521 |
+
for k, v in slotstate.items():
|
| 522 |
+
setattr(obj, k, v)
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def _class_setstate(obj, state):
|
| 526 |
+
state, slotstate = state
|
| 527 |
+
registry = None
|
| 528 |
+
for attrname, attr in state.items():
|
| 529 |
+
if attrname == "_abc_impl":
|
| 530 |
+
registry = attr
|
| 531 |
+
else:
|
| 532 |
+
setattr(obj, attrname, attr)
|
| 533 |
+
if registry is not None:
|
| 534 |
+
for subclass in registry:
|
| 535 |
+
obj.register(subclass)
|
| 536 |
+
|
| 537 |
+
return obj
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class CloudPickler(Pickler):
|
| 541 |
+
# set of reducers defined and used by cloudpickle (private)
|
| 542 |
+
_dispatch_table = {}
|
| 543 |
+
_dispatch_table[classmethod] = _classmethod_reduce
|
| 544 |
+
_dispatch_table[io.TextIOWrapper] = _file_reduce
|
| 545 |
+
_dispatch_table[logging.Logger] = _logger_reduce
|
| 546 |
+
_dispatch_table[logging.RootLogger] = _root_logger_reduce
|
| 547 |
+
_dispatch_table[memoryview] = _memoryview_reduce
|
| 548 |
+
_dispatch_table[property] = _property_reduce
|
| 549 |
+
_dispatch_table[staticmethod] = _classmethod_reduce
|
| 550 |
+
_dispatch_table[CellType] = _cell_reduce
|
| 551 |
+
_dispatch_table[types.CodeType] = _code_reduce
|
| 552 |
+
_dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce
|
| 553 |
+
_dispatch_table[types.ModuleType] = _module_reduce
|
| 554 |
+
_dispatch_table[types.MethodType] = _method_reduce
|
| 555 |
+
_dispatch_table[types.MappingProxyType] = _mappingproxy_reduce
|
| 556 |
+
_dispatch_table[weakref.WeakSet] = _weakset_reduce
|
| 557 |
+
_dispatch_table[typing.TypeVar] = _typevar_reduce
|
| 558 |
+
_dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce
|
| 559 |
+
_dispatch_table[_collections_abc.dict_values] = _dict_values_reduce
|
| 560 |
+
_dispatch_table[_collections_abc.dict_items] = _dict_items_reduce
|
| 561 |
+
_dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce
|
| 562 |
+
_dispatch_table[type(OrderedDict().values())] = _odict_values_reduce
|
| 563 |
+
_dispatch_table[type(OrderedDict().items())] = _odict_items_reduce
|
| 564 |
+
_dispatch_table[abc.abstractmethod] = _classmethod_reduce
|
| 565 |
+
_dispatch_table[abc.abstractclassmethod] = _classmethod_reduce
|
| 566 |
+
_dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce
|
| 567 |
+
_dispatch_table[abc.abstractproperty] = _property_reduce
|
| 568 |
+
|
| 569 |
+
dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table)
|
| 570 |
+
|
| 571 |
+
# function reducers are defined as instance methods of CloudPickler
|
| 572 |
+
# objects, as they rely on a CloudPickler attribute (globals_ref)
|
| 573 |
+
def _dynamic_function_reduce(self, func):
|
| 574 |
+
"""Reduce a function that is not pickleable via attribute lookup."""
|
| 575 |
+
newargs = self._function_getnewargs(func)
|
| 576 |
+
state = _function_getstate(func)
|
| 577 |
+
return (_make_function, newargs, state, None, None,
|
| 578 |
+
_function_setstate)
|
| 579 |
+
|
| 580 |
+
def _function_reduce(self, obj):
|
| 581 |
+
"""Reducer for function objects.
|
| 582 |
+
|
| 583 |
+
If obj is a top-level attribute of a file-backed module, this
|
| 584 |
+
reducer returns NotImplemented, making the CloudPickler fallback to
|
| 585 |
+
traditional _pickle.Pickler routines to save obj. Otherwise, it reduces
|
| 586 |
+
obj using a custom cloudpickle reducer designed specifically to handle
|
| 587 |
+
dynamic functions.
|
| 588 |
+
|
| 589 |
+
As opposed to cloudpickle.py, There no special handling for builtin
|
| 590 |
+
pypy functions because cloudpickle_fast is CPython-specific.
|
| 591 |
+
"""
|
| 592 |
+
if _should_pickle_by_reference(obj):
|
| 593 |
+
return NotImplemented
|
| 594 |
+
else:
|
| 595 |
+
return self._dynamic_function_reduce(obj)
|
| 596 |
+
|
| 597 |
+
def _function_getnewargs(self, func):
|
| 598 |
+
code = func.__code__
|
| 599 |
+
|
| 600 |
+
# base_globals represents the future global namespace of func at
|
| 601 |
+
# unpickling time. Looking it up and storing it in
|
| 602 |
+
# CloudpiPickler.globals_ref allow functions sharing the same globals
|
| 603 |
+
# at pickling time to also share them once unpickled, at one condition:
|
| 604 |
+
# since globals_ref is an attribute of a CloudPickler instance, and
|
| 605 |
+
# that a new CloudPickler is created each time pickle.dump or
|
| 606 |
+
# pickle.dumps is called, functions also need to be saved within the
|
| 607 |
+
# same invocation of cloudpickle.dump/cloudpickle.dumps (for example:
|
| 608 |
+
# cloudpickle.dumps([f1, f2])). There is no such limitation when using
|
| 609 |
+
# CloudPickler.dump, as long as the multiple invocations are bound to
|
| 610 |
+
# the same CloudPickler.
|
| 611 |
+
base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
|
| 612 |
+
|
| 613 |
+
if base_globals == {}:
|
| 614 |
+
# Add module attributes used to resolve relative imports
|
| 615 |
+
# instructions inside func.
|
| 616 |
+
for k in ["__package__", "__name__", "__path__", "__file__"]:
|
| 617 |
+
if k in func.__globals__:
|
| 618 |
+
base_globals[k] = func.__globals__[k]
|
| 619 |
+
|
| 620 |
+
# Do not bind the free variables before the function is created to
|
| 621 |
+
# avoid infinite recursion.
|
| 622 |
+
if func.__closure__ is None:
|
| 623 |
+
closure = None
|
| 624 |
+
else:
|
| 625 |
+
closure = tuple(
|
| 626 |
+
_make_empty_cell() for _ in range(len(code.co_freevars)))
|
| 627 |
+
|
| 628 |
+
return code, base_globals, None, None, closure
|
| 629 |
+
|
| 630 |
+
def dump(self, obj):
|
| 631 |
+
try:
|
| 632 |
+
return Pickler.dump(self, obj)
|
| 633 |
+
except RuntimeError as e:
|
| 634 |
+
if "recursion" in e.args[0]:
|
| 635 |
+
msg = (
|
| 636 |
+
"Could not pickle object as excessively deep recursion "
|
| 637 |
+
"required."
|
| 638 |
+
)
|
| 639 |
+
raise pickle.PicklingError(msg) from e
|
| 640 |
+
else:
|
| 641 |
+
raise
|
| 642 |
+
|
| 643 |
+
if pickle.HIGHEST_PROTOCOL >= 5:
|
| 644 |
+
def __init__(self, file, protocol=None, buffer_callback=None):
|
| 645 |
+
if protocol is None:
|
| 646 |
+
protocol = DEFAULT_PROTOCOL
|
| 647 |
+
Pickler.__init__(
|
| 648 |
+
self, file, protocol=protocol, buffer_callback=buffer_callback
|
| 649 |
+
)
|
| 650 |
+
# map functions __globals__ attribute ids, to ensure that functions
|
| 651 |
+
# sharing the same global namespace at pickling time also share
|
| 652 |
+
# their global namespace at unpickling time.
|
| 653 |
+
self.globals_ref = {}
|
| 654 |
+
self.proto = int(protocol)
|
| 655 |
+
else:
|
| 656 |
+
def __init__(self, file, protocol=None):
|
| 657 |
+
if protocol is None:
|
| 658 |
+
protocol = DEFAULT_PROTOCOL
|
| 659 |
+
Pickler.__init__(self, file, protocol=protocol)
|
| 660 |
+
# map functions __globals__ attribute ids, to ensure that functions
|
| 661 |
+
# sharing the same global namespace at pickling time also share
|
| 662 |
+
# their global namespace at unpickling time.
|
| 663 |
+
self.globals_ref = {}
|
| 664 |
+
assert hasattr(self, 'proto')
|
| 665 |
+
|
| 666 |
+
if pickle.HIGHEST_PROTOCOL >= 5 and not PYPY:
|
| 667 |
+
# Pickler is the C implementation of the CPython pickler and therefore
|
| 668 |
+
# we rely on reduce_override method to customize the pickler behavior.
|
| 669 |
+
|
| 670 |
+
# `CloudPickler.dispatch` is only left for backward compatibility - note
|
| 671 |
+
# that when using protocol 5, `CloudPickler.dispatch` is not an
|
| 672 |
+
# extension of `Pickler.dispatch` dictionary, because CloudPickler
|
| 673 |
+
# subclasses the C-implemented Pickler, which does not expose a
|
| 674 |
+
# `dispatch` attribute. Earlier versions of the protocol 5 CloudPickler
|
| 675 |
+
# used `CloudPickler.dispatch` as a class-level attribute storing all
|
| 676 |
+
# reducers implemented by cloudpickle, but the attribute name was not a
|
| 677 |
+
# great choice given the meaning of `CloudPickler.dispatch` when
|
| 678 |
+
# `CloudPickler` extends the pure-python pickler.
|
| 679 |
+
dispatch = dispatch_table
|
| 680 |
+
|
| 681 |
+
# Implementation of the reducer_override callback, in order to
|
| 682 |
+
# efficiently serialize dynamic functions and classes by subclassing
|
| 683 |
+
# the C-implemented Pickler.
|
| 684 |
+
# TODO: decorrelate reducer_override (which is tied to CPython's
|
| 685 |
+
# implementation - would it make sense to backport it to pypy? - and
|
| 686 |
+
# pickle's protocol 5 which is implementation agnostic. Currently, the
|
| 687 |
+
# availability of both notions coincide on CPython's pickle and the
|
| 688 |
+
# pickle5 backport, but it may not be the case anymore when pypy
|
| 689 |
+
# implements protocol 5
|
| 690 |
+
|
| 691 |
+
def reducer_override(self, obj):
|
| 692 |
+
"""Type-agnostic reducing callback for function and classes.
|
| 693 |
+
|
| 694 |
+
For performance reasons, subclasses of the C _pickle.Pickler class
|
| 695 |
+
cannot register custom reducers for functions and classes in the
|
| 696 |
+
dispatch_table. Reducer for such types must instead implemented in
|
| 697 |
+
the special reducer_override method.
|
| 698 |
+
|
| 699 |
+
Note that method will be called for any object except a few
|
| 700 |
+
builtin-types (int, lists, dicts etc.), which differs from reducers
|
| 701 |
+
in the Pickler's dispatch_table, each of them being invoked for
|
| 702 |
+
objects of a specific type only.
|
| 703 |
+
|
| 704 |
+
This property comes in handy for classes: although most classes are
|
| 705 |
+
instances of the ``type`` metaclass, some of them can be instances
|
| 706 |
+
of other custom metaclasses (such as enum.EnumMeta for example). In
|
| 707 |
+
particular, the metaclass will likely not be known in advance, and
|
| 708 |
+
thus cannot be special-cased using an entry in the dispatch_table.
|
| 709 |
+
reducer_override, among other things, allows us to register a
|
| 710 |
+
reducer that will be called for any class, independently of its
|
| 711 |
+
type.
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
Notes:
|
| 715 |
+
|
| 716 |
+
* reducer_override has the priority over dispatch_table-registered
|
| 717 |
+
reducers.
|
| 718 |
+
* reducer_override can be used to fix other limitations of
|
| 719 |
+
cloudpickle for other types that suffered from type-specific
|
| 720 |
+
reducers, such as Exceptions. See
|
| 721 |
+
https://github.com/cloudpipe/cloudpickle/issues/248
|
| 722 |
+
"""
|
| 723 |
+
if sys.version_info[:2] < (3, 7) and _is_parametrized_type_hint(obj): # noqa # pragma: no branch
|
| 724 |
+
return (
|
| 725 |
+
_create_parametrized_type_hint,
|
| 726 |
+
parametrized_type_hint_getinitargs(obj)
|
| 727 |
+
)
|
| 728 |
+
t = type(obj)
|
| 729 |
+
try:
|
| 730 |
+
is_anyclass = issubclass(t, type)
|
| 731 |
+
except TypeError: # t is not a class (old Boost; see SF #502085)
|
| 732 |
+
is_anyclass = False
|
| 733 |
+
|
| 734 |
+
if is_anyclass:
|
| 735 |
+
return _class_reduce(obj)
|
| 736 |
+
elif isinstance(obj, types.FunctionType):
|
| 737 |
+
return self._function_reduce(obj)
|
| 738 |
+
else:
|
| 739 |
+
# fallback to save_global, including the Pickler's
|
| 740 |
+
# dispatch_table
|
| 741 |
+
return NotImplemented
|
| 742 |
+
|
| 743 |
+
else:
|
| 744 |
+
# When reducer_override is not available, hack the pure-Python
|
| 745 |
+
# Pickler's types.FunctionType and type savers. Note: the type saver
|
| 746 |
+
# must override Pickler.save_global, because pickle.py contains a
|
| 747 |
+
# hard-coded call to save_global when pickling meta-classes.
|
| 748 |
+
dispatch = Pickler.dispatch.copy()
|
| 749 |
+
|
| 750 |
+
def _save_reduce_pickle5(self, func, args, state=None, listitems=None,
|
| 751 |
+
dictitems=None, state_setter=None, obj=None):
|
| 752 |
+
save = self.save
|
| 753 |
+
write = self.write
|
| 754 |
+
self.save_reduce(
|
| 755 |
+
func, args, state=None, listitems=listitems,
|
| 756 |
+
dictitems=dictitems, obj=obj
|
| 757 |
+
)
|
| 758 |
+
# backport of the Python 3.8 state_setter pickle operations
|
| 759 |
+
save(state_setter)
|
| 760 |
+
save(obj) # simple BINGET opcode as obj is already memoized.
|
| 761 |
+
save(state)
|
| 762 |
+
write(pickle.TUPLE2)
|
| 763 |
+
# Trigger a state_setter(obj, state) function call.
|
| 764 |
+
write(pickle.REDUCE)
|
| 765 |
+
# The purpose of state_setter is to carry-out an
|
| 766 |
+
# inplace modification of obj. We do not care about what the
|
| 767 |
+
# method might return, so its output is eventually removed from
|
| 768 |
+
# the stack.
|
| 769 |
+
write(pickle.POP)
|
| 770 |
+
|
| 771 |
+
def save_global(self, obj, name=None, pack=struct.pack):
|
| 772 |
+
"""
|
| 773 |
+
Save a "global".
|
| 774 |
+
|
| 775 |
+
The name of this method is somewhat misleading: all types get
|
| 776 |
+
dispatched here.
|
| 777 |
+
"""
|
| 778 |
+
if obj is type(None): # noqa
|
| 779 |
+
return self.save_reduce(type, (None,), obj=obj)
|
| 780 |
+
elif obj is type(Ellipsis):
|
| 781 |
+
return self.save_reduce(type, (Ellipsis,), obj=obj)
|
| 782 |
+
elif obj is type(NotImplemented):
|
| 783 |
+
return self.save_reduce(type, (NotImplemented,), obj=obj)
|
| 784 |
+
elif obj in _BUILTIN_TYPE_NAMES:
|
| 785 |
+
return self.save_reduce(
|
| 786 |
+
_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj)
|
| 787 |
+
|
| 788 |
+
if sys.version_info[:2] < (3, 7) and _is_parametrized_type_hint(obj): # noqa # pragma: no branch
|
| 789 |
+
# Parametrized typing constructs in Python < 3.7 are not
|
| 790 |
+
# compatible with type checks and ``isinstance`` semantics. For
|
| 791 |
+
# this reason, it is easier to detect them using a
|
| 792 |
+
# duck-typing-based check (``_is_parametrized_type_hint``) than
|
| 793 |
+
# to populate the Pickler's dispatch with type-specific savers.
|
| 794 |
+
self.save_reduce(
|
| 795 |
+
_create_parametrized_type_hint,
|
| 796 |
+
parametrized_type_hint_getinitargs(obj),
|
| 797 |
+
obj=obj
|
| 798 |
+
)
|
| 799 |
+
elif name is not None:
|
| 800 |
+
Pickler.save_global(self, obj, name=name)
|
| 801 |
+
elif not _should_pickle_by_reference(obj, name=name):
|
| 802 |
+
self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj)
|
| 803 |
+
else:
|
| 804 |
+
Pickler.save_global(self, obj, name=name)
|
| 805 |
+
dispatch[type] = save_global
|
| 806 |
+
|
| 807 |
+
def save_function(self, obj, name=None):
|
| 808 |
+
""" Registered with the dispatch to handle all function types.
|
| 809 |
+
|
| 810 |
+
Determines what kind of function obj is (e.g. lambda, defined at
|
| 811 |
+
interactive prompt, etc) and handles the pickling appropriately.
|
| 812 |
+
"""
|
| 813 |
+
if _should_pickle_by_reference(obj, name=name):
|
| 814 |
+
return Pickler.save_global(self, obj, name=name)
|
| 815 |
+
elif PYPY and isinstance(obj.__code__, builtin_code_type):
|
| 816 |
+
return self.save_pypy_builtin_func(obj)
|
| 817 |
+
else:
|
| 818 |
+
return self._save_reduce_pickle5(
|
| 819 |
+
*self._dynamic_function_reduce(obj), obj=obj
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
def save_pypy_builtin_func(self, obj):
|
| 823 |
+
"""Save pypy equivalent of builtin functions.
|
| 824 |
+
PyPy does not have the concept of builtin-functions. Instead,
|
| 825 |
+
builtin-functions are simple function instances, but with a
|
| 826 |
+
builtin-code attribute.
|
| 827 |
+
Most of the time, builtin functions should be pickled by attribute.
|
| 828 |
+
But PyPy has flaky support for __qualname__, so some builtin
|
| 829 |
+
functions such as float.__new__ will be classified as dynamic. For
|
| 830 |
+
this reason only, we created this special routine. Because
|
| 831 |
+
builtin-functions are not expected to have closure or globals,
|
| 832 |
+
there is no additional hack (compared the one already implemented
|
| 833 |
+
in pickle) to protect ourselves from reference cycles. A simple
|
| 834 |
+
(reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note
|
| 835 |
+
also that PyPy improved their support for __qualname__ in v3.6, so
|
| 836 |
+
this routing should be removed when cloudpickle supports only PyPy
|
| 837 |
+
3.6 and later.
|
| 838 |
+
"""
|
| 839 |
+
rv = (types.FunctionType, (obj.__code__, {}, obj.__name__,
|
| 840 |
+
obj.__defaults__, obj.__closure__),
|
| 841 |
+
obj.__dict__)
|
| 842 |
+
self.save_reduce(*rv, obj=obj)
|
| 843 |
+
|
| 844 |
+
dispatch[types.FunctionType] = save_function
|
runtime/Lib/site-packages/joblib/externals/cloudpickle/compat.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
if sys.version_info < (3, 8):
|
| 5 |
+
try:
|
| 6 |
+
import pickle5 as pickle # noqa: F401
|
| 7 |
+
from pickle5 import Pickler # noqa: F401
|
| 8 |
+
except ImportError:
|
| 9 |
+
import pickle # noqa: F401
|
| 10 |
+
|
| 11 |
+
# Use the Python pickler for old CPython versions
|
| 12 |
+
from pickle import _Pickler as Pickler # noqa: F401
|
| 13 |
+
else:
|
| 14 |
+
import pickle # noqa: F401
|
| 15 |
+
|
| 16 |
+
# Pickler will the C implementation in CPython and the Python
|
| 17 |
+
# implementation in PyPy
|
| 18 |
+
from pickle import Pickler # noqa: F401
|
runtime/Lib/site-packages/joblib/externals/loky/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""The :mod:`loky` module manages a pool of worker that can be re-used across time.
|
| 2 |
+
It provides a robust and dynamic implementation os the
|
| 3 |
+
:class:`ProcessPoolExecutor` and a function :func:`get_reusable_executor` which
|
| 4 |
+
hide the pool management under the hood.
|
| 5 |
+
"""
|
| 6 |
+
from concurrent.futures import (
|
| 7 |
+
ALL_COMPLETED,
|
| 8 |
+
FIRST_COMPLETED,
|
| 9 |
+
FIRST_EXCEPTION,
|
| 10 |
+
CancelledError,
|
| 11 |
+
Executor,
|
| 12 |
+
TimeoutError,
|
| 13 |
+
as_completed,
|
| 14 |
+
wait,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from ._base import Future
|
| 18 |
+
from .backend.context import cpu_count
|
| 19 |
+
from .backend.reduction import set_loky_pickler
|
| 20 |
+
from .reusable_executor import get_reusable_executor
|
| 21 |
+
from .cloudpickle_wrapper import wrap_non_picklable_objects
|
| 22 |
+
from .process_executor import BrokenProcessPool, ProcessPoolExecutor
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
__all__ = ["get_reusable_executor", "cpu_count", "wait", "as_completed",
|
| 26 |
+
"Future", "Executor", "ProcessPoolExecutor",
|
| 27 |
+
"BrokenProcessPool", "CancelledError", "TimeoutError",
|
| 28 |
+
"FIRST_COMPLETED", "FIRST_EXCEPTION", "ALL_COMPLETED",
|
| 29 |
+
"wrap_non_picklable_objects", "set_loky_pickler"]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
__version__ = '3.3.0'
|
runtime/Lib/site-packages/joblib/externals/loky/_base.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Modification of concurrent.futures.Future
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from concurrent/futures/_base.py (17/02/2017)
|
| 7 |
+
# * Do not use yield from
|
| 8 |
+
# * Use old super syntax
|
| 9 |
+
#
|
| 10 |
+
# Copyright 2009 Brian Quinlan. All Rights Reserved.
|
| 11 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 12 |
+
|
| 13 |
+
from concurrent.futures import Future as _BaseFuture
|
| 14 |
+
from concurrent.futures._base import LOGGER
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# To make loky._base.Future instances awaitable by concurrent.futures.wait,
|
| 18 |
+
# derive our custom Future class from _BaseFuture. _invoke_callback is the only
|
| 19 |
+
# modification made to this class in loky.
|
| 20 |
+
# TODO investigate why using `concurrent.futures.Future` directly does not
|
| 21 |
+
# always work in our test suite.
|
| 22 |
+
class Future(_BaseFuture):
|
| 23 |
+
def _invoke_callbacks(self):
|
| 24 |
+
for callback in self._done_callbacks:
|
| 25 |
+
try:
|
| 26 |
+
callback(self)
|
| 27 |
+
except BaseException:
|
| 28 |
+
LOGGER.exception(f'exception calling callback for {self!r}')
|
runtime/Lib/site-packages/joblib/externals/loky/backend/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from multiprocessing import synchronize
|
| 3 |
+
|
| 4 |
+
from .context import get_context
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _make_name():
|
| 8 |
+
return f'/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}'
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# monkey patch the name creation for multiprocessing
|
| 12 |
+
synchronize.SemLock._make_name = staticmethod(_make_name)
|
| 13 |
+
|
| 14 |
+
__all__ = ["get_context"]
|
runtime/Lib/site-packages/joblib/externals/loky/backend/_posix_reduction.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Extra reducers for Unix based system and connections objects
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/reduction.py (17/02/2017)
|
| 7 |
+
# * Add adapted reduction for LokyProcesses and socket/Connection
|
| 8 |
+
#
|
| 9 |
+
import os
|
| 10 |
+
import socket
|
| 11 |
+
import _socket
|
| 12 |
+
from multiprocessing.connection import Connection
|
| 13 |
+
from multiprocessing.context import get_spawning_popen
|
| 14 |
+
|
| 15 |
+
from .reduction import register
|
| 16 |
+
|
| 17 |
+
HAVE_SEND_HANDLE = (hasattr(socket, 'CMSG_LEN') and
|
| 18 |
+
hasattr(socket, 'SCM_RIGHTS') and
|
| 19 |
+
hasattr(socket.socket, 'sendmsg'))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _mk_inheritable(fd):
|
| 23 |
+
os.set_inheritable(fd, True)
|
| 24 |
+
return fd
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def DupFd(fd):
|
| 28 |
+
'''Return a wrapper for an fd.'''
|
| 29 |
+
popen_obj = get_spawning_popen()
|
| 30 |
+
if popen_obj is not None:
|
| 31 |
+
return popen_obj.DupFd(popen_obj.duplicate_for_child(fd))
|
| 32 |
+
elif HAVE_SEND_HANDLE:
|
| 33 |
+
from multiprocessing import resource_sharer
|
| 34 |
+
return resource_sharer.DupFd(fd)
|
| 35 |
+
else:
|
| 36 |
+
raise TypeError(
|
| 37 |
+
'Cannot pickle connection object. This object can only be '
|
| 38 |
+
'passed when spawning a new process'
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _reduce_socket(s):
|
| 43 |
+
df = DupFd(s.fileno())
|
| 44 |
+
return _rebuild_socket, (df, s.family, s.type, s.proto)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _rebuild_socket(df, family, type, proto):
|
| 48 |
+
fd = df.detach()
|
| 49 |
+
return socket.fromfd(fd, family, type, proto)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def rebuild_connection(df, readable, writable):
|
| 53 |
+
fd = df.detach()
|
| 54 |
+
return Connection(fd, readable, writable)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def reduce_connection(conn):
|
| 58 |
+
df = DupFd(conn.fileno())
|
| 59 |
+
return rebuild_connection, (df, conn.readable, conn.writable)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
register(socket.socket, _reduce_socket)
|
| 63 |
+
register(_socket.socket, _reduce_socket)
|
| 64 |
+
register(Connection, reduce_connection)
|
runtime/Lib/site-packages/joblib/externals/loky/backend/_win_reduction.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Extra reducers for Windows system and connections objects
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/reduction.py (17/02/2017)
|
| 7 |
+
# * Add adapted reduction for LokyProcesses and socket/PipeConnection
|
| 8 |
+
#
|
| 9 |
+
import os
|
| 10 |
+
import socket
|
| 11 |
+
import _winapi
|
| 12 |
+
from multiprocessing.connection import PipeConnection
|
| 13 |
+
from multiprocessing.reduction import _reduce_socket
|
| 14 |
+
|
| 15 |
+
from .reduction import register
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DupHandle:
|
| 19 |
+
def __init__(self, handle, access, pid=None):
|
| 20 |
+
# duplicate handle for process with given pid
|
| 21 |
+
if pid is None:
|
| 22 |
+
pid = os.getpid()
|
| 23 |
+
proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False, pid)
|
| 24 |
+
try:
|
| 25 |
+
self._handle = _winapi.DuplicateHandle(
|
| 26 |
+
_winapi.GetCurrentProcess(),
|
| 27 |
+
handle, proc, access, False, 0)
|
| 28 |
+
finally:
|
| 29 |
+
_winapi.CloseHandle(proc)
|
| 30 |
+
self._access = access
|
| 31 |
+
self._pid = pid
|
| 32 |
+
|
| 33 |
+
def detach(self):
|
| 34 |
+
# retrieve handle from process which currently owns it
|
| 35 |
+
if self._pid == os.getpid():
|
| 36 |
+
return self._handle
|
| 37 |
+
proc = _winapi.OpenProcess(_winapi.PROCESS_DUP_HANDLE, False,
|
| 38 |
+
self._pid)
|
| 39 |
+
try:
|
| 40 |
+
return _winapi.DuplicateHandle(
|
| 41 |
+
proc, self._handle, _winapi.GetCurrentProcess(),
|
| 42 |
+
self._access, False, _winapi.DUPLICATE_CLOSE_SOURCE)
|
| 43 |
+
finally:
|
| 44 |
+
_winapi.CloseHandle(proc)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def rebuild_pipe_connection(dh, readable, writable):
|
| 48 |
+
handle = dh.detach()
|
| 49 |
+
return PipeConnection(handle, readable, writable)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def reduce_pipe_connection(conn):
|
| 53 |
+
access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
|
| 54 |
+
(_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
|
| 55 |
+
dh = DupHandle(conn.fileno(), access)
|
| 56 |
+
return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
register(PipeConnection, reduce_pipe_connection)
|
| 60 |
+
register(socket.socket, _reduce_socket)
|
runtime/Lib/site-packages/joblib/externals/loky/backend/context.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Basic context management with LokyContext
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/context.py
|
| 7 |
+
# * Create a context ensuring loky uses only objects that are compatible
|
| 8 |
+
# * Add LokyContext to the list of context of multiprocessing so loky can be
|
| 9 |
+
# used with multiprocessing.set_start_method
|
| 10 |
+
# * Implement a CFS-aware amd physical-core aware cpu_count function.
|
| 11 |
+
#
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import math
|
| 15 |
+
import subprocess
|
| 16 |
+
import traceback
|
| 17 |
+
import warnings
|
| 18 |
+
import multiprocessing as mp
|
| 19 |
+
from multiprocessing import get_context as mp_get_context
|
| 20 |
+
from multiprocessing.context import BaseContext
|
| 21 |
+
|
| 22 |
+
from .process import LokyProcess, LokyInitMainProcess
|
| 23 |
+
|
| 24 |
+
START_METHODS = ['loky', 'loky_init_main', 'spawn']
|
| 25 |
+
if sys.platform != 'win32':
|
| 26 |
+
START_METHODS += ['fork', 'forkserver']
|
| 27 |
+
|
| 28 |
+
_DEFAULT_START_METHOD = None
|
| 29 |
+
|
| 30 |
+
# Cache for the number of physical cores to avoid repeating subprocess calls.
|
| 31 |
+
# It should not change during the lifetime of the program.
|
| 32 |
+
physical_cores_cache = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_context(method=None):
|
| 36 |
+
# Try to overload the default context
|
| 37 |
+
method = method or _DEFAULT_START_METHOD or "loky"
|
| 38 |
+
if method == "fork":
|
| 39 |
+
# If 'fork' is explicitly requested, warn user about potential issues.
|
| 40 |
+
warnings.warn("`fork` start method should not be used with "
|
| 41 |
+
"`loky` as it does not respect POSIX. Try using "
|
| 42 |
+
"`spawn` or `loky` instead.", UserWarning)
|
| 43 |
+
try:
|
| 44 |
+
return mp_get_context(method)
|
| 45 |
+
except ValueError:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"Unknown context '{method}'. Value should be in "
|
| 48 |
+
f"{START_METHODS}."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def set_start_method(method, force=False):
|
| 53 |
+
global _DEFAULT_START_METHOD
|
| 54 |
+
if _DEFAULT_START_METHOD is not None and not force:
|
| 55 |
+
raise RuntimeError('context has already been set')
|
| 56 |
+
assert method is None or method in START_METHODS, (
|
| 57 |
+
f"'{method}' is not a valid start_method. It should be in "
|
| 58 |
+
f"{START_METHODS}"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
_DEFAULT_START_METHOD = method
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_start_method():
|
| 65 |
+
return _DEFAULT_START_METHOD
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def cpu_count(only_physical_cores=False):
|
| 69 |
+
"""Return the number of CPUs the current process can use.
|
| 70 |
+
|
| 71 |
+
The returned number of CPUs accounts for:
|
| 72 |
+
* the number of CPUs in the system, as given by
|
| 73 |
+
``multiprocessing.cpu_count``;
|
| 74 |
+
* the CPU affinity settings of the current process
|
| 75 |
+
(available on some Unix systems);
|
| 76 |
+
* Cgroup CPU bandwidth limit (available on Linux only, typically
|
| 77 |
+
set by docker and similar container orchestration systems);
|
| 78 |
+
* the value of the LOKY_MAX_CPU_COUNT environment variable if defined.
|
| 79 |
+
and is given as the minimum of these constraints.
|
| 80 |
+
|
| 81 |
+
If ``only_physical_cores`` is True, return the number of physical cores
|
| 82 |
+
instead of the number of logical cores (hyperthreading / SMT). Note that
|
| 83 |
+
this option is not enforced if the number of usable cores is controlled in
|
| 84 |
+
any other way such as: process affinity, Cgroup restricted CPU bandwidth
|
| 85 |
+
or the LOKY_MAX_CPU_COUNT environment variable. If the number of physical
|
| 86 |
+
cores is not found, return the number of logical cores.
|
| 87 |
+
|
| 88 |
+
It is also always larger or equal to 1.
|
| 89 |
+
"""
|
| 90 |
+
# Note: os.cpu_count() is allowed to return None in its docstring
|
| 91 |
+
os_cpu_count = os.cpu_count() or 1
|
| 92 |
+
|
| 93 |
+
cpu_count_user = _cpu_count_user(os_cpu_count)
|
| 94 |
+
aggregate_cpu_count = max(min(os_cpu_count, cpu_count_user), 1)
|
| 95 |
+
|
| 96 |
+
if not only_physical_cores:
|
| 97 |
+
return aggregate_cpu_count
|
| 98 |
+
|
| 99 |
+
if cpu_count_user < os_cpu_count:
|
| 100 |
+
# Respect user setting
|
| 101 |
+
return max(cpu_count_user, 1)
|
| 102 |
+
|
| 103 |
+
cpu_count_physical, exception = _count_physical_cores()
|
| 104 |
+
if cpu_count_physical != "not found":
|
| 105 |
+
return cpu_count_physical
|
| 106 |
+
|
| 107 |
+
# Fallback to default behavior
|
| 108 |
+
if exception is not None:
|
| 109 |
+
# warns only the first time
|
| 110 |
+
warnings.warn(
|
| 111 |
+
"Could not find the number of physical cores for the "
|
| 112 |
+
f"following reason:\n{exception}\n"
|
| 113 |
+
"Returning the number of logical cores instead. You can "
|
| 114 |
+
"silence this warning by setting LOKY_MAX_CPU_COUNT to "
|
| 115 |
+
"the number of cores you want to use.")
|
| 116 |
+
traceback.print_tb(exception.__traceback__)
|
| 117 |
+
|
| 118 |
+
return aggregate_cpu_count
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _cpu_count_cgroup(os_cpu_count):
|
| 122 |
+
# Cgroup CPU bandwidth limit available in Linux since 2.6 kernel
|
| 123 |
+
cpu_max_fname = "/sys/fs/cgroup/cpu.max"
|
| 124 |
+
cfs_quota_fname = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
|
| 125 |
+
cfs_period_fname = "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
|
| 126 |
+
if os.path.exists(cpu_max_fname):
|
| 127 |
+
# cgroup v2
|
| 128 |
+
# https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
|
| 129 |
+
with open(cpu_max_fname) as fh:
|
| 130 |
+
cpu_quota_us, cpu_period_us = fh.read().strip().split()
|
| 131 |
+
elif os.path.exists(cfs_quota_fname) and os.path.exists(cfs_period_fname):
|
| 132 |
+
# cgroup v1
|
| 133 |
+
# https://www.kernel.org/doc/html/latest/scheduler/sched-bwc.html#management
|
| 134 |
+
with open(cfs_quota_fname) as fh:
|
| 135 |
+
cpu_quota_us = fh.read().strip()
|
| 136 |
+
with open(cfs_period_fname) as fh:
|
| 137 |
+
cpu_period_us = fh.read().strip()
|
| 138 |
+
else:
|
| 139 |
+
# No Cgroup CPU bandwidth limit (e.g. non-Linux platform)
|
| 140 |
+
cpu_quota_us = "max"
|
| 141 |
+
cpu_period_us = 100_000 # unused, for consistency with default values
|
| 142 |
+
|
| 143 |
+
if cpu_quota_us == "max":
|
| 144 |
+
# No active Cgroup quota on a Cgroup-capable platform
|
| 145 |
+
return os_cpu_count
|
| 146 |
+
else:
|
| 147 |
+
cpu_quota_us = int(cpu_quota_us)
|
| 148 |
+
cpu_period_us = int(cpu_period_us)
|
| 149 |
+
if cpu_quota_us > 0 and cpu_period_us > 0:
|
| 150 |
+
return math.ceil(cpu_quota_us / cpu_period_us)
|
| 151 |
+
else: # pragma: no cover
|
| 152 |
+
# Setting a negative cpu_quota_us value is a valid way to disable
|
| 153 |
+
# cgroup CPU bandwith limits
|
| 154 |
+
return os_cpu_count
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _cpu_count_user(os_cpu_count):
|
| 158 |
+
"""Number of user defined available CPUs"""
|
| 159 |
+
# Number of available CPUs given affinity settings
|
| 160 |
+
cpu_count_affinity = os_cpu_count
|
| 161 |
+
if hasattr(os, 'sched_getaffinity'):
|
| 162 |
+
try:
|
| 163 |
+
cpu_count_affinity = len(os.sched_getaffinity(0))
|
| 164 |
+
except NotImplementedError:
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
cpu_count_cgroup = _cpu_count_cgroup(os_cpu_count)
|
| 168 |
+
|
| 169 |
+
# User defined soft-limit passed as a loky specific environment variable.
|
| 170 |
+
cpu_count_loky = int(os.environ.get('LOKY_MAX_CPU_COUNT', os_cpu_count))
|
| 171 |
+
|
| 172 |
+
return min(cpu_count_affinity, cpu_count_cgroup, cpu_count_loky)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _count_physical_cores():
|
| 176 |
+
"""Return a tuple (number of physical cores, exception)
|
| 177 |
+
|
| 178 |
+
If the number of physical cores is found, exception is set to None.
|
| 179 |
+
If it has not been found, return ("not found", exception).
|
| 180 |
+
|
| 181 |
+
The number of physical cores is cached to avoid repeating subprocess calls.
|
| 182 |
+
"""
|
| 183 |
+
exception = None
|
| 184 |
+
|
| 185 |
+
# First check if the value is cached
|
| 186 |
+
global physical_cores_cache
|
| 187 |
+
if physical_cores_cache is not None:
|
| 188 |
+
return physical_cores_cache, exception
|
| 189 |
+
|
| 190 |
+
# Not cached yet, find it
|
| 191 |
+
try:
|
| 192 |
+
if sys.platform == "linux":
|
| 193 |
+
cpu_info = subprocess.run(
|
| 194 |
+
"lscpu --parse=core".split(), capture_output=True, text=True)
|
| 195 |
+
cpu_info = cpu_info.stdout.splitlines()
|
| 196 |
+
cpu_info = {line for line in cpu_info if not line.startswith("#")}
|
| 197 |
+
cpu_count_physical = len(cpu_info)
|
| 198 |
+
elif sys.platform == "win32":
|
| 199 |
+
cpu_info = subprocess.run(
|
| 200 |
+
"wmic CPU Get NumberOfCores /Format:csv".split(),
|
| 201 |
+
capture_output=True, text=True)
|
| 202 |
+
cpu_info = cpu_info.stdout.splitlines()
|
| 203 |
+
cpu_info = [l.split(",")[1] for l in cpu_info
|
| 204 |
+
if (l and l != "Node,NumberOfCores")]
|
| 205 |
+
cpu_count_physical = sum(map(int, cpu_info))
|
| 206 |
+
elif sys.platform == "darwin":
|
| 207 |
+
cpu_info = subprocess.run(
|
| 208 |
+
"sysctl -n hw.physicalcpu".split(),
|
| 209 |
+
capture_output=True, text=True)
|
| 210 |
+
cpu_info = cpu_info.stdout
|
| 211 |
+
cpu_count_physical = int(cpu_info)
|
| 212 |
+
else:
|
| 213 |
+
raise NotImplementedError(f"unsupported platform: {sys.platform}")
|
| 214 |
+
|
| 215 |
+
# if cpu_count_physical < 1, we did not find a valid value
|
| 216 |
+
if cpu_count_physical < 1:
|
| 217 |
+
raise ValueError(
|
| 218 |
+
f"found {cpu_count_physical} physical cores < 1")
|
| 219 |
+
|
| 220 |
+
except Exception as e:
|
| 221 |
+
exception = e
|
| 222 |
+
cpu_count_physical = "not found"
|
| 223 |
+
|
| 224 |
+
# Put the result in cache
|
| 225 |
+
physical_cores_cache = cpu_count_physical
|
| 226 |
+
|
| 227 |
+
return cpu_count_physical, exception
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class LokyContext(BaseContext):
|
| 231 |
+
"""Context relying on the LokyProcess."""
|
| 232 |
+
_name = 'loky'
|
| 233 |
+
Process = LokyProcess
|
| 234 |
+
cpu_count = staticmethod(cpu_count)
|
| 235 |
+
|
| 236 |
+
def Queue(self, maxsize=0, reducers=None):
|
| 237 |
+
'''Returns a queue object'''
|
| 238 |
+
from .queues import Queue
|
| 239 |
+
return Queue(maxsize, reducers=reducers,
|
| 240 |
+
ctx=self.get_context())
|
| 241 |
+
|
| 242 |
+
def SimpleQueue(self, reducers=None):
|
| 243 |
+
'''Returns a queue object'''
|
| 244 |
+
from .queues import SimpleQueue
|
| 245 |
+
return SimpleQueue(reducers=reducers, ctx=self.get_context())
|
| 246 |
+
|
| 247 |
+
if sys.platform != "win32":
|
| 248 |
+
"""For Unix platform, use our custom implementation of synchronize
|
| 249 |
+
ensuring that we use the loky.backend.resource_tracker to clean-up
|
| 250 |
+
the semaphores in case of a worker crash.
|
| 251 |
+
"""
|
| 252 |
+
def Semaphore(self, value=1):
|
| 253 |
+
"""Returns a semaphore object"""
|
| 254 |
+
from .synchronize import Semaphore
|
| 255 |
+
return Semaphore(value=value)
|
| 256 |
+
|
| 257 |
+
def BoundedSemaphore(self, value):
|
| 258 |
+
"""Returns a bounded semaphore object"""
|
| 259 |
+
from .synchronize import BoundedSemaphore
|
| 260 |
+
return BoundedSemaphore(value)
|
| 261 |
+
|
| 262 |
+
def Lock(self):
|
| 263 |
+
"""Returns a lock object"""
|
| 264 |
+
from .synchronize import Lock
|
| 265 |
+
return Lock()
|
| 266 |
+
|
| 267 |
+
def RLock(self):
|
| 268 |
+
"""Returns a recurrent lock object"""
|
| 269 |
+
from .synchronize import RLock
|
| 270 |
+
return RLock()
|
| 271 |
+
|
| 272 |
+
def Condition(self, lock=None):
|
| 273 |
+
"""Returns a condition object"""
|
| 274 |
+
from .synchronize import Condition
|
| 275 |
+
return Condition(lock)
|
| 276 |
+
|
| 277 |
+
def Event(self):
|
| 278 |
+
"""Returns an event object"""
|
| 279 |
+
from .synchronize import Event
|
| 280 |
+
return Event()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class LokyInitMainContext(LokyContext):
|
| 284 |
+
"""Extra context with LokyProcess, which does load the main module
|
| 285 |
+
|
| 286 |
+
This context is used for compatibility in the case ``cloudpickle`` is not
|
| 287 |
+
present on the running system. This permits to load functions defined in
|
| 288 |
+
the ``main`` module, using proper safeguards. The declaration of the
|
| 289 |
+
``executor`` should be protected by ``if __name__ == "__main__":`` and the
|
| 290 |
+
functions and variable used from main should be out of this block.
|
| 291 |
+
|
| 292 |
+
This mimics the default behavior of multiprocessing under Windows and the
|
| 293 |
+
behavior of the ``spawn`` start method on a posix system.
|
| 294 |
+
For more details, see the end of the following section of python doc
|
| 295 |
+
https://docs.python.org/3/library/multiprocessing.html#multiprocessing-programming
|
| 296 |
+
"""
|
| 297 |
+
_name = 'loky_init_main'
|
| 298 |
+
Process = LokyInitMainProcess
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
# Register loky context so it works with multiprocessing.get_context
|
| 302 |
+
ctx_loky = LokyContext()
|
| 303 |
+
mp.context._concrete_contexts['loky'] = ctx_loky
|
| 304 |
+
mp.context._concrete_contexts['loky_init_main'] = LokyInitMainContext()
|
runtime/Lib/site-packages/joblib/externals/loky/backend/fork_exec.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Launch a subprocess using forkexec and make sure only the needed fd are
|
| 3 |
+
# shared in the two process.
|
| 4 |
+
#
|
| 5 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 6 |
+
#
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def close_fds(keep_fds): # pragma: no cover
|
| 12 |
+
"""Close all the file descriptors except those in keep_fds."""
|
| 13 |
+
|
| 14 |
+
# Make sure to keep stdout and stderr open for logging purpose
|
| 15 |
+
keep_fds = {*keep_fds, 1, 2}
|
| 16 |
+
|
| 17 |
+
# We try to retrieve all the open fds
|
| 18 |
+
try:
|
| 19 |
+
open_fds = {int(fd) for fd in os.listdir('/proc/self/fd')}
|
| 20 |
+
except FileNotFoundError:
|
| 21 |
+
import resource
|
| 22 |
+
max_nfds = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
|
| 23 |
+
open_fds = {*range(max_nfds)}
|
| 24 |
+
|
| 25 |
+
for i in open_fds - keep_fds:
|
| 26 |
+
try:
|
| 27 |
+
os.close(i)
|
| 28 |
+
except OSError:
|
| 29 |
+
pass
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fork_exec(cmd, keep_fds, env=None):
|
| 33 |
+
# copy the environment variables to set in the child process
|
| 34 |
+
env = env or {}
|
| 35 |
+
child_env = {**os.environ, **env}
|
| 36 |
+
|
| 37 |
+
pid = os.fork()
|
| 38 |
+
if pid == 0: # pragma: no cover
|
| 39 |
+
close_fds(keep_fds)
|
| 40 |
+
os.execve(sys.executable, cmd, child_env)
|
| 41 |
+
else:
|
| 42 |
+
return pid
|
runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_posix.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Popen for LokyProcess.
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import signal
|
| 9 |
+
import pickle
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from multiprocessing import util, process
|
| 12 |
+
from multiprocessing.connection import wait
|
| 13 |
+
from multiprocessing.context import set_spawning_popen
|
| 14 |
+
|
| 15 |
+
from . import reduction, resource_tracker, spawn
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ['Popen']
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
#
|
| 22 |
+
# Wrapper for an fd used while launching a process
|
| 23 |
+
#
|
| 24 |
+
|
| 25 |
+
class _DupFd:
|
| 26 |
+
def __init__(self, fd):
|
| 27 |
+
self.fd = reduction._mk_inheritable(fd)
|
| 28 |
+
|
| 29 |
+
def detach(self):
|
| 30 |
+
return self.fd
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
#
|
| 34 |
+
# Start child process using subprocess.Popen
|
| 35 |
+
#
|
| 36 |
+
|
| 37 |
+
class Popen:
|
| 38 |
+
method = 'loky'
|
| 39 |
+
DupFd = _DupFd
|
| 40 |
+
|
| 41 |
+
def __init__(self, process_obj):
|
| 42 |
+
sys.stdout.flush()
|
| 43 |
+
sys.stderr.flush()
|
| 44 |
+
self.returncode = None
|
| 45 |
+
self._fds = []
|
| 46 |
+
self._launch(process_obj)
|
| 47 |
+
|
| 48 |
+
def duplicate_for_child(self, fd):
|
| 49 |
+
self._fds.append(fd)
|
| 50 |
+
return reduction._mk_inheritable(fd)
|
| 51 |
+
|
| 52 |
+
def poll(self, flag=os.WNOHANG):
|
| 53 |
+
if self.returncode is None:
|
| 54 |
+
while True:
|
| 55 |
+
try:
|
| 56 |
+
pid, sts = os.waitpid(self.pid, flag)
|
| 57 |
+
except OSError:
|
| 58 |
+
# Child process not yet created. See #1731717
|
| 59 |
+
# e.errno == errno.ECHILD == 10
|
| 60 |
+
return None
|
| 61 |
+
else:
|
| 62 |
+
break
|
| 63 |
+
if pid == self.pid:
|
| 64 |
+
if os.WIFSIGNALED(sts):
|
| 65 |
+
self.returncode = -os.WTERMSIG(sts)
|
| 66 |
+
else:
|
| 67 |
+
assert os.WIFEXITED(sts)
|
| 68 |
+
self.returncode = os.WEXITSTATUS(sts)
|
| 69 |
+
return self.returncode
|
| 70 |
+
|
| 71 |
+
def wait(self, timeout=None):
|
| 72 |
+
if self.returncode is None:
|
| 73 |
+
if timeout is not None:
|
| 74 |
+
if not wait([self.sentinel], timeout):
|
| 75 |
+
return None
|
| 76 |
+
# This shouldn't block if wait() returned successfully.
|
| 77 |
+
return self.poll(os.WNOHANG if timeout == 0.0 else 0)
|
| 78 |
+
return self.returncode
|
| 79 |
+
|
| 80 |
+
def terminate(self):
|
| 81 |
+
if self.returncode is None:
|
| 82 |
+
try:
|
| 83 |
+
os.kill(self.pid, signal.SIGTERM)
|
| 84 |
+
except ProcessLookupError:
|
| 85 |
+
pass
|
| 86 |
+
except OSError:
|
| 87 |
+
if self.wait(timeout=0.1) is None:
|
| 88 |
+
raise
|
| 89 |
+
|
| 90 |
+
def _launch(self, process_obj):
|
| 91 |
+
|
| 92 |
+
tracker_fd = resource_tracker._resource_tracker.getfd()
|
| 93 |
+
|
| 94 |
+
fp = BytesIO()
|
| 95 |
+
set_spawning_popen(self)
|
| 96 |
+
try:
|
| 97 |
+
prep_data = spawn.get_preparation_data(
|
| 98 |
+
process_obj._name,
|
| 99 |
+
getattr(process_obj, "init_main_module", True))
|
| 100 |
+
reduction.dump(prep_data, fp)
|
| 101 |
+
reduction.dump(process_obj, fp)
|
| 102 |
+
|
| 103 |
+
finally:
|
| 104 |
+
set_spawning_popen(None)
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
parent_r, child_w = os.pipe()
|
| 108 |
+
child_r, parent_w = os.pipe()
|
| 109 |
+
# for fd in self._fds:
|
| 110 |
+
# _mk_inheritable(fd)
|
| 111 |
+
|
| 112 |
+
cmd_python = [sys.executable]
|
| 113 |
+
cmd_python += ['-m', self.__module__]
|
| 114 |
+
cmd_python += ['--process-name', str(process_obj.name)]
|
| 115 |
+
cmd_python += ['--pipe', str(reduction._mk_inheritable(child_r))]
|
| 116 |
+
reduction._mk_inheritable(child_w)
|
| 117 |
+
reduction._mk_inheritable(tracker_fd)
|
| 118 |
+
self._fds += [child_r, child_w, tracker_fd]
|
| 119 |
+
if sys.version_info >= (3, 8) and os.name == 'posix':
|
| 120 |
+
mp_tracker_fd = prep_data['mp_tracker_args']['fd']
|
| 121 |
+
self.duplicate_for_child(mp_tracker_fd)
|
| 122 |
+
|
| 123 |
+
from .fork_exec import fork_exec
|
| 124 |
+
pid = fork_exec(cmd_python, self._fds, env=process_obj.env)
|
| 125 |
+
util.debug(
|
| 126 |
+
f"launched python with pid {pid} and cmd:\n{cmd_python}"
|
| 127 |
+
)
|
| 128 |
+
self.sentinel = parent_r
|
| 129 |
+
|
| 130 |
+
method = 'getbuffer'
|
| 131 |
+
if not hasattr(fp, method):
|
| 132 |
+
method = 'getvalue'
|
| 133 |
+
with os.fdopen(parent_w, 'wb') as f:
|
| 134 |
+
f.write(getattr(fp, method)())
|
| 135 |
+
self.pid = pid
|
| 136 |
+
finally:
|
| 137 |
+
if parent_r is not None:
|
| 138 |
+
util.Finalize(self, os.close, (parent_r,))
|
| 139 |
+
for fd in (child_r, child_w):
|
| 140 |
+
if fd is not None:
|
| 141 |
+
os.close(fd)
|
| 142 |
+
|
| 143 |
+
@staticmethod
|
| 144 |
+
def thread_is_spawning():
|
| 145 |
+
return True
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == '__main__':
|
| 149 |
+
import argparse
|
| 150 |
+
parser = argparse.ArgumentParser('Command line parser')
|
| 151 |
+
parser.add_argument('--pipe', type=int, required=True,
|
| 152 |
+
help='File handle for the pipe')
|
| 153 |
+
parser.add_argument('--process-name', type=str, default=None,
|
| 154 |
+
help='Identifier for debugging purpose')
|
| 155 |
+
|
| 156 |
+
args = parser.parse_args()
|
| 157 |
+
|
| 158 |
+
info = {}
|
| 159 |
+
exitcode = 1
|
| 160 |
+
try:
|
| 161 |
+
with os.fdopen(args.pipe, 'rb') as from_parent:
|
| 162 |
+
process.current_process()._inheriting = True
|
| 163 |
+
try:
|
| 164 |
+
prep_data = pickle.load(from_parent)
|
| 165 |
+
spawn.prepare(prep_data)
|
| 166 |
+
process_obj = pickle.load(from_parent)
|
| 167 |
+
finally:
|
| 168 |
+
del process.current_process()._inheriting
|
| 169 |
+
|
| 170 |
+
exitcode = process_obj._bootstrap()
|
| 171 |
+
except Exception:
|
| 172 |
+
print('\n\n' + '-' * 80)
|
| 173 |
+
print(f'{args.process_name} failed with traceback: ')
|
| 174 |
+
print('-' * 80)
|
| 175 |
+
import traceback
|
| 176 |
+
print(traceback.format_exc())
|
| 177 |
+
print('\n' + '-' * 80)
|
| 178 |
+
finally:
|
| 179 |
+
if from_parent is not None:
|
| 180 |
+
from_parent.close()
|
| 181 |
+
|
| 182 |
+
sys.exit(exitcode)
|
runtime/Lib/site-packages/joblib/externals/loky/backend/popen_loky_win32.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import msvcrt
|
| 4 |
+
import _winapi
|
| 5 |
+
from pickle import load
|
| 6 |
+
from multiprocessing import process, util
|
| 7 |
+
from multiprocessing.context import get_spawning_popen, set_spawning_popen
|
| 8 |
+
from multiprocessing.popen_spawn_win32 import Popen as _Popen
|
| 9 |
+
from multiprocessing.reduction import duplicate
|
| 10 |
+
|
| 11 |
+
from . import reduction, spawn
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ['Popen']
|
| 15 |
+
|
| 16 |
+
#
|
| 17 |
+
#
|
| 18 |
+
#
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _path_eq(p1, p2):
|
| 22 |
+
return p1 == p2 or os.path.normcase(p1) == os.path.normcase(p2)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
WINENV = (hasattr(sys, "_base_executable")
|
| 26 |
+
and not _path_eq(sys.executable, sys._base_executable))
|
| 27 |
+
|
| 28 |
+
#
|
| 29 |
+
# We define a Popen class similar to the one from subprocess, but
|
| 30 |
+
# whose constructor takes a process object as its argument.
|
| 31 |
+
#
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Popen(_Popen):
|
| 35 |
+
'''
|
| 36 |
+
Start a subprocess to run the code of a process object
|
| 37 |
+
'''
|
| 38 |
+
method = 'loky'
|
| 39 |
+
|
| 40 |
+
def __init__(self, process_obj):
|
| 41 |
+
prep_data = spawn.get_preparation_data(
|
| 42 |
+
process_obj._name, getattr(process_obj, "init_main_module", True))
|
| 43 |
+
|
| 44 |
+
# read end of pipe will be "stolen" by the child process
|
| 45 |
+
# -- see spawn_main() in spawn.py.
|
| 46 |
+
rfd, wfd = os.pipe()
|
| 47 |
+
rhandle = duplicate(msvcrt.get_osfhandle(rfd), inheritable=True)
|
| 48 |
+
os.close(rfd)
|
| 49 |
+
|
| 50 |
+
cmd = get_command_line(parent_pid=os.getpid(), pipe_handle=rhandle)
|
| 51 |
+
cmd = ' '.join(f'"{x}"' for x in cmd)
|
| 52 |
+
|
| 53 |
+
python_exe = spawn.get_executable()
|
| 54 |
+
|
| 55 |
+
# copy the environment variables to set in the child process
|
| 56 |
+
child_env = {**os.environ, **process_obj.env}
|
| 57 |
+
|
| 58 |
+
# bpo-35797: When running in a venv, we bypass the redirect
|
| 59 |
+
# executor and launch our base Python.
|
| 60 |
+
if WINENV and _path_eq(python_exe, sys.executable):
|
| 61 |
+
python_exe = sys._base_executable
|
| 62 |
+
child_env["__PYVENV_LAUNCHER__"] = sys.executable
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
with open(wfd, 'wb') as to_child:
|
| 66 |
+
# start process
|
| 67 |
+
try:
|
| 68 |
+
# This flag allows to pass inheritable handles from the
|
| 69 |
+
# parent to the child process in a python2-3 compatible way
|
| 70 |
+
# (see
|
| 71 |
+
# https://github.com/tomMoral/loky/pull/204#discussion_r290719629
|
| 72 |
+
# for more detail). When support for Python 2 is dropped,
|
| 73 |
+
# the cleaner multiprocessing.reduction.steal_handle should
|
| 74 |
+
# be used instead.
|
| 75 |
+
inherit = True
|
| 76 |
+
hp, ht, pid, _ = _winapi.CreateProcess(
|
| 77 |
+
python_exe, cmd,
|
| 78 |
+
None, None, inherit, 0,
|
| 79 |
+
child_env, None, None)
|
| 80 |
+
_winapi.CloseHandle(ht)
|
| 81 |
+
except BaseException:
|
| 82 |
+
_winapi.CloseHandle(rhandle)
|
| 83 |
+
raise
|
| 84 |
+
|
| 85 |
+
# set attributes of self
|
| 86 |
+
self.pid = pid
|
| 87 |
+
self.returncode = None
|
| 88 |
+
self._handle = hp
|
| 89 |
+
self.sentinel = int(hp)
|
| 90 |
+
util.Finalize(self, _winapi.CloseHandle, (self.sentinel,))
|
| 91 |
+
|
| 92 |
+
# send information to child
|
| 93 |
+
set_spawning_popen(self)
|
| 94 |
+
try:
|
| 95 |
+
reduction.dump(prep_data, to_child)
|
| 96 |
+
reduction.dump(process_obj, to_child)
|
| 97 |
+
finally:
|
| 98 |
+
set_spawning_popen(None)
|
| 99 |
+
except IOError as exc:
|
| 100 |
+
# IOError 22 happens when the launched subprocess terminated before
|
| 101 |
+
# wfd.close is called. Thus we can safely ignore it.
|
| 102 |
+
if exc.errno != 22:
|
| 103 |
+
raise
|
| 104 |
+
util.debug(
|
| 105 |
+
f"While starting {process_obj._name}, ignored a IOError 22"
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def duplicate_for_child(self, handle):
|
| 109 |
+
assert self is get_spawning_popen()
|
| 110 |
+
return duplicate(handle, self.sentinel)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def get_command_line(pipe_handle, **kwds):
|
| 114 |
+
'''
|
| 115 |
+
Returns prefix of command line used for spawning a child process
|
| 116 |
+
'''
|
| 117 |
+
if getattr(sys, 'frozen', False):
|
| 118 |
+
return [sys.executable, '--multiprocessing-fork', pipe_handle]
|
| 119 |
+
else:
|
| 120 |
+
prog = 'from joblib.externals.loky.backend.popen_loky_win32 import main; main()'
|
| 121 |
+
opts = util._args_from_interpreter_flags()
|
| 122 |
+
return [spawn.get_executable(), *opts,
|
| 123 |
+
'-c', prog, '--multiprocessing-fork', pipe_handle]
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def is_forking(argv):
|
| 127 |
+
'''
|
| 128 |
+
Return whether commandline indicates we are forking
|
| 129 |
+
'''
|
| 130 |
+
if len(argv) >= 2 and argv[1] == '--multiprocessing-fork':
|
| 131 |
+
assert len(argv) == 3
|
| 132 |
+
return True
|
| 133 |
+
else:
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def main():
|
| 138 |
+
'''
|
| 139 |
+
Run code specified by data received over pipe
|
| 140 |
+
'''
|
| 141 |
+
assert is_forking(sys.argv)
|
| 142 |
+
|
| 143 |
+
handle = int(sys.argv[-1])
|
| 144 |
+
fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
|
| 145 |
+
from_parent = os.fdopen(fd, 'rb')
|
| 146 |
+
|
| 147 |
+
process.current_process()._inheriting = True
|
| 148 |
+
preparation_data = load(from_parent)
|
| 149 |
+
spawn.prepare(preparation_data)
|
| 150 |
+
self = load(from_parent)
|
| 151 |
+
process.current_process()._inheriting = False
|
| 152 |
+
|
| 153 |
+
from_parent.close()
|
| 154 |
+
|
| 155 |
+
exitcode = self._bootstrap()
|
| 156 |
+
sys.exit(exitcode)
|
runtime/Lib/site-packages/joblib/externals/loky/backend/process.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# LokyProcess implementation
|
| 3 |
+
#
|
| 4 |
+
# authors: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# based on multiprocessing/process.py (17/02/2017)
|
| 7 |
+
#
|
| 8 |
+
import sys
|
| 9 |
+
from multiprocessing.context import assert_spawning
|
| 10 |
+
from multiprocessing.process import BaseProcess
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class LokyProcess(BaseProcess):
|
| 14 |
+
_start_method = 'loky'
|
| 15 |
+
|
| 16 |
+
def __init__(self, group=None, target=None, name=None, args=(),
|
| 17 |
+
kwargs={}, daemon=None, init_main_module=False,
|
| 18 |
+
env=None):
|
| 19 |
+
super().__init__(
|
| 20 |
+
group=group, target=target, name=name, args=args,
|
| 21 |
+
kwargs=kwargs, daemon=daemon)
|
| 22 |
+
self.env = {} if env is None else env
|
| 23 |
+
self.authkey = self.authkey
|
| 24 |
+
self.init_main_module = init_main_module
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def _Popen(process_obj):
|
| 28 |
+
if sys.platform == "win32":
|
| 29 |
+
from .popen_loky_win32 import Popen
|
| 30 |
+
else:
|
| 31 |
+
from .popen_loky_posix import Popen
|
| 32 |
+
return Popen(process_obj)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LokyInitMainProcess(LokyProcess):
|
| 36 |
+
_start_method = 'loky_init_main'
|
| 37 |
+
|
| 38 |
+
def __init__(self, group=None, target=None, name=None, args=(),
|
| 39 |
+
kwargs={}, daemon=None):
|
| 40 |
+
super().__init__(
|
| 41 |
+
group=group, target=target, name=name, args=args, kwargs=kwargs,
|
| 42 |
+
daemon=daemon, init_main_module=True)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
#
|
| 46 |
+
# We subclass bytes to avoid accidental transmission of auth keys over network
|
| 47 |
+
#
|
| 48 |
+
|
| 49 |
+
class AuthenticationKey(bytes):
|
| 50 |
+
def __reduce__(self):
|
| 51 |
+
try:
|
| 52 |
+
assert_spawning(self)
|
| 53 |
+
except RuntimeError:
|
| 54 |
+
raise TypeError(
|
| 55 |
+
'Pickling an AuthenticationKey object is '
|
| 56 |
+
'disallowed for security reasons'
|
| 57 |
+
)
|
| 58 |
+
return AuthenticationKey, (bytes(self),)
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Queue and SimpleQueue implementation for loky
|
| 3 |
+
#
|
| 4 |
+
# authors: Thomas Moreau, Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# based on multiprocessing/queues.py (16/02/2017)
|
| 7 |
+
# * Add some custom reducers for the Queues/SimpleQueue to tweak the
|
| 8 |
+
# pickling process. (overload Queue._feed/SimpleQueue.put)
|
| 9 |
+
#
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import errno
|
| 13 |
+
import weakref
|
| 14 |
+
import threading
|
| 15 |
+
from multiprocessing import util
|
| 16 |
+
from multiprocessing.queues import (
|
| 17 |
+
Full,
|
| 18 |
+
Queue as mp_Queue,
|
| 19 |
+
SimpleQueue as mp_SimpleQueue,
|
| 20 |
+
_sentinel,
|
| 21 |
+
)
|
| 22 |
+
from multiprocessing.context import assert_spawning
|
| 23 |
+
|
| 24 |
+
from .reduction import dumps
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
__all__ = ['Queue', 'SimpleQueue', 'Full']
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Queue(mp_Queue):
|
| 31 |
+
|
| 32 |
+
def __init__(self, maxsize=0, reducers=None, ctx=None):
|
| 33 |
+
super().__init__(maxsize=maxsize, ctx=ctx)
|
| 34 |
+
self._reducers = reducers
|
| 35 |
+
|
| 36 |
+
# Use custom queue set/get state to be able to reduce the custom reducers
|
| 37 |
+
def __getstate__(self):
|
| 38 |
+
assert_spawning(self)
|
| 39 |
+
return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
|
| 40 |
+
self._reducers, self._rlock, self._wlock, self._sem,
|
| 41 |
+
self._opid)
|
| 42 |
+
|
| 43 |
+
def __setstate__(self, state):
|
| 44 |
+
(self._ignore_epipe, self._maxsize, self._reader, self._writer,
|
| 45 |
+
self._reducers, self._rlock, self._wlock, self._sem,
|
| 46 |
+
self._opid) = state
|
| 47 |
+
if sys.version_info >= (3, 9):
|
| 48 |
+
self._reset()
|
| 49 |
+
else:
|
| 50 |
+
self._after_fork()
|
| 51 |
+
|
| 52 |
+
# Overload _start_thread to correctly call our custom _feed
|
| 53 |
+
def _start_thread(self):
|
| 54 |
+
util.debug('Queue._start_thread()')
|
| 55 |
+
|
| 56 |
+
# Start thread which transfers data from buffer to pipe
|
| 57 |
+
self._buffer.clear()
|
| 58 |
+
self._thread = threading.Thread(
|
| 59 |
+
target=Queue._feed,
|
| 60 |
+
args=(self._buffer, self._notempty, self._send_bytes,
|
| 61 |
+
self._wlock, self._writer.close, self._reducers,
|
| 62 |
+
self._ignore_epipe, self._on_queue_feeder_error, self._sem),
|
| 63 |
+
name='QueueFeederThread'
|
| 64 |
+
)
|
| 65 |
+
self._thread.daemon = True
|
| 66 |
+
|
| 67 |
+
util.debug('doing self._thread.start()')
|
| 68 |
+
self._thread.start()
|
| 69 |
+
util.debug('... done self._thread.start()')
|
| 70 |
+
|
| 71 |
+
# On process exit we will wait for data to be flushed to pipe.
|
| 72 |
+
#
|
| 73 |
+
# However, if this process created the queue then all
|
| 74 |
+
# processes which use the queue will be descendants of this
|
| 75 |
+
# process. Therefore waiting for the queue to be flushed
|
| 76 |
+
# is pointless once all the child processes have been joined.
|
| 77 |
+
created_by_this_process = (self._opid == os.getpid())
|
| 78 |
+
if not self._joincancelled and not created_by_this_process:
|
| 79 |
+
self._jointhread = util.Finalize(
|
| 80 |
+
self._thread, Queue._finalize_join,
|
| 81 |
+
[weakref.ref(self._thread)],
|
| 82 |
+
exitpriority=-5
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Send sentinel to the thread queue object when garbage collected
|
| 86 |
+
self._close = util.Finalize(
|
| 87 |
+
self, Queue._finalize_close,
|
| 88 |
+
[self._buffer, self._notempty],
|
| 89 |
+
exitpriority=10
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Overload the _feed methods to use our custom pickling strategy.
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _feed(buffer, notempty, send_bytes, writelock, close, reducers,
|
| 95 |
+
ignore_epipe, onerror, queue_sem):
|
| 96 |
+
util.debug('starting thread to feed data to pipe')
|
| 97 |
+
nacquire = notempty.acquire
|
| 98 |
+
nrelease = notempty.release
|
| 99 |
+
nwait = notempty.wait
|
| 100 |
+
bpopleft = buffer.popleft
|
| 101 |
+
sentinel = _sentinel
|
| 102 |
+
if sys.platform != 'win32':
|
| 103 |
+
wacquire = writelock.acquire
|
| 104 |
+
wrelease = writelock.release
|
| 105 |
+
else:
|
| 106 |
+
wacquire = None
|
| 107 |
+
|
| 108 |
+
while True:
|
| 109 |
+
try:
|
| 110 |
+
nacquire()
|
| 111 |
+
try:
|
| 112 |
+
if not buffer:
|
| 113 |
+
nwait()
|
| 114 |
+
finally:
|
| 115 |
+
nrelease()
|
| 116 |
+
try:
|
| 117 |
+
while True:
|
| 118 |
+
obj = bpopleft()
|
| 119 |
+
if obj is sentinel:
|
| 120 |
+
util.debug('feeder thread got sentinel -- exiting')
|
| 121 |
+
close()
|
| 122 |
+
return
|
| 123 |
+
|
| 124 |
+
# serialize the data before acquiring the lock
|
| 125 |
+
obj_ = dumps(obj, reducers=reducers)
|
| 126 |
+
if wacquire is None:
|
| 127 |
+
send_bytes(obj_)
|
| 128 |
+
else:
|
| 129 |
+
wacquire()
|
| 130 |
+
try:
|
| 131 |
+
send_bytes(obj_)
|
| 132 |
+
finally:
|
| 133 |
+
wrelease()
|
| 134 |
+
# Remove references early to avoid leaking memory
|
| 135 |
+
del obj, obj_
|
| 136 |
+
except IndexError:
|
| 137 |
+
pass
|
| 138 |
+
except BaseException as e:
|
| 139 |
+
if ignore_epipe and getattr(e, 'errno', 0) == errno.EPIPE:
|
| 140 |
+
return
|
| 141 |
+
# Since this runs in a daemon thread the resources it uses
|
| 142 |
+
# may be become unusable while the process is cleaning up.
|
| 143 |
+
# We ignore errors which happen after the process has
|
| 144 |
+
# started to cleanup.
|
| 145 |
+
if util.is_exiting():
|
| 146 |
+
util.info(f'error in queue thread: {e}')
|
| 147 |
+
return
|
| 148 |
+
else:
|
| 149 |
+
queue_sem.release()
|
| 150 |
+
onerror(e, obj)
|
| 151 |
+
|
| 152 |
+
def _on_queue_feeder_error(self, e, obj):
|
| 153 |
+
"""
|
| 154 |
+
Private API hook called when feeding data in the background thread
|
| 155 |
+
raises an exception. For overriding by concurrent.futures.
|
| 156 |
+
"""
|
| 157 |
+
import traceback
|
| 158 |
+
traceback.print_exc()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class SimpleQueue(mp_SimpleQueue):
|
| 162 |
+
|
| 163 |
+
def __init__(self, reducers=None, ctx=None):
|
| 164 |
+
super().__init__(ctx=ctx)
|
| 165 |
+
|
| 166 |
+
# Add possiblity to use custom reducers
|
| 167 |
+
self._reducers = reducers
|
| 168 |
+
|
| 169 |
+
def close(self):
|
| 170 |
+
self._reader.close()
|
| 171 |
+
self._writer.close()
|
| 172 |
+
|
| 173 |
+
# Use custom queue set/get state to be able to reduce the custom reducers
|
| 174 |
+
def __getstate__(self):
|
| 175 |
+
assert_spawning(self)
|
| 176 |
+
return (self._reader, self._writer, self._reducers, self._rlock,
|
| 177 |
+
self._wlock)
|
| 178 |
+
|
| 179 |
+
def __setstate__(self, state):
|
| 180 |
+
(self._reader, self._writer, self._reducers, self._rlock,
|
| 181 |
+
self._wlock) = state
|
| 182 |
+
|
| 183 |
+
# Overload put to use our customizable reducer
|
| 184 |
+
def put(self, obj):
|
| 185 |
+
# serialize the data before acquiring the lock
|
| 186 |
+
obj = dumps(obj, reducers=self._reducers)
|
| 187 |
+
if self._wlock is None:
|
| 188 |
+
# writes to a message oriented win32 pipe are atom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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Customizable Pickler with some basic reducers
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/reduction.py (17/02/2017)
|
| 7 |
+
# * Replace the ForkingPickler with a similar _LokyPickler,
|
| 8 |
+
# * Add CustomizableLokyPickler to allow customizing pickling process
|
| 9 |
+
# on the fly.
|
| 10 |
+
#
|
| 11 |
+
import copyreg
|
| 12 |
+
import io
|
| 13 |
+
import functools
|
| 14 |
+
import types
|
| 15 |
+
import sys
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
from multiprocessing import util
|
| 19 |
+
from pickle import loads, HIGHEST_PROTOCOL
|
| 20 |
+
|
| 21 |
+
###############################################################################
|
| 22 |
+
# Enable custom pickling in Loky.
|
| 23 |
+
|
| 24 |
+
_dispatch_table = {}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def register(type_, reduce_function):
|
| 28 |
+
_dispatch_table[type_] = reduce_function
|
| 29 |
+
|
| 30 |
+
###############################################################################
|
| 31 |
+
# Registers extra pickling routines to improve picklization for loky
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# make methods picklable
|
| 35 |
+
def _reduce_method(m):
|
| 36 |
+
if m.__self__ is None:
|
| 37 |
+
return getattr, (m.__class__, m.__func__.__name__)
|
| 38 |
+
else:
|
| 39 |
+
return getattr, (m.__self__, m.__func__.__name__)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class _C:
|
| 43 |
+
def f(self):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
@classmethod
|
| 47 |
+
def h(cls):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
register(type(_C().f), _reduce_method)
|
| 52 |
+
register(type(_C.h), _reduce_method)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if not hasattr(sys, "pypy_version_info"):
|
| 56 |
+
# PyPy uses functions instead of method_descriptors and wrapper_descriptors
|
| 57 |
+
def _reduce_method_descriptor(m):
|
| 58 |
+
return getattr, (m.__objclass__, m.__name__)
|
| 59 |
+
|
| 60 |
+
register(type(list.append), _reduce_method_descriptor)
|
| 61 |
+
register(type(int.__add__), _reduce_method_descriptor)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Make partial func pickable
|
| 65 |
+
def _reduce_partial(p):
|
| 66 |
+
return _rebuild_partial, (p.func, p.args, p.keywords or {})
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _rebuild_partial(func, args, keywords):
|
| 70 |
+
return functools.partial(func, *args, **keywords)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
register(functools.partial, _reduce_partial)
|
| 74 |
+
|
| 75 |
+
if sys.platform != "win32":
|
| 76 |
+
from ._posix_reduction import _mk_inheritable # noqa: F401
|
| 77 |
+
else:
|
| 78 |
+
from . import _win_reduction # noqa: F401
|
| 79 |
+
|
| 80 |
+
# global variable to change the pickler behavior
|
| 81 |
+
try:
|
| 82 |
+
from joblib.externals import cloudpickle # noqa: F401
|
| 83 |
+
DEFAULT_ENV = "cloudpickle"
|
| 84 |
+
except ImportError:
|
| 85 |
+
# If cloudpickle is not present, fallback to pickle
|
| 86 |
+
DEFAULT_ENV = "pickle"
|
| 87 |
+
|
| 88 |
+
ENV_LOKY_PICKLER = os.environ.get("LOKY_PICKLER", DEFAULT_ENV)
|
| 89 |
+
_LokyPickler = None
|
| 90 |
+
_loky_pickler_name = None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def set_loky_pickler(loky_pickler=None):
|
| 94 |
+
global _LokyPickler, _loky_pickler_name
|
| 95 |
+
|
| 96 |
+
if loky_pickler is None:
|
| 97 |
+
loky_pickler = ENV_LOKY_PICKLER
|
| 98 |
+
|
| 99 |
+
loky_pickler_cls = None
|
| 100 |
+
|
| 101 |
+
# The default loky_pickler is cloudpickle
|
| 102 |
+
if loky_pickler in ["", None]:
|
| 103 |
+
loky_pickler = "cloudpickle"
|
| 104 |
+
|
| 105 |
+
if loky_pickler == _loky_pickler_name:
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
if loky_pickler == "cloudpickle":
|
| 109 |
+
from joblib.externals.cloudpickle import CloudPickler as loky_pickler_cls
|
| 110 |
+
else:
|
| 111 |
+
try:
|
| 112 |
+
from importlib import import_module
|
| 113 |
+
module_pickle = import_module(loky_pickler)
|
| 114 |
+
loky_pickler_cls = module_pickle.Pickler
|
| 115 |
+
except (ImportError, AttributeError) as e:
|
| 116 |
+
extra_info = ("\nThis error occurred while setting loky_pickler to"
|
| 117 |
+
f" '{loky_pickler}', as required by the env variable "
|
| 118 |
+
"LOKY_PICKLER or the function set_loky_pickler.")
|
| 119 |
+
e.args = (e.args[0] + extra_info,) + e.args[1:]
|
| 120 |
+
e.msg = e.args[0]
|
| 121 |
+
raise e
|
| 122 |
+
|
| 123 |
+
util.debug(
|
| 124 |
+
f"Using '{loky_pickler if loky_pickler else 'cloudpickle'}' for "
|
| 125 |
+
"serialization."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
class CustomizablePickler(loky_pickler_cls):
|
| 129 |
+
_loky_pickler_cls = loky_pickler_cls
|
| 130 |
+
|
| 131 |
+
def _set_dispatch_table(self, dispatch_table):
|
| 132 |
+
for ancestor_class in self._loky_pickler_cls.mro():
|
| 133 |
+
dt_attribute = getattr(ancestor_class, "dispatch_table", None)
|
| 134 |
+
if isinstance(dt_attribute, types.MemberDescriptorType):
|
| 135 |
+
# Ancestor class (typically _pickle.Pickler) has a
|
| 136 |
+
# member_descriptor for its "dispatch_table" attribute. Use
|
| 137 |
+
# it to set the dispatch_table as a member instead of a
|
| 138 |
+
# dynamic attribute in the __dict__ of the instance,
|
| 139 |
+
# otherwise it will not be taken into account by the C
|
| 140 |
+
# implementation of the dump method if a subclass defines a
|
| 141 |
+
# class-level dispatch_table attribute as was done in
|
| 142 |
+
# cloudpickle 1.6.0:
|
| 143 |
+
# https://github.com/joblib/loky/pull/260
|
| 144 |
+
dt_attribute.__set__(self, dispatch_table)
|
| 145 |
+
break
|
| 146 |
+
|
| 147 |
+
# On top of member descriptor set, also use setattr such that code
|
| 148 |
+
# that directly access self.dispatch_table gets a consistent view
|
| 149 |
+
# of the same table.
|
| 150 |
+
self.dispatch_table = dispatch_table
|
| 151 |
+
|
| 152 |
+
def __init__(self, writer, reducers=None, protocol=HIGHEST_PROTOCOL):
|
| 153 |
+
loky_pickler_cls.__init__(self, writer, protocol=protocol)
|
| 154 |
+
if reducers is None:
|
| 155 |
+
reducers = {}
|
| 156 |
+
|
| 157 |
+
if hasattr(self, "dispatch_table"):
|
| 158 |
+
# Force a copy that we will update without mutating the
|
| 159 |
+
# any class level defined dispatch_table.
|
| 160 |
+
loky_dt = dict(self.dispatch_table)
|
| 161 |
+
else:
|
| 162 |
+
# Use standard reducers as bases
|
| 163 |
+
loky_dt = copyreg.dispatch_table.copy()
|
| 164 |
+
|
| 165 |
+
# Register loky specific reducers
|
| 166 |
+
loky_dt.update(_dispatch_table)
|
| 167 |
+
|
| 168 |
+
# Set the new dispatch table, taking care of the fact that we
|
| 169 |
+
# need to use the member_descriptor when we inherit from a
|
| 170 |
+
# subclass of the C implementation of the Pickler base class
|
| 171 |
+
# with an class level dispatch_table attribute.
|
| 172 |
+
self._set_dispatch_table(loky_dt)
|
| 173 |
+
|
| 174 |
+
# Register the reducers
|
| 175 |
+
for type, reduce_func in reducers.items():
|
| 176 |
+
self.register(type, reduce_func)
|
| 177 |
+
|
| 178 |
+
def register(self, type, reduce_func):
|
| 179 |
+
"""Attach a reducer function to a given type in the dispatch table.
|
| 180 |
+
"""
|
| 181 |
+
self.dispatch_table[type] = reduce_func
|
| 182 |
+
|
| 183 |
+
_LokyPickler = CustomizablePickler
|
| 184 |
+
_loky_pickler_name = loky_pickler
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def get_loky_pickler_name():
|
| 188 |
+
global _loky_pickler_name
|
| 189 |
+
return _loky_pickler_name
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def get_loky_pickler():
|
| 193 |
+
global _LokyPickler
|
| 194 |
+
return _LokyPickler
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# Set it to its default value
|
| 198 |
+
set_loky_pickler()
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def dump(obj, file, reducers=None, protocol=None):
|
| 202 |
+
'''Replacement for pickle.dump() using _LokyPickler.'''
|
| 203 |
+
global _LokyPickler
|
| 204 |
+
_LokyPickler(file, reducers=reducers, protocol=protocol).dump(obj)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def dumps(obj, reducers=None, protocol=None):
|
| 208 |
+
global _LokyPickler
|
| 209 |
+
|
| 210 |
+
buf = io.BytesIO()
|
| 211 |
+
dump(obj, buf, reducers=reducers, protocol=protocol)
|
| 212 |
+
return buf.getbuffer()
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
__all__ = ["dump", "dumps", "loads", "register", "set_loky_pickler"]
|
| 216 |
+
|
| 217 |
+
if sys.platform == "win32":
|
| 218 |
+
from multiprocessing.reduction import duplicate
|
| 219 |
+
__all__ += ["duplicate"]
|
runtime/Lib/site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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Server process to keep track of unlinked resources, like folders and
|
| 3 |
+
# semaphores and clean them.
|
| 4 |
+
#
|
| 5 |
+
# author: Thomas Moreau
|
| 6 |
+
#
|
| 7 |
+
# adapted from multiprocessing/semaphore_tracker.py (17/02/2017)
|
| 8 |
+
# * include custom spawnv_passfds to start the process
|
| 9 |
+
# * add some VERBOSE logging
|
| 10 |
+
#
|
| 11 |
+
# TODO: multiprocessing.resource_tracker was contributed to Python 3.8 so
|
| 12 |
+
# once loky drops support for Python 3.7 it might be possible to stop
|
| 13 |
+
# maintaining this loky-specific fork. As a consequence, it might also be
|
| 14 |
+
# possible to stop maintaining the loky.backend.synchronize fork of
|
| 15 |
+
# multiprocessing.synchronize.
|
| 16 |
+
|
| 17 |
+
#
|
| 18 |
+
# On Unix we run a server process which keeps track of unlinked
|
| 19 |
+
# resources. The server ignores SIGINT and SIGTERM and reads from a
|
| 20 |
+
# pipe. The resource_tracker implements a reference counting scheme: each time
|
| 21 |
+
# a Python process anticipates the shared usage of a resource by another
|
| 22 |
+
# process, it signals the resource_tracker of this shared usage, and in return,
|
| 23 |
+
# the resource_tracker increments the resource's reference count by 1.
|
| 24 |
+
# Similarly, when access to a resource is closed by a Python process, the
|
| 25 |
+
# process notifies the resource_tracker by asking it to decrement the
|
| 26 |
+
# resource's reference count by 1. When the reference count drops to 0, the
|
| 27 |
+
# resource_tracker attempts to clean up the underlying resource.
|
| 28 |
+
|
| 29 |
+
# Finally, every other process connected to the resource tracker has a copy of
|
| 30 |
+
# the writable end of the pipe used to communicate with it, so the resource
|
| 31 |
+
# tracker gets EOF when all other processes have exited. Then the
|
| 32 |
+
# resource_tracker process unlinks any remaining leaked resources (with
|
| 33 |
+
# reference count above 0)
|
| 34 |
+
|
| 35 |
+
# For semaphores, this is important because the system only supports a limited
|
| 36 |
+
# number of named semaphores, and they will not be automatically removed till
|
| 37 |
+
# the next reboot. Without this resource tracker process, "killall python"
|
| 38 |
+
# would probably leave unlinked semaphores.
|
| 39 |
+
|
| 40 |
+
# Note that this behavior differs from CPython's resource_tracker, which only
|
| 41 |
+
# implements list of shared resources, and not a proper refcounting scheme.
|
| 42 |
+
# Also, CPython's resource tracker will only attempt to cleanup those shared
|
| 43 |
+
# resources once all procsses connected to the resouce tracker have exited.
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
import os
|
| 47 |
+
import shutil
|
| 48 |
+
import sys
|
| 49 |
+
import signal
|
| 50 |
+
import warnings
|
| 51 |
+
import threading
|
| 52 |
+
from _multiprocessing import sem_unlink
|
| 53 |
+
from multiprocessing import util
|
| 54 |
+
|
| 55 |
+
from . import spawn
|
| 56 |
+
|
| 57 |
+
if sys.platform == "win32":
|
| 58 |
+
import _winapi
|
| 59 |
+
import msvcrt
|
| 60 |
+
from multiprocessing.reduction import duplicate
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
__all__ = ['ensure_running', 'register', 'unregister']
|
| 64 |
+
|
| 65 |
+
_HAVE_SIGMASK = hasattr(signal, 'pthread_sigmask')
|
| 66 |
+
_IGNORED_SIGNALS = (signal.SIGINT, signal.SIGTERM)
|
| 67 |
+
|
| 68 |
+
_CLEANUP_FUNCS = {
|
| 69 |
+
'folder': shutil.rmtree,
|
| 70 |
+
'file': os.unlink
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
if os.name == "posix":
|
| 74 |
+
_CLEANUP_FUNCS['semlock'] = sem_unlink
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
VERBOSE = False
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class ResourceTracker:
|
| 81 |
+
|
| 82 |
+
def __init__(self):
|
| 83 |
+
self._lock = threading.Lock()
|
| 84 |
+
self._fd = None
|
| 85 |
+
self._pid = None
|
| 86 |
+
|
| 87 |
+
def getfd(self):
|
| 88 |
+
self.ensure_running()
|
| 89 |
+
return self._fd
|
| 90 |
+
|
| 91 |
+
def ensure_running(self):
|
| 92 |
+
'''Make sure that resource tracker process is running.
|
| 93 |
+
|
| 94 |
+
This can be run from any process. Usually a child process will use
|
| 95 |
+
the resource created by its parent.'''
|
| 96 |
+
with self._lock:
|
| 97 |
+
if self._fd is not None:
|
| 98 |
+
# resource tracker was launched before, is it still running?
|
| 99 |
+
if self._check_alive():
|
| 100 |
+
# => still alive
|
| 101 |
+
return
|
| 102 |
+
# => dead, launch it again
|
| 103 |
+
os.close(self._fd)
|
| 104 |
+
if os.name == "posix":
|
| 105 |
+
try:
|
| 106 |
+
# At this point, the resource_tracker process has been
|
| 107 |
+
# killed or crashed. Let's remove the process entry
|
| 108 |
+
# from the process table to avoid zombie processes.
|
| 109 |
+
os.waitpid(self._pid, 0)
|
| 110 |
+
except OSError:
|
| 111 |
+
# The process was terminated or is a child from an
|
| 112 |
+
# ancestor of the current process.
|
| 113 |
+
pass
|
| 114 |
+
self._fd = None
|
| 115 |
+
self._pid = None
|
| 116 |
+
|
| 117 |
+
warnings.warn('resource_tracker: process died unexpectedly, '
|
| 118 |
+
'relaunching. Some folders/sempahores might '
|
| 119 |
+
'leak.')
|
| 120 |
+
|
| 121 |
+
fds_to_pass = []
|
| 122 |
+
try:
|
| 123 |
+
fds_to_pass.append(sys.stderr.fileno())
|
| 124 |
+
except Exception:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
r, w = os.pipe()
|
| 128 |
+
if sys.platform == "win32":
|
| 129 |
+
_r = duplicate(msvcrt.get_osfhandle(r), inheritable=True)
|
| 130 |
+
os.close(r)
|
| 131 |
+
r = _r
|
| 132 |
+
|
| 133 |
+
cmd = f'from {main.__module__} import main; main({r}, {VERBOSE})'
|
| 134 |
+
try:
|
| 135 |
+
fds_to_pass.append(r)
|
| 136 |
+
# process will out live us, so no need to wait on pid
|
| 137 |
+
exe = spawn.get_executable()
|
| 138 |
+
args = [exe, *util._args_from_interpreter_flags(), '-c', cmd]
|
| 139 |
+
util.debug(f"launching resource tracker: {args}")
|
| 140 |
+
# bpo-33613: Register a signal mask that will block the
|
| 141 |
+
# signals. This signal mask will be inherited by the child
|
| 142 |
+
# that is going to be spawned and will protect the child from a
|
| 143 |
+
# race condition that can make the child die before it
|
| 144 |
+
# registers signal handlers for SIGINT and SIGTERM. The mask is
|
| 145 |
+
# unregistered after spawning the child.
|
| 146 |
+
try:
|
| 147 |
+
if _HAVE_SIGMASK:
|
| 148 |
+
signal.pthread_sigmask(signal.SIG_BLOCK,
|
| 149 |
+
_IGNORED_SIGNALS)
|
| 150 |
+
pid = spawnv_passfds(exe, args, fds_to_pass)
|
| 151 |
+
finally:
|
| 152 |
+
if _HAVE_SIGMASK:
|
| 153 |
+
signal.pthread_sigmask(signal.SIG_UNBLOCK,
|
| 154 |
+
_IGNORED_SIGNALS)
|
| 155 |
+
except BaseException:
|
| 156 |
+
os.close(w)
|
| 157 |
+
raise
|
| 158 |
+
else:
|
| 159 |
+
self._fd = w
|
| 160 |
+
self._pid = pid
|
| 161 |
+
finally:
|
| 162 |
+
if sys.platform == "win32":
|
| 163 |
+
_winapi.CloseHandle(r)
|
| 164 |
+
else:
|
| 165 |
+
os.close(r)
|
| 166 |
+
|
| 167 |
+
def _check_alive(self):
|
| 168 |
+
'''Check for the existence of the resource tracker process.'''
|
| 169 |
+
try:
|
| 170 |
+
self._send('PROBE', '', '')
|
| 171 |
+
except BrokenPipeError:
|
| 172 |
+
return False
|
| 173 |
+
else:
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
def register(self, name, rtype):
|
| 177 |
+
'''Register a named resource, and increment its refcount.'''
|
| 178 |
+
self.ensure_running()
|
| 179 |
+
self._send('REGISTER', name, rtype)
|
| 180 |
+
|
| 181 |
+
def unregister(self, name, rtype):
|
| 182 |
+
'''Unregister a named resource with resource tracker.'''
|
| 183 |
+
self.ensure_running()
|
| 184 |
+
self._send('UNREGISTER', name, rtype)
|
| 185 |
+
|
| 186 |
+
def maybe_unlink(self, name, rtype):
|
| 187 |
+
'''Decrement the refcount of a resource, and delete it if it hits 0'''
|
| 188 |
+
self.ensure_running()
|
| 189 |
+
self._send("MAYBE_UNLINK", name, rtype)
|
| 190 |
+
|
| 191 |
+
def _send(self, cmd, name, rtype):
|
| 192 |
+
if len(name) > 512:
|
| 193 |
+
# posix guarantees that writes to a pipe of less than PIPE_BUF
|
| 194 |
+
# bytes are atomic, and that PIPE_BUF >= 512
|
| 195 |
+
raise ValueError('name too long')
|
| 196 |
+
msg = f'{cmd}:{name}:{rtype}\n'.encode('ascii')
|
| 197 |
+
nbytes = os.write(self._fd, msg)
|
| 198 |
+
assert nbytes == len(msg)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
_resource_tracker = ResourceTracker()
|
| 202 |
+
ensure_running = _resource_tracker.ensure_running
|
| 203 |
+
register = _resource_tracker.register
|
| 204 |
+
maybe_unlink = _resource_tracker.maybe_unlink
|
| 205 |
+
unregister = _resource_tracker.unregister
|
| 206 |
+
getfd = _resource_tracker.getfd
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def main(fd, verbose=0):
|
| 210 |
+
'''Run resource tracker.'''
|
| 211 |
+
# protect the process from ^C and "killall python" etc
|
| 212 |
+
if verbose:
|
| 213 |
+
util.log_to_stderr(level=util.DEBUG)
|
| 214 |
+
|
| 215 |
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
| 216 |
+
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
| 217 |
+
|
| 218 |
+
if _HAVE_SIGMASK:
|
| 219 |
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS)
|
| 220 |
+
|
| 221 |
+
for f in (sys.stdin, sys.stdout):
|
| 222 |
+
try:
|
| 223 |
+
f.close()
|
| 224 |
+
except Exception:
|
| 225 |
+
pass
|
| 226 |
+
|
| 227 |
+
if verbose:
|
| 228 |
+
util.debug("Main resource tracker is running")
|
| 229 |
+
|
| 230 |
+
registry = {rtype: {} for rtype in _CLEANUP_FUNCS.keys()}
|
| 231 |
+
try:
|
| 232 |
+
# keep track of registered/unregistered resources
|
| 233 |
+
if sys.platform == "win32":
|
| 234 |
+
fd = msvcrt.open_osfhandle(fd, os.O_RDONLY)
|
| 235 |
+
with open(fd, 'rb') as f:
|
| 236 |
+
while True:
|
| 237 |
+
line = f.readline()
|
| 238 |
+
if line == b'': # EOF
|
| 239 |
+
break
|
| 240 |
+
try:
|
| 241 |
+
splitted = line.strip().decode('ascii').split(':')
|
| 242 |
+
# name can potentially contain separator symbols (for
|
| 243 |
+
# instance folders on Windows)
|
| 244 |
+
cmd, name, rtype = (
|
| 245 |
+
splitted[0], ':'.join(splitted[1:-1]), splitted[-1])
|
| 246 |
+
|
| 247 |
+
if cmd == 'PROBE':
|
| 248 |
+
continue
|
| 249 |
+
|
| 250 |
+
if rtype not in _CLEANUP_FUNCS:
|
| 251 |
+
raise ValueError(
|
| 252 |
+
f'Cannot register {name} for automatic cleanup: '
|
| 253 |
+
f'unknown resource type ({rtype}). Resource type '
|
| 254 |
+
'should be one of the following: '
|
| 255 |
+
f'{list(_CLEANUP_FUNCS.keys())}'
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
if cmd == 'REGISTER':
|
| 259 |
+
if name not in registry[rtype]:
|
| 260 |
+
registry[rtype][name] = 1
|
| 261 |
+
else:
|
| 262 |
+
registry[rtype][name] += 1
|
| 263 |
+
|
| 264 |
+
if verbose:
|
| 265 |
+
util.debug(
|
| 266 |
+
"[ResourceTracker] incremented refcount of "
|
| 267 |
+
f"{rtype} {name} "
|
| 268 |
+
f"(current {registry[rtype][name]})"
|
| 269 |
+
)
|
| 270 |
+
elif cmd == 'UNREGISTER':
|
| 271 |
+
del registry[rtype][name]
|
| 272 |
+
if verbose:
|
| 273 |
+
util.debug(
|
| 274 |
+
f"[ResourceTracker] unregister {name} {rtype}: "
|
| 275 |
+
f"registry({len(registry)})"
|
| 276 |
+
)
|
| 277 |
+
elif cmd == 'MAYBE_UNLINK':
|
| 278 |
+
registry[rtype][name] -= 1
|
| 279 |
+
if verbose:
|
| 280 |
+
util.debug(
|
| 281 |
+
"[ResourceTracker] decremented refcount of "
|
| 282 |
+
f"{rtype} {name} "
|
| 283 |
+
f"(current {registry[rtype][name]})"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
if registry[rtype][name] == 0:
|
| 287 |
+
del registry[rtype][name]
|
| 288 |
+
try:
|
| 289 |
+
if verbose:
|
| 290 |
+
util.debug(
|
| 291 |
+
f"[ResourceTracker] unlink {name}"
|
| 292 |
+
)
|
| 293 |
+
_CLEANUP_FUNCS[rtype](name)
|
| 294 |
+
except Exception as e:
|
| 295 |
+
warnings.warn(
|
| 296 |
+
f'resource_tracker: {name}: {e!r}')
|
| 297 |
+
|
| 298 |
+
else:
|
| 299 |
+
raise RuntimeError(f'unrecognized command {cmd!r}')
|
| 300 |
+
except BaseException:
|
| 301 |
+
try:
|
| 302 |
+
sys.excepthook(*sys.exc_info())
|
| 303 |
+
except BaseException:
|
| 304 |
+
pass
|
| 305 |
+
finally:
|
| 306 |
+
# all processes have terminated; cleanup any remaining resources
|
| 307 |
+
def _unlink_resources(rtype_registry, rtype):
|
| 308 |
+
if rtype_registry:
|
| 309 |
+
try:
|
| 310 |
+
warnings.warn(
|
| 311 |
+
'resource_tracker: There appear to be '
|
| 312 |
+
f'{len(rtype_registry)} leaked {rtype} objects to '
|
| 313 |
+
'clean up at shutdown'
|
| 314 |
+
)
|
| 315 |
+
except Exception:
|
| 316 |
+
pass
|
| 317 |
+
for name in rtype_registry:
|
| 318 |
+
# For some reason the process which created and registered this
|
| 319 |
+
# resource has failed to unregister it. Presumably it has
|
| 320 |
+
# died. We therefore clean it up.
|
| 321 |
+
try:
|
| 322 |
+
_CLEANUP_FUNCS[rtype](name)
|
| 323 |
+
if verbose:
|
| 324 |
+
util.debug(f"[ResourceTracker] unlink {name}")
|
| 325 |
+
except Exception as e:
|
| 326 |
+
warnings.warn(f'resource_tracker: {name}: {e!r}')
|
| 327 |
+
|
| 328 |
+
for rtype, rtype_registry in registry.items():
|
| 329 |
+
if rtype == "folder":
|
| 330 |
+
continue
|
| 331 |
+
else:
|
| 332 |
+
_unlink_resources(rtype_registry, rtype)
|
| 333 |
+
|
| 334 |
+
# The default cleanup routine for folders deletes everything inside
|
| 335 |
+
# those folders recursively, which can include other resources tracked
|
| 336 |
+
# by the resource tracker). To limit the risk of the resource tracker
|
| 337 |
+
# attempting to delete twice a resource (once as part of a tracked
|
| 338 |
+
# folder, and once as a resource), we delete the folders after all
|
| 339 |
+
# other resource types.
|
| 340 |
+
if "folder" in registry:
|
| 341 |
+
_unlink_resources(registry["folder"], "folder")
|
| 342 |
+
|
| 343 |
+
if verbose:
|
| 344 |
+
util.debug("resource tracker shut down")
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
#
|
| 348 |
+
# Start a program with only specified fds kept open
|
| 349 |
+
#
|
| 350 |
+
|
| 351 |
+
def spawnv_passfds(path, args, passfds):
|
| 352 |
+
passfds = sorted(passfds)
|
| 353 |
+
if sys.platform != "win32":
|
| 354 |
+
errpipe_read, errpipe_write = os.pipe()
|
| 355 |
+
try:
|
| 356 |
+
from .reduction import _mk_inheritable
|
| 357 |
+
from .fork_exec import fork_exec
|
| 358 |
+
_pass = [_mk_inheritable(fd) for fd in passfds]
|
| 359 |
+
return fork_exec(args, _pass)
|
| 360 |
+
finally:
|
| 361 |
+
os.close(errpipe_read)
|
| 362 |
+
os.close(errpipe_write)
|
| 363 |
+
else:
|
| 364 |
+
cmd = ' '.join(f'"{x}"' for x in args)
|
| 365 |
+
try:
|
| 366 |
+
_, ht, pid, _ = _winapi.CreateProcess(
|
| 367 |
+
path, cmd, None, None, True, 0, None, None, None)
|
| 368 |
+
_winapi.CloseHandle(ht)
|
| 369 |
+
except BaseException:
|
| 370 |
+
pass
|
| 371 |
+
return pid
|
runtime/Lib/site-packages/joblib/externals/loky/backend/spawn.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Prepares and processes the data to setup the new process environment
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/spawn.py (17/02/2017)
|
| 7 |
+
# * Improve logging data
|
| 8 |
+
#
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
import runpy
|
| 12 |
+
import types
|
| 13 |
+
from multiprocessing import process, util
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if sys.platform != 'win32':
|
| 17 |
+
WINEXE = False
|
| 18 |
+
WINSERVICE = False
|
| 19 |
+
else:
|
| 20 |
+
import msvcrt
|
| 21 |
+
from multiprocessing.reduction import duplicate
|
| 22 |
+
WINEXE = (sys.platform == 'win32' and getattr(sys, 'frozen', False))
|
| 23 |
+
WINSERVICE = sys.executable.lower().endswith("pythonservice.exe")
|
| 24 |
+
|
| 25 |
+
if WINSERVICE:
|
| 26 |
+
_python_exe = os.path.join(sys.exec_prefix, 'python.exe')
|
| 27 |
+
else:
|
| 28 |
+
_python_exe = sys.executable
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_executable():
|
| 32 |
+
return _python_exe
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _check_not_importing_main():
|
| 36 |
+
if getattr(process.current_process(), '_inheriting', False):
|
| 37 |
+
raise RuntimeError('''
|
| 38 |
+
An attempt has been made to start a new process before the
|
| 39 |
+
current process has finished its bootstrapping phase.
|
| 40 |
+
|
| 41 |
+
This probably means that you are not using fork to start your
|
| 42 |
+
child processes and you have forgotten to use the proper idiom
|
| 43 |
+
in the main module:
|
| 44 |
+
|
| 45 |
+
if __name__ == '__main__':
|
| 46 |
+
freeze_support()
|
| 47 |
+
...
|
| 48 |
+
|
| 49 |
+
The "freeze_support()" line can be omitted if the program
|
| 50 |
+
is not going to be frozen to produce an executable.''')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_preparation_data(name, init_main_module=True):
|
| 54 |
+
'''
|
| 55 |
+
Return info about parent needed by child to unpickle process object
|
| 56 |
+
'''
|
| 57 |
+
_check_not_importing_main()
|
| 58 |
+
d = dict(
|
| 59 |
+
log_to_stderr=util._log_to_stderr,
|
| 60 |
+
authkey=bytes(process.current_process().authkey),
|
| 61 |
+
name=name,
|
| 62 |
+
sys_argv=sys.argv,
|
| 63 |
+
orig_dir=process.ORIGINAL_DIR,
|
| 64 |
+
dir=os.getcwd()
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Send sys_path and make sure the current directory will not be changed
|
| 68 |
+
d['sys_path'] = [p if p != '' else process.ORIGINAL_DIR for p in sys.path]
|
| 69 |
+
|
| 70 |
+
# Make sure to pass the information if the multiprocessing logger is active
|
| 71 |
+
if util._logger is not None:
|
| 72 |
+
d['log_level'] = util._logger.getEffectiveLevel()
|
| 73 |
+
if util._logger.handlers:
|
| 74 |
+
h = util._logger.handlers[0]
|
| 75 |
+
d['log_fmt'] = h.formatter._fmt
|
| 76 |
+
|
| 77 |
+
# Tell the child how to communicate with the resource_tracker
|
| 78 |
+
from .resource_tracker import _resource_tracker
|
| 79 |
+
_resource_tracker.ensure_running()
|
| 80 |
+
d["tracker_args"] = {"pid": _resource_tracker._pid}
|
| 81 |
+
if sys.platform == "win32":
|
| 82 |
+
child_w = duplicate(
|
| 83 |
+
msvcrt.get_osfhandle(_resource_tracker._fd), inheritable=True)
|
| 84 |
+
d["tracker_args"]["fh"] = child_w
|
| 85 |
+
else:
|
| 86 |
+
d["tracker_args"]["fd"] = _resource_tracker._fd
|
| 87 |
+
|
| 88 |
+
if sys.version_info >= (3, 8) and os.name == 'posix':
|
| 89 |
+
# joblib/loky#242: allow loky processes to retrieve the resource
|
| 90 |
+
# tracker of their parent in case the child processes depickles
|
| 91 |
+
# shared_memory objects, that are still tracked by multiprocessing's
|
| 92 |
+
# resource_tracker by default.
|
| 93 |
+
# XXX: this is a workaround that may be error prone: in the future, it
|
| 94 |
+
# would be better to have loky subclass multiprocessing's shared_memory
|
| 95 |
+
# to force registration of shared_memory segments via loky's
|
| 96 |
+
# resource_tracker.
|
| 97 |
+
from multiprocessing.resource_tracker import (
|
| 98 |
+
_resource_tracker as mp_resource_tracker
|
| 99 |
+
)
|
| 100 |
+
# multiprocessing's resource_tracker must be running before loky
|
| 101 |
+
# process is created (othewise the child won't be able to use it if it
|
| 102 |
+
# is created later on)
|
| 103 |
+
mp_resource_tracker.ensure_running()
|
| 104 |
+
d["mp_tracker_args"] = {
|
| 105 |
+
'fd': mp_resource_tracker._fd, 'pid': mp_resource_tracker._pid
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
# Figure out whether to initialise main in the subprocess as a module
|
| 109 |
+
# or through direct execution (or to leave it alone entirely)
|
| 110 |
+
if init_main_module:
|
| 111 |
+
main_module = sys.modules['__main__']
|
| 112 |
+
try:
|
| 113 |
+
main_mod_name = getattr(main_module.__spec__, "name", None)
|
| 114 |
+
except BaseException:
|
| 115 |
+
main_mod_name = None
|
| 116 |
+
if main_mod_name is not None:
|
| 117 |
+
d['init_main_from_name'] = main_mod_name
|
| 118 |
+
elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
|
| 119 |
+
main_path = getattr(main_module, '__file__', None)
|
| 120 |
+
if main_path is not None:
|
| 121 |
+
if (not os.path.isabs(main_path) and
|
| 122 |
+
process.ORIGINAL_DIR is not None):
|
| 123 |
+
main_path = os.path.join(process.ORIGINAL_DIR, main_path)
|
| 124 |
+
d['init_main_from_path'] = os.path.normpath(main_path)
|
| 125 |
+
|
| 126 |
+
return d
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
#
|
| 130 |
+
# Prepare current process
|
| 131 |
+
#
|
| 132 |
+
old_main_modules = []
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def prepare(data):
|
| 136 |
+
'''
|
| 137 |
+
Try to get current process ready to unpickle process object
|
| 138 |
+
'''
|
| 139 |
+
if 'name' in data:
|
| 140 |
+
process.current_process().name = data['name']
|
| 141 |
+
|
| 142 |
+
if 'authkey' in data:
|
| 143 |
+
process.current_process().authkey = data['authkey']
|
| 144 |
+
|
| 145 |
+
if 'log_to_stderr' in data and data['log_to_stderr']:
|
| 146 |
+
util.log_to_stderr()
|
| 147 |
+
|
| 148 |
+
if 'log_level' in data:
|
| 149 |
+
util.get_logger().setLevel(data['log_level'])
|
| 150 |
+
|
| 151 |
+
if 'log_fmt' in data:
|
| 152 |
+
import logging
|
| 153 |
+
util.get_logger().handlers[0].setFormatter(
|
| 154 |
+
logging.Formatter(data['log_fmt'])
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
if 'sys_path' in data:
|
| 158 |
+
sys.path = data['sys_path']
|
| 159 |
+
|
| 160 |
+
if 'sys_argv' in data:
|
| 161 |
+
sys.argv = data['sys_argv']
|
| 162 |
+
|
| 163 |
+
if 'dir' in data:
|
| 164 |
+
os.chdir(data['dir'])
|
| 165 |
+
|
| 166 |
+
if 'orig_dir' in data:
|
| 167 |
+
process.ORIGINAL_DIR = data['orig_dir']
|
| 168 |
+
|
| 169 |
+
if 'mp_tracker_args' in data:
|
| 170 |
+
from multiprocessing.resource_tracker import (
|
| 171 |
+
_resource_tracker as mp_resource_tracker
|
| 172 |
+
)
|
| 173 |
+
mp_resource_tracker._fd = data['mp_tracker_args']['fd']
|
| 174 |
+
mp_resource_tracker._pid = data['mp_tracker_args']['pid']
|
| 175 |
+
if 'tracker_args' in data:
|
| 176 |
+
from .resource_tracker import _resource_tracker
|
| 177 |
+
_resource_tracker._pid = data["tracker_args"]['pid']
|
| 178 |
+
if sys.platform == 'win32':
|
| 179 |
+
handle = data["tracker_args"]["fh"]
|
| 180 |
+
_resource_tracker._fd = msvcrt.open_osfhandle(handle, 0)
|
| 181 |
+
else:
|
| 182 |
+
_resource_tracker._fd = data["tracker_args"]["fd"]
|
| 183 |
+
|
| 184 |
+
if 'init_main_from_name' in data:
|
| 185 |
+
_fixup_main_from_name(data['init_main_from_name'])
|
| 186 |
+
elif 'init_main_from_path' in data:
|
| 187 |
+
_fixup_main_from_path(data['init_main_from_path'])
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# Multiprocessing module helpers to fix up the main module in
|
| 191 |
+
# spawned subprocesses
|
| 192 |
+
def _fixup_main_from_name(mod_name):
|
| 193 |
+
# __main__.py files for packages, directories, zip archives, etc, run
|
| 194 |
+
# their "main only" code unconditionally, so we don't even try to
|
| 195 |
+
# populate anything in __main__, nor do we make any changes to
|
| 196 |
+
# __main__ attributes
|
| 197 |
+
current_main = sys.modules['__main__']
|
| 198 |
+
if mod_name == "__main__" or mod_name.endswith(".__main__"):
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
# If this process was forked, __main__ may already be populated
|
| 202 |
+
if getattr(current_main.__spec__, "name", None) == mod_name:
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
# Otherwise, __main__ may contain some non-main code where we need to
|
| 206 |
+
# support unpickling it properly. We rerun it as __mp_main__ and make
|
| 207 |
+
# the normal __main__ an alias to that
|
| 208 |
+
old_main_modules.append(current_main)
|
| 209 |
+
main_module = types.ModuleType("__mp_main__")
|
| 210 |
+
main_content = runpy.run_module(mod_name,
|
| 211 |
+
run_name="__mp_main__",
|
| 212 |
+
alter_sys=True)
|
| 213 |
+
main_module.__dict__.update(main_content)
|
| 214 |
+
sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _fixup_main_from_path(main_path):
|
| 218 |
+
# If this process was forked, __main__ may already be populated
|
| 219 |
+
current_main = sys.modules['__main__']
|
| 220 |
+
|
| 221 |
+
# Unfortunately, the main ipython launch script historically had no
|
| 222 |
+
# "if __name__ == '__main__'" guard, so we work around that
|
| 223 |
+
# by treating it like a __main__.py file
|
| 224 |
+
# See https://github.com/ipython/ipython/issues/4698
|
| 225 |
+
main_name = os.path.splitext(os.path.basename(main_path))[0]
|
| 226 |
+
if main_name == 'ipython':
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
# Otherwise, if __file__ already has the setting we expect,
|
| 230 |
+
# there's nothing more to do
|
| 231 |
+
if getattr(current_main, '__file__', None) == main_path:
|
| 232 |
+
return
|
| 233 |
+
|
| 234 |
+
# If the parent process has sent a path through rather than a module
|
| 235 |
+
# name we assume it is an executable script that may contain
|
| 236 |
+
# non-main code that needs to be executed
|
| 237 |
+
old_main_modules.append(current_main)
|
| 238 |
+
main_module = types.ModuleType("__mp_main__")
|
| 239 |
+
main_content = runpy.run_path(main_path,
|
| 240 |
+
run_name="__mp_main__")
|
| 241 |
+
main_module.__dict__.update(main_content)
|
| 242 |
+
sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module
|
runtime/Lib/site-packages/joblib/externals/loky/backend/synchronize.py
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Synchronization primitives based on our SemLock implementation
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from multiprocessing/synchronize.py (17/02/2017)
|
| 7 |
+
# * Remove ctx argument for compatibility reason
|
| 8 |
+
# * Registers a cleanup function with the loky resource_tracker to remove the
|
| 9 |
+
# semaphore when the process dies instead.
|
| 10 |
+
#
|
| 11 |
+
# TODO: investigate which Python version is required to be able to use
|
| 12 |
+
# multiprocessing.resource_tracker and therefore multiprocessing.synchronize
|
| 13 |
+
# instead of a loky-specific fork.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import tempfile
|
| 18 |
+
import threading
|
| 19 |
+
import _multiprocessing
|
| 20 |
+
from time import time as _time
|
| 21 |
+
from multiprocessing import process, util
|
| 22 |
+
from multiprocessing.context import assert_spawning
|
| 23 |
+
|
| 24 |
+
from . import resource_tracker
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition', 'Event'
|
| 28 |
+
]
|
| 29 |
+
# Try to import the mp.synchronize module cleanly, if it fails
|
| 30 |
+
# raise ImportError for platforms lacking a working sem_open implementation.
|
| 31 |
+
# See issue 3770
|
| 32 |
+
try:
|
| 33 |
+
from _multiprocessing import SemLock as _SemLock
|
| 34 |
+
from _multiprocessing import sem_unlink
|
| 35 |
+
except ImportError:
|
| 36 |
+
raise ImportError("This platform lacks a functioning sem_open" +
|
| 37 |
+
" implementation, therefore, the required" +
|
| 38 |
+
" synchronization primitives needed will not" +
|
| 39 |
+
" function, see issue 3770.")
|
| 40 |
+
|
| 41 |
+
#
|
| 42 |
+
# Constants
|
| 43 |
+
#
|
| 44 |
+
|
| 45 |
+
RECURSIVE_MUTEX, SEMAPHORE = range(2)
|
| 46 |
+
SEM_VALUE_MAX = _multiprocessing.SemLock.SEM_VALUE_MAX
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
#
|
| 50 |
+
# Base class for semaphores and mutexes; wraps `_multiprocessing.SemLock`
|
| 51 |
+
#
|
| 52 |
+
|
| 53 |
+
class SemLock:
|
| 54 |
+
|
| 55 |
+
_rand = tempfile._RandomNameSequence()
|
| 56 |
+
|
| 57 |
+
def __init__(self, kind, value, maxvalue, name=None):
|
| 58 |
+
# unlink_now is only used on win32 or when we are using fork.
|
| 59 |
+
unlink_now = False
|
| 60 |
+
if name is None:
|
| 61 |
+
# Try to find an unused name for the SemLock instance.
|
| 62 |
+
for _ in range(100):
|
| 63 |
+
try:
|
| 64 |
+
self._semlock = _SemLock(
|
| 65 |
+
kind, value, maxvalue, SemLock._make_name(), unlink_now
|
| 66 |
+
)
|
| 67 |
+
except FileExistsError: # pragma: no cover
|
| 68 |
+
pass
|
| 69 |
+
else:
|
| 70 |
+
break
|
| 71 |
+
else: # pragma: no cover
|
| 72 |
+
raise FileExistsError('cannot find name for semaphore')
|
| 73 |
+
else:
|
| 74 |
+
self._semlock = _SemLock(
|
| 75 |
+
kind, value, maxvalue, name, unlink_now
|
| 76 |
+
)
|
| 77 |
+
self.name = name
|
| 78 |
+
util.debug(
|
| 79 |
+
f'created semlock with handle {self._semlock.handle} and name '
|
| 80 |
+
f'"{self.name}"'
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
self._make_methods()
|
| 84 |
+
|
| 85 |
+
def _after_fork(obj):
|
| 86 |
+
obj._semlock._after_fork()
|
| 87 |
+
|
| 88 |
+
util.register_after_fork(self, _after_fork)
|
| 89 |
+
|
| 90 |
+
# When the object is garbage collected or the
|
| 91 |
+
# process shuts down we unlink the semaphore name
|
| 92 |
+
resource_tracker.register(self._semlock.name, "semlock")
|
| 93 |
+
util.Finalize(self, SemLock._cleanup, (self._semlock.name,),
|
| 94 |
+
exitpriority=0)
|
| 95 |
+
|
| 96 |
+
@staticmethod
|
| 97 |
+
def _cleanup(name):
|
| 98 |
+
try:
|
| 99 |
+
sem_unlink(name)
|
| 100 |
+
except FileNotFoundError:
|
| 101 |
+
# Already unlinked, possibly by user code: ignore and make sure to
|
| 102 |
+
# unregister the semaphore from the resource tracker.
|
| 103 |
+
pass
|
| 104 |
+
finally:
|
| 105 |
+
resource_tracker.unregister(name, "semlock")
|
| 106 |
+
|
| 107 |
+
def _make_methods(self):
|
| 108 |
+
self.acquire = self._semlock.acquire
|
| 109 |
+
self.release = self._semlock.release
|
| 110 |
+
|
| 111 |
+
def __enter__(self):
|
| 112 |
+
return self._semlock.acquire()
|
| 113 |
+
|
| 114 |
+
def __exit__(self, *args):
|
| 115 |
+
return self._semlock.release()
|
| 116 |
+
|
| 117 |
+
def __getstate__(self):
|
| 118 |
+
assert_spawning(self)
|
| 119 |
+
sl = self._semlock
|
| 120 |
+
h = sl.handle
|
| 121 |
+
return (h, sl.kind, sl.maxvalue, sl.name)
|
| 122 |
+
|
| 123 |
+
def __setstate__(self, state):
|
| 124 |
+
self._semlock = _SemLock._rebuild(*state)
|
| 125 |
+
util.debug(
|
| 126 |
+
f'recreated blocker with handle {state[0]!r} and name "{state[3]}"'
|
| 127 |
+
)
|
| 128 |
+
self._make_methods()
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def _make_name():
|
| 132 |
+
# OSX does not support long names for semaphores
|
| 133 |
+
return f'/loky-{os.getpid()}-{next(SemLock._rand)}'
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
#
|
| 137 |
+
# Semaphore
|
| 138 |
+
#
|
| 139 |
+
|
| 140 |
+
class Semaphore(SemLock):
|
| 141 |
+
|
| 142 |
+
def __init__(self, value=1):
|
| 143 |
+
SemLock.__init__(self, SEMAPHORE, value, SEM_VALUE_MAX)
|
| 144 |
+
|
| 145 |
+
def get_value(self):
|
| 146 |
+
if sys.platform == 'darwin':
|
| 147 |
+
raise NotImplementedError("OSX does not implement sem_getvalue")
|
| 148 |
+
return self._semlock._get_value()
|
| 149 |
+
|
| 150 |
+
def __repr__(self):
|
| 151 |
+
try:
|
| 152 |
+
value = self._semlock._get_value()
|
| 153 |
+
except Exception:
|
| 154 |
+
value = 'unknown'
|
| 155 |
+
return f'<{self.__class__.__name__}(value={value})>'
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
#
|
| 159 |
+
# Bounded semaphore
|
| 160 |
+
#
|
| 161 |
+
|
| 162 |
+
class BoundedSemaphore(Semaphore):
|
| 163 |
+
|
| 164 |
+
def __init__(self, value=1):
|
| 165 |
+
SemLock.__init__(self, SEMAPHORE, value, value)
|
| 166 |
+
|
| 167 |
+
def __repr__(self):
|
| 168 |
+
try:
|
| 169 |
+
value = self._semlock._get_value()
|
| 170 |
+
except Exception:
|
| 171 |
+
value = 'unknown'
|
| 172 |
+
return (
|
| 173 |
+
f'<{self.__class__.__name__}(value={value}, '
|
| 174 |
+
f'maxvalue={self._semlock.maxvalue})>'
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
#
|
| 179 |
+
# Non-recursive lock
|
| 180 |
+
#
|
| 181 |
+
|
| 182 |
+
class Lock(SemLock):
|
| 183 |
+
|
| 184 |
+
def __init__(self):
|
| 185 |
+
super().__init__(SEMAPHORE, 1, 1)
|
| 186 |
+
|
| 187 |
+
def __repr__(self):
|
| 188 |
+
try:
|
| 189 |
+
if self._semlock._is_mine():
|
| 190 |
+
name = process.current_process().name
|
| 191 |
+
if threading.current_thread().name != 'MainThread':
|
| 192 |
+
name = f'{name}|{threading.current_thread().name}'
|
| 193 |
+
elif self._semlock._get_value() == 1:
|
| 194 |
+
name = 'None'
|
| 195 |
+
elif self._semlock._count() > 0:
|
| 196 |
+
name = 'SomeOtherThread'
|
| 197 |
+
else:
|
| 198 |
+
name = 'SomeOtherProcess'
|
| 199 |
+
except Exception:
|
| 200 |
+
name = 'unknown'
|
| 201 |
+
return f'<{self.__class__.__name__}(owner={name})>'
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
#
|
| 205 |
+
# Recursive lock
|
| 206 |
+
#
|
| 207 |
+
|
| 208 |
+
class RLock(SemLock):
|
| 209 |
+
|
| 210 |
+
def __init__(self):
|
| 211 |
+
super().__init__(RECURSIVE_MUTEX, 1, 1)
|
| 212 |
+
|
| 213 |
+
def __repr__(self):
|
| 214 |
+
try:
|
| 215 |
+
if self._semlock._is_mine():
|
| 216 |
+
name = process.current_process().name
|
| 217 |
+
if threading.current_thread().name != 'MainThread':
|
| 218 |
+
name = f'{name}|{threading.current_thread().name}'
|
| 219 |
+
count = self._semlock._count()
|
| 220 |
+
elif self._semlock._get_value() == 1:
|
| 221 |
+
name, count = 'None', 0
|
| 222 |
+
elif self._semlock._count() > 0:
|
| 223 |
+
name, count = 'SomeOtherThread', 'nonzero'
|
| 224 |
+
else:
|
| 225 |
+
name, count = 'SomeOtherProcess', 'nonzero'
|
| 226 |
+
except Exception:
|
| 227 |
+
name, count = 'unknown', 'unknown'
|
| 228 |
+
return f'<{self.__class__.__name__}({name}, {count})>'
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
#
|
| 232 |
+
# Condition variable
|
| 233 |
+
#
|
| 234 |
+
|
| 235 |
+
class Condition:
|
| 236 |
+
|
| 237 |
+
def __init__(self, lock=None):
|
| 238 |
+
self._lock = lock or RLock()
|
| 239 |
+
self._sleeping_count = Semaphore(0)
|
| 240 |
+
self._woken_count = Semaphore(0)
|
| 241 |
+
self._wait_semaphore = Semaphore(0)
|
| 242 |
+
self._make_methods()
|
| 243 |
+
|
| 244 |
+
def __getstate__(self):
|
| 245 |
+
assert_spawning(self)
|
| 246 |
+
return (self._lock, self._sleeping_count,
|
| 247 |
+
self._woken_count, self._wait_semaphore)
|
| 248 |
+
|
| 249 |
+
def __setstate__(self, state):
|
| 250 |
+
(self._lock, self._sleeping_count,
|
| 251 |
+
self._woken_count, self._wait_semaphore) = state
|
| 252 |
+
self._make_methods()
|
| 253 |
+
|
| 254 |
+
def __enter__(self):
|
| 255 |
+
return self._lock.__enter__()
|
| 256 |
+
|
| 257 |
+
def __exit__(self, *args):
|
| 258 |
+
return self._lock.__exit__(*args)
|
| 259 |
+
|
| 260 |
+
def _make_methods(self):
|
| 261 |
+
self.acquire = self._lock.acquire
|
| 262 |
+
self.release = self._lock.release
|
| 263 |
+
|
| 264 |
+
def __repr__(self):
|
| 265 |
+
try:
|
| 266 |
+
num_waiters = (self._sleeping_count._semlock._get_value() -
|
| 267 |
+
self._woken_count._semlock._get_value())
|
| 268 |
+
except Exception:
|
| 269 |
+
num_waiters = 'unknown'
|
| 270 |
+
return f'<{self.__class__.__name__}({self._lock}, {num_waiters})>'
|
| 271 |
+
|
| 272 |
+
def wait(self, timeout=None):
|
| 273 |
+
assert self._lock._semlock._is_mine(), \
|
| 274 |
+
'must acquire() condition before using wait()'
|
| 275 |
+
|
| 276 |
+
# indicate that this thread is going to sleep
|
| 277 |
+
self._sleeping_count.release()
|
| 278 |
+
|
| 279 |
+
# release lock
|
| 280 |
+
count = self._lock._semlock._count()
|
| 281 |
+
for _ in range(count):
|
| 282 |
+
self._lock.release()
|
| 283 |
+
|
| 284 |
+
try:
|
| 285 |
+
# wait for notification or timeout
|
| 286 |
+
return self._wait_semaphore.acquire(True, timeout)
|
| 287 |
+
finally:
|
| 288 |
+
# indicate that this thread has woken
|
| 289 |
+
self._woken_count.release()
|
| 290 |
+
|
| 291 |
+
# reacquire lock
|
| 292 |
+
for _ in range(count):
|
| 293 |
+
self._lock.acquire()
|
| 294 |
+
|
| 295 |
+
def notify(self):
|
| 296 |
+
assert self._lock._semlock._is_mine(), 'lock is not owned'
|
| 297 |
+
assert not self._wait_semaphore.acquire(False)
|
| 298 |
+
|
| 299 |
+
# to take account of timeouts since last notify() we subtract
|
| 300 |
+
# woken_count from sleeping_count and rezero woken_count
|
| 301 |
+
while self._woken_count.acquire(False):
|
| 302 |
+
res = self._sleeping_count.acquire(False)
|
| 303 |
+
assert res
|
| 304 |
+
|
| 305 |
+
if self._sleeping_count.acquire(False): # try grabbing a sleeper
|
| 306 |
+
self._wait_semaphore.release() # wake up one sleeper
|
| 307 |
+
self._woken_count.acquire() # wait for the sleeper to wake
|
| 308 |
+
|
| 309 |
+
# rezero _wait_semaphore in case a timeout just happened
|
| 310 |
+
self._wait_semaphore.acquire(False)
|
| 311 |
+
|
| 312 |
+
def notify_all(self):
|
| 313 |
+
assert self._lock._semlock._is_mine(), 'lock is not owned'
|
| 314 |
+
assert not self._wait_semaphore.acquire(False)
|
| 315 |
+
|
| 316 |
+
# to take account of timeouts since last notify*() we subtract
|
| 317 |
+
# woken_count from sleeping_count and rezero woken_count
|
| 318 |
+
while self._woken_count.acquire(False):
|
| 319 |
+
res = self._sleeping_count.acquire(False)
|
| 320 |
+
assert res
|
| 321 |
+
|
| 322 |
+
sleepers = 0
|
| 323 |
+
while self._sleeping_count.acquire(False):
|
| 324 |
+
self._wait_semaphore.release() # wake up one sleeper
|
| 325 |
+
sleepers += 1
|
| 326 |
+
|
| 327 |
+
if sleepers:
|
| 328 |
+
for _ in range(sleepers):
|
| 329 |
+
self._woken_count.acquire() # wait for a sleeper to wake
|
| 330 |
+
|
| 331 |
+
# rezero wait_semaphore in case some timeouts just happened
|
| 332 |
+
while self._wait_semaphore.acquire(False):
|
| 333 |
+
pass
|
| 334 |
+
|
| 335 |
+
def wait_for(self, predicate, timeout=None):
|
| 336 |
+
result = predicate()
|
| 337 |
+
if result:
|
| 338 |
+
return result
|
| 339 |
+
if timeout is not None:
|
| 340 |
+
endtime = _time() + timeout
|
| 341 |
+
else:
|
| 342 |
+
endtime = None
|
| 343 |
+
waittime = None
|
| 344 |
+
while not result:
|
| 345 |
+
if endtime is not None:
|
| 346 |
+
waittime = endtime - _time()
|
| 347 |
+
if waittime <= 0:
|
| 348 |
+
break
|
| 349 |
+
self.wait(waittime)
|
| 350 |
+
result = predicate()
|
| 351 |
+
return result
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
#
|
| 355 |
+
# Event
|
| 356 |
+
#
|
| 357 |
+
|
| 358 |
+
class Event:
|
| 359 |
+
|
| 360 |
+
def __init__(self):
|
| 361 |
+
self._cond = Condition(Lock())
|
| 362 |
+
self._flag = Semaphore(0)
|
| 363 |
+
|
| 364 |
+
def is_set(self):
|
| 365 |
+
with self._cond:
|
| 366 |
+
if self._flag.acquire(False):
|
| 367 |
+
self._flag.release()
|
| 368 |
+
return True
|
| 369 |
+
return False
|
| 370 |
+
|
| 371 |
+
def set(self):
|
| 372 |
+
with self._cond:
|
| 373 |
+
self._flag.acquire(False)
|
| 374 |
+
self._flag.release()
|
| 375 |
+
self._cond.notify_all()
|
| 376 |
+
|
| 377 |
+
def clear(self):
|
| 378 |
+
with self._cond:
|
| 379 |
+
self._flag.acquire(False)
|
| 380 |
+
|
| 381 |
+
def wait(self, timeout=None):
|
| 382 |
+
with self._cond:
|
| 383 |
+
if self._flag.acquire(False):
|
| 384 |
+
self._flag.release()
|
| 385 |
+
else:
|
| 386 |
+
self._cond.wait(timeout)
|
| 387 |
+
|
| 388 |
+
if self._flag.acquire(False):
|
| 389 |
+
self._flag.release()
|
| 390 |
+
return True
|
| 391 |
+
return False
|
runtime/Lib/site-packages/joblib/externals/loky/backend/utils.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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subprocess
|
| 8 |
+
import traceback
|
| 9 |
+
try:
|
| 10 |
+
import psutil
|
| 11 |
+
except ImportError:
|
| 12 |
+
psutil = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def kill_process_tree(process, use_psutil=True):
|
| 16 |
+
"""Terminate process and its descendants with SIGKILL"""
|
| 17 |
+
if use_psutil and psutil is not None:
|
| 18 |
+
_kill_process_tree_with_psutil(process)
|
| 19 |
+
else:
|
| 20 |
+
_kill_process_tree_without_psutil(process)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def recursive_terminate(process, use_psutil=True):
|
| 24 |
+
warnings.warn(
|
| 25 |
+
"recursive_terminate is deprecated in loky 3.2, use kill_process_tree"
|
| 26 |
+
"instead",
|
| 27 |
+
DeprecationWarning,
|
| 28 |
+
)
|
| 29 |
+
kill_process_tree(process, use_psutil=use_psutil)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _kill_process_tree_with_psutil(process):
|
| 33 |
+
try:
|
| 34 |
+
descendants = psutil.Process(process.pid).children(recursive=True)
|
| 35 |
+
except psutil.NoSuchProcess:
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
# Kill the descendants in reverse order to avoid killing the parents before
|
| 39 |
+
# the descendant in cases where there are more processes nested.
|
| 40 |
+
for descendant in descendants[::-1]:
|
| 41 |
+
try:
|
| 42 |
+
descendant.kill()
|
| 43 |
+
except psutil.NoSuchProcess:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
psutil.Process(process.pid).kill()
|
| 48 |
+
except psutil.NoSuchProcess:
|
| 49 |
+
pass
|
| 50 |
+
process.join()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _kill_process_tree_without_psutil(process):
|
| 54 |
+
"""Terminate a process and its descendants."""
|
| 55 |
+
try:
|
| 56 |
+
if sys.platform == "win32":
|
| 57 |
+
_windows_taskkill_process_tree(process.pid)
|
| 58 |
+
else:
|
| 59 |
+
_posix_recursive_kill(process.pid)
|
| 60 |
+
except Exception: # pragma: no cover
|
| 61 |
+
details = traceback.format_exc()
|
| 62 |
+
warnings.warn(
|
| 63 |
+
"Failed to kill subprocesses on this platform. Please install"
|
| 64 |
+
"psutil: https://github.com/giampaolo/psutil\n"
|
| 65 |
+
f"Details:\n{details}"
|
| 66 |
+
)
|
| 67 |
+
# In case we cannot introspect or kill the descendants, we fall back to
|
| 68 |
+
# only killing the main process.
|
| 69 |
+
#
|
| 70 |
+
# Note: on Windows, process.kill() is an alias for process.terminate()
|
| 71 |
+
# which in turns calls the Win32 API function TerminateProcess().
|
| 72 |
+
process.kill()
|
| 73 |
+
process.join()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _windows_taskkill_process_tree(pid):
|
| 77 |
+
# On windows, the taskkill function with option `/T` terminate a given
|
| 78 |
+
# process pid and its children.
|
| 79 |
+
try:
|
| 80 |
+
subprocess.check_output(
|
| 81 |
+
["taskkill", "/F", "/T", "/PID", str(pid)], stderr=None
|
| 82 |
+
)
|
| 83 |
+
except subprocess.CalledProcessError as e:
|
| 84 |
+
# In Windows, taskkill returns 128, 255 for no process found.
|
| 85 |
+
if e.returncode not in [128, 255]:
|
| 86 |
+
# Let's raise to let the caller log the error details in a
|
| 87 |
+
# warning and only kill the root process.
|
| 88 |
+
raise # pragma: no cover
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _kill(pid):
|
| 92 |
+
# Not all systems (e.g. Windows) have a SIGKILL, but the C specification
|
| 93 |
+
# mandates a SIGTERM signal. While Windows is handled specifically above,
|
| 94 |
+
# let's try to be safe for other hypothetic platforms that only have
|
| 95 |
+
# SIGTERM without SIGKILL.
|
| 96 |
+
kill_signal = getattr(signal, 'SIGKILL', signal.SIGTERM)
|
| 97 |
+
try:
|
| 98 |
+
os.kill(pid, kill_signal)
|
| 99 |
+
except OSError as e:
|
| 100 |
+
# if OSError is raised with [Errno 3] no such process, the process
|
| 101 |
+
# is already terminated, else, raise the error and let the top
|
| 102 |
+
# level function raise a warning and retry to kill the process.
|
| 103 |
+
if e.errno != errno.ESRCH:
|
| 104 |
+
raise # pragma: no cover
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _posix_recursive_kill(pid):
|
| 108 |
+
"""Recursively kill the descendants of a process before killing it."""
|
| 109 |
+
try:
|
| 110 |
+
children_pids = subprocess.check_output(
|
| 111 |
+
["pgrep", "-P", str(pid)], stderr=None, text=True
|
| 112 |
+
)
|
| 113 |
+
except subprocess.CalledProcessError as e:
|
| 114 |
+
# `ps` returns 1 when no child process has been found
|
| 115 |
+
if e.returncode == 1:
|
| 116 |
+
children_pids = ''
|
| 117 |
+
else:
|
| 118 |
+
raise # pragma: no cover
|
| 119 |
+
|
| 120 |
+
# Decode the result, split the cpid and remove the trailing line
|
| 121 |
+
for cpid in children_pids.splitlines():
|
| 122 |
+
cpid = int(cpid)
|
| 123 |
+
_posix_recursive_kill(cpid)
|
| 124 |
+
|
| 125 |
+
_kill(pid)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_exitcodes_terminated_worker(processes):
|
| 129 |
+
"""Return a formated string with the exitcodes of terminated workers.
|
| 130 |
+
|
| 131 |
+
If necessary, wait (up to .25s) for the system to correctly set the
|
| 132 |
+
exitcode of one terminated worker.
|
| 133 |
+
"""
|
| 134 |
+
patience = 5
|
| 135 |
+
|
| 136 |
+
# Catch the exitcode of the terminated workers. There should at least be
|
| 137 |
+
# one. If not, wait a bit for the system to correctly set the exitcode of
|
| 138 |
+
# the terminated worker.
|
| 139 |
+
exitcodes = [p.exitcode for p in list(processes.values())
|
| 140 |
+
if p.exitcode is not None]
|
| 141 |
+
while not exitcodes and patience > 0:
|
| 142 |
+
patience -= 1
|
| 143 |
+
exitcodes = [p.exitcode for p in list(processes.values())
|
| 144 |
+
if p.exitcode is not None]
|
| 145 |
+
time.sleep(.05)
|
| 146 |
+
|
| 147 |
+
return _format_exitcodes(exitcodes)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _format_exitcodes(exitcodes):
|
| 151 |
+
"""Format a list of exit code with names of the signals if possible"""
|
| 152 |
+
str_exitcodes = [f"{_get_exitcode_name(e)}({e})"
|
| 153 |
+
for e in exitcodes if e is not None]
|
| 154 |
+
return "{" + ", ".join(str_exitcodes) + "}"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _get_exitcode_name(exitcode):
|
| 158 |
+
if sys.platform == "win32":
|
| 159 |
+
# The exitcode are unreliable on windows (see bpo-31863).
|
| 160 |
+
# For this case, return UNKNOWN
|
| 161 |
+
return "UNKNOWN"
|
| 162 |
+
|
| 163 |
+
if exitcode < 0:
|
| 164 |
+
try:
|
| 165 |
+
import signal
|
| 166 |
+
return signal.Signals(-exitcode).name
|
| 167 |
+
except ValueError:
|
| 168 |
+
return "UNKNOWN"
|
| 169 |
+
elif exitcode != 255:
|
| 170 |
+
# The exitcode are unreliable on forkserver were 255 is always returned
|
| 171 |
+
# (see bpo-30589). For this case, return UNKNOWN
|
| 172 |
+
return "EXIT"
|
| 173 |
+
|
| 174 |
+
return "UNKNOWN"
|
runtime/Lib/site-packages/joblib/externals/loky/cloudpickle_wrapper.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
from functools import partial
|
| 3 |
+
from joblib.externals.cloudpickle import dumps, loads
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
WRAP_CACHE = {}
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CloudpickledObjectWrapper:
|
| 10 |
+
def __init__(self, obj, keep_wrapper=False):
|
| 11 |
+
self._obj = obj
|
| 12 |
+
self._keep_wrapper = keep_wrapper
|
| 13 |
+
|
| 14 |
+
def __reduce__(self):
|
| 15 |
+
_pickled_object = dumps(self._obj)
|
| 16 |
+
if not self._keep_wrapper:
|
| 17 |
+
return loads, (_pickled_object,)
|
| 18 |
+
|
| 19 |
+
return _reconstruct_wrapper, (_pickled_object, self._keep_wrapper)
|
| 20 |
+
|
| 21 |
+
def __getattr__(self, attr):
|
| 22 |
+
# Ensure that the wrapped object can be used seemlessly as the
|
| 23 |
+
# previous object.
|
| 24 |
+
if attr not in ['_obj', '_keep_wrapper']:
|
| 25 |
+
return getattr(self._obj, attr)
|
| 26 |
+
return getattr(self, attr)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Make sure the wrapped object conserves the callable property
|
| 30 |
+
class CallableObjectWrapper(CloudpickledObjectWrapper):
|
| 31 |
+
|
| 32 |
+
def __call__(self, *args, **kwargs):
|
| 33 |
+
return self._obj(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _wrap_non_picklable_objects(obj, keep_wrapper):
|
| 37 |
+
if callable(obj):
|
| 38 |
+
return CallableObjectWrapper(obj, keep_wrapper=keep_wrapper)
|
| 39 |
+
return CloudpickledObjectWrapper(obj, keep_wrapper=keep_wrapper)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _reconstruct_wrapper(_pickled_object, keep_wrapper):
|
| 43 |
+
obj = loads(_pickled_object)
|
| 44 |
+
return _wrap_non_picklable_objects(obj, keep_wrapper)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _wrap_objects_when_needed(obj):
|
| 48 |
+
# Function to introspect an object and decide if it should be wrapped or
|
| 49 |
+
# not.
|
| 50 |
+
need_wrap = "__main__" in getattr(obj, "__module__", "")
|
| 51 |
+
if isinstance(obj, partial):
|
| 52 |
+
return partial(
|
| 53 |
+
_wrap_objects_when_needed(obj.func),
|
| 54 |
+
*[_wrap_objects_when_needed(a) for a in obj.args],
|
| 55 |
+
**{k: _wrap_objects_when_needed(v)
|
| 56 |
+
for k, v in obj.keywords.items()}
|
| 57 |
+
)
|
| 58 |
+
if callable(obj):
|
| 59 |
+
# Need wrap if the object is a function defined in a local scope of
|
| 60 |
+
# another function.
|
| 61 |
+
func_code = getattr(obj, "__code__", "")
|
| 62 |
+
need_wrap |= getattr(func_code, "co_flags", 0) & inspect.CO_NESTED
|
| 63 |
+
|
| 64 |
+
# Need wrap if the obj is a lambda expression
|
| 65 |
+
func_name = getattr(obj, "__name__", "")
|
| 66 |
+
need_wrap |= "<lambda>" in func_name
|
| 67 |
+
|
| 68 |
+
if not need_wrap:
|
| 69 |
+
return obj
|
| 70 |
+
|
| 71 |
+
wrapped_obj = WRAP_CACHE.get(obj)
|
| 72 |
+
if wrapped_obj is None:
|
| 73 |
+
wrapped_obj = _wrap_non_picklable_objects(obj, keep_wrapper=False)
|
| 74 |
+
WRAP_CACHE[obj] = wrapped_obj
|
| 75 |
+
return wrapped_obj
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def wrap_non_picklable_objects(obj, keep_wrapper=True):
|
| 79 |
+
"""Wrapper for non-picklable object to use cloudpickle to serialize them.
|
| 80 |
+
|
| 81 |
+
Note that this wrapper tends to slow down the serialization process as it
|
| 82 |
+
is done with cloudpickle which is typically slower compared to pickle. The
|
| 83 |
+
proper way to solve serialization issues is to avoid defining functions and
|
| 84 |
+
objects in the main scripts and to implement __reduce__ functions for
|
| 85 |
+
complex classes.
|
| 86 |
+
"""
|
| 87 |
+
# If obj is a class, create a CloudpickledClassWrapper which instantiates
|
| 88 |
+
# the object internally and wrap it directly in a CloudpickledObjectWrapper
|
| 89 |
+
if inspect.isclass(obj):
|
| 90 |
+
class CloudpickledClassWrapper(CloudpickledObjectWrapper):
|
| 91 |
+
def __init__(self, *args, **kwargs):
|
| 92 |
+
self._obj = obj(*args, **kwargs)
|
| 93 |
+
self._keep_wrapper = keep_wrapper
|
| 94 |
+
|
| 95 |
+
CloudpickledClassWrapper.__name__ = obj.__name__
|
| 96 |
+
return CloudpickledClassWrapper
|
| 97 |
+
|
| 98 |
+
# If obj is an instance of a class, just wrap it in a regular
|
| 99 |
+
# CloudpickledObjectWrapper
|
| 100 |
+
return _wrap_non_picklable_objects(obj, keep_wrapper=keep_wrapper)
|