我正在寻找一种方法来使用 configparser
在我的预测程序代码中,我尝试了以下的代码片段
普通.cfg
[MODEL]
VERSION=config-true
setup.py
from setuptools import setup
REQUIRED_PACKAGES = [
'joblib==0.13.0'
]
setup(
name='test',
description='Custom prediction routine',
version=0.1,
install_requires=REQUIRED_PACKAGES,
scripts=['src/predictor.py', 'config/common.cfg']
)
预测器.py
import os
import joblib
import subprocess
import configparser
class CustomPredictor(object):
def __init__(self, model, config):
self._model = model
self._config = config
def predict(self, instances, **kwargs):
version_value = self._config.get('MODEL', 'VERSION', fallback='config-false')
print(f'version value = {version_value}', flush=True) # printing config-false
preprocessed_input = self._preprocess(instances)
score = self._model.predict(preprocessed_input)
print(f'predicted score {score}', flush=True)
return score.to_list()
@classmethod
def from_path(cls, model_dir):
config = configparser.RawConfigParser()
result = config.read('config/common.cfg')
print(f'read config result: {result}', flush=True) # empty
print(f'config sections: {config.sections()}', flush=True) # empty
subprocess.run(["ls", "-l"]) # don't see the config file or folder
model_path = os.path.join(model_dir, "model.joblib")
model = joblib.load(model_path)
return cls(model, config)
有什么建议可以告诉我,我做错了什么或者遗漏了什么?
我运行了这段代码,它打印出了预期的结果。
config = configparser.RawConfigParser()
result = config.read('common.cfg')
print(f'read config result: {result}', flush=True) # empty
print(f'config sections: {config.sections()}', flush=True) # empty
read config result: ['common.cfg']
config sections: ['MODEL']
当我复制你的代码并运行它时,它的输出显示为空列表,因为文件在同一个目录下,而不是在config目录下,但只要我纠正路径,它就会打印出预期的结果。
你有2个选项。
setup.py
并加 configparser
在那里。REQUIRED_PACKAGES = [
'joblib==0.13.0',
'configparser'
]
package-uris
当你创建模型时。从 虾米 我已经找到了tar.gz文件,请看一下。这个 例如,当我们传递一个PyTorch包时,在你的情况下,从pypi下载文件,并将其放入GCS Bucket中,从那里创建模型时定义它即可。gcloud beta ai-platform versions create {MODEL_VERSION} --model {MODEL_NAME} \
--origin=gs://{BUCKET_NAME}/{MODEL_DIR}/ \
--python-version=3.7 \
--runtime-version={RUNTIME_VERSION} \
--package-uris=gs://{BUCKET_NAME}/{PACKAGES_DIR}/text_classification-0.1.tar.gz,
gs://{BUCKET_NAME}/configparser-5.0.0.tar.gz \
--machine-type=mls1-c4-m4 \
--prediction-class=model.CustomModelPrediction
我发现了我的错误,在部署自定义预测程序的时候,ai平台将文件保存在... /tmp/custom_lib/bin/
并将执行路径保留为根目录。所以,在我的代码中,我把配置路径更新为这样的内容
config_file = pathlib.Path(__file__).parent.absolute() / 'common.cfg'
config.read(config_file)
这就解决了这个问题!
注意:我也相信我们需要将配置文件保存在 脚本 标签,因为当部署逻辑安装包时,setuptools会将脚本复制到ai-platform定义的PATH中,并使其可用。