ツタンラーメンの忘備録

プログラミングや精神疾患、ラーメンについて書いていきます。たぶん。

python salesforce einstein 始める language 使い方

pythonsalesforceのeinstein apiを使おうとしたんだけど、絶妙に情報が少ない上に、絶妙にわかりづらい…。
Salesforce Einstein は、ビジネステクノロジーにおける AI です。 - セールスフォース・ドットコム

というわけでpythonでデータセットを持ち上げるサンプルファイルを公式に基づいて書いた。公式だと複数ファイルに分割していたが、その書き方がわかりづらいので…。

EINSTEIN_BASE_URL = 'https://api.einstein.ai/v2'
LANG_BASE_URL = EINSTEIN_BASE_URL + '/language'
LANG_DATASETS_URL = LANG_BASE_URL + '/datasets'
ACCESS_TOKEN = '***'

import requests
import json
from requests_toolbelt.multipart.encoder import MultipartEncoder

class DataSet():
    def __init__(self, access_token):
        self.access_token = access_token

    def create_intent_dataset(self, path):
        type = 'text-intent'
        return self._create_dataset(path, type)

    def _create_dataset(self, path, type):
        multipart_data = MultipartEncoder(
            fields={
                'path': path,
                'type': type
            }
        )
        headers = {'Authorization': 'Bearer ' + self.access_token,
                'Content-Type': multipart_data.content_type}
        res = requests.post(LANG_DATASETS_URL + '/upload',
                            headers=headers, data=multipart_data)
        json_response = json.loads(res.text)
        return json_response

def main():
    access_token = ACCESS_TOKEN
    dataset = DataSet(access_token=access_token)
    path = 'http://einstein.ai/text/weather.csv'
    response = dataset.create_intent_dataset(path)
    print(json.dumps(response, indent=4, sort_keys=True))

if __name__ == "__main__":
    main()