LoginSignup
3
7

More than 1 year has passed since last update.

COTOHA API を (あらためて) 使ってみる

Posted at

NTT コミュニケーションズが提供している COTOHA API を使ってみたので記事にします。

COTOHA API

COTOHA API は NTT コミュニケーションズが提供している自然言語処理および音声処理用の API プラットフォームです。
利用にはアカウントの登録が必要であり, 無料プランの for Developers と有料プランの for Enterprise があります。
プランによって API の利用制限や辞書の登録可否などの差があるため注意してください。
筆者は for Developers プランでアカウントを登録しています。

提供されている API は以下の通り : 1

API 名 概要 for Developers for Enterprise
構文解析 日本語テキストの構造と意味を解析する。
固有表現抽出 人名や地名などの固有表現を抽出する。
固有名詞(企業名)補正 テキストから固有名詞 (企業名) を抽出・正規化する。 ×
照応解析 指示語を検知し, 指し示す対象を特定する。
キーワード抽出 文章からキーワードを抽出する。
類似度算出 2つの文章の類似性を数値化し出力する。
文タイプ判定 挨拶や同意, 約束などの発話行為のタイプと叙述文, 命令文, 質問などの文タイプを判定し出力する。
ユーザ属性推定(β) 文章からユーザの年代, 職業などの属性を推定する。
言い淀み除去(β) ユーザからの音声入力時に含まれる言い淀みを除去する。
音声認識誤り検知(β) 音声認識処理後のテキストに対して, 認識ミスの恐れがある単語を検知・抽出する。
感情分析 文章作成時の書き手のネガポジを判定すると同時に, 文章に含まれる「喜ぶ」や「驚く」といった特定の感情も認識する。
音声認識 ユーザからの音声入力をテキスト化する。 ×
音声合成 テキストから音声を人工的に生成する。 ×
要約 日本語・英語で記述された文章を要約する。 ×
テキスト分類 テキストを予め学習したクラスに分類する。 ×

COTOHA API を Python で利用する

for Developers プランに対する COTOHA API Client クラスを Python で作成しました。2
おおよその雛形は中の人が書いたこちらの記事を引用しています。
若干修正が必要だった箇所に手を加えたり, リファクタリングしたり, この記事以降に追加された機能も使用できるようにしました。
イニシャライザに渡す情報はマイページに表示されているものをそのまま指定してください。

cotoha_api_client.py
cotoha_api_client.py
import urllib.request
import json

class CotohaAPIClient:
    """
    COTOHA API クライアントクラス
    """
    def __init__(self, client_id, client_secret, developer_api_base_url, access_token_publish_url):
        """
        イニシャライザ

        Parameters
        ----------
        client_id : str
            Client ID
        client_secret : str
            Developer Client Secret
        developer_api_base_url : str
            Developer API Base URL
        access_token_publish_url : str
            Access Token Publish URL
        """
        self.client_id = client_id
        self.client_secret = client_secret
        self.developer_api_base_url = developer_api_base_url
        self.access_token_publish_url = access_token_publish_url
        self.get_access_token()


    def get_access_token(self):
        """
        Access Token を取得し設定する
        """
        # アクセストークン取得 API URL 指定
        url = self.access_token_publish_url
        # ヘッダ指定
        headers={
            'Content-Type' : 'application/json;charset=UTF-8'
        }
        # リクエストボディ指定
        data = {
            'grantType' : 'client_credentials',
            'clientId' : self.client_id,
            'clientSecret' : self.client_secret
        }
        # リクエストボディ指定をJSONにエンコード
        data = json.dumps(data).encode()

        # リクエスト生成
        req = urllib.request.Request(url, data, headers)
        # リクエストを送信し、レスポンスを受信
        res = urllib.request.urlopen(req)

        # レスポンスボディ取得
        res_body = res.read()
        # レスポンスボディをJSONからデコード
        res_body = json.loads(res_body)
        # レスポンスボディからアクセストークンを取得
        self.access_token = res_body['access_token']


    def get_response(self, url, data, headers) :
        """
        API を呼び出すテンプレートの private メソッド

        Parameters
        ----------
        url : url
            エンドポイント
        data : dict
            リクエストボディ
        headers : dict
            リクエストヘッダ

        Returns
        -------
        res_body : dict
            レスポンスボディ
        """        
        # リクエストボディ指定をJSONにエンコード
        data = json.dumps(data).encode()

        # リクエスト生成
        req = urllib.request.Request(url, data, headers)

        # リクエストを送信し、レスポンスを受信
        try:
            res = urllib.request.urlopen(req)
        # リクエストでエラーが発生した場合の処理
        except urllib.request.HTTPError as e:
            # ステータスコードが401 Unauthorizedならアクセストークンを取得し直して再リクエスト
            if e.code == 401:
                print ('get access token')
                self.get_access_token()
                headers['Authorization'] = 'Bearer ' + self.access_token
                req = urllib.request.Request(url, data, headers)
                res = urllib.request.urlopen(req)
            # 401以外のエラーなら原因を表示
            else:
                raise Exception(e.reason)

        # レスポンスボディ取得
        res_body = res.read()
        # レスポンスボディをJSONからデコード
        res_body = json.loads(res_body)

        return res_body



    def parse(self, sentence, type='default'):
        """
        構文解析 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#parsing)

        Parameters
        ----------
        sentence : str
            構文解析対象の文字列
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定

        Returns
        -------
        result : dict
            構文解析結果
        """
        # 構文解析API URL指定
        url = self.developer_api_base_url + 'nlp/v1/parse'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'sentence' : sentence,
            'type' : type
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def ne(self, sentence, type='default'):
        """
        固有表現抽出 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#entity)

        Parameters
        ----------
        sentence : str
            固有表現抽出対象の文字列
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定

        Returns
        -------
        result : dict
            固有表現抽出結果
        """
        # 固有表現抽出API URL指定
        url = self.developer_api_base_url + 'nlp/v1/ne'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'sentence' : sentence,
            'type' : type
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def coreference(self, document, type='default', do_segment=False):
        """
        照応解析 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#correspond)

        Parameters
        ----------
        document : Union[str, list[str]]
            照応解析対象の文字列または文字列のリスト
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定
        do_segment : bool
            文区切りを実施するか否かを指定 (document が list のときは無効)

        Returns
        -------
        result : dict
            照応解析結果
        """
        # 照応解析API URL指定
        url = self.developer_api_base_url + 'nlp/v1/coreference'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'document' : document,
            'type' : type,
            'do_segment' : do_segment
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def keyword(self, document, type='default', do_segment=False, max_keyword_num=5) :
        """
        キーワード抽出 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#keyword)

        Parameters
        ----------
        document : Union[str, list[str]]
            キーワード抽出対象の文字列または文字列のリスト
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定
        do_segment : bool
            文区切りを実施するか否かを指定 (document が list のときは無効)
        max_keyword_num : int
            抽出するキーワードの上限個数

        Returns
        -------
        result : dict
            キーワード抽出結果
        """
        # キーワード抽出API URL指定
        url = self.developer_api_base_url + 'nlp/v1/keyword'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'document' : document,
            'type' : type,
            'do_segment' : do_segment,
            'max_keyword_num' : max_keyword_num,
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def similarity(self, s1, s2, type='default'):
        """
        類似度算出 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#similarity)

        Parameters
        ----------
        s1 : str
            類似度計算対象の文字列1
        s2 : str
            類似度計算対象の文字列2
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定

        Returns
        -------
        result : dict
            類似度算出結果
        """
        # 類似度算出API URL指定
        url = self.developer_api_base_url + 'nlp/v1/similarity'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            's1' : s1,
            's2' : s2,
            'type' : type,
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def sentence_type(self, sentence, type='default'):
        """
        文タイプ判定 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#sentence)

        Parameters
        ----------
        sentence : str
            文タイプ判定対象の文字列
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定

        Returns
        -------
        result : dict
            文タイプ判定結果
        """
        # 文タイプ判定API URL指定
        url = self.developer_api_base_url + 'nlp/v1/sentence_type'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'sentence' : sentence,
            'type' : type,
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def user_attribute(self, document, type='default', do_segment=False):
        """
        ユーザ属性推定 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#user)

        Parameters
        ----------
        document : Union[str, list[str]]
            キーワード抽出対象の文字列または文字列のリスト
        type : str
            通常文なら 'default', SNS などの崩れた文なら 'kuzure' を指定
        do_segment : bool
            文区切りを実施するか否かを指定 (document が list のときは無効)

        Returns
        -------
        result : dict
            ユーザ属性推定結果
        """
        # ユーザ属性推定API URL指定
        url = self.developer_api_base_url + 'nlp/beta/user_attribute'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'document' : document,
            'type' : type,
            'do_segment' : do_segment
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def remove_filler(self, text, do_segment=False) : 
        """
        言い淀み除去 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#filler)

        Parameters
        ----------
        text : str
            言い淀み除去対象の文字列
        do_segment : bool
            文区切りを実施するか否かを指定 (document が list のときは無効)

        Returns
        -------
        result : dict
            言い淀み除去結果
        """
        # 言い淀み除去 API URL指定
        url = self.developer_api_base_url + 'nlp/beta/remove_filler'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'text' : text,
            'do_segment' : do_segment
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def detect_misrecognition(self, sentence) :
        """
        音声認識誤り検知 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#detect)

        Parameters
        ----------
        sentence : str
            音声認識誤り検知対象の文字列

        Returns
        -------
        result : dict
            音声認識誤り検知結果
        """
        # 音声認識誤り検知 API URL指定
        url = self.developer_api_base_url + 'nlp/beta/detect_misrecognition'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'sentence' : sentence
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result


    def sentiment(self, sentence) :
        """
        感情分析 API を呼び出す (https://api.ce-cotoha.com/contents/reference/apireference.html#sentiment)

        Parameters
        ----------
        sentence : str
            感情分析対象の文字列

        Returns
        -------
        result : dict
            感情分析結果
        """
        # 感情分析 API URL指定
        url = self.developer_api_base_url + 'nlp/v1/sentiment'
        # ヘッダ指定
        headers={
            'Authorization' : 'Bearer ' + self.access_token,
            'Content-Type' : 'application/json;charset=UTF-8',
        }
        # リクエストボディ指定
        data = {
            'sentence' : sentence
        }

        # API を呼び出して結果取得
        result = self.get_response(url, data, headers)

        return result

以下, 簡単な使用例を残します。
設定ファイルとして以下を想定します (各情報はご自身のものを入力してください)。

config.ini
[COTOHA API]
Developer API Base URL: xxxxxxxxxxxxxxxxxxxxxx
Developer Client id: xxxxxxxxxxxxxxxxxxxxxx
Developer Client secret: xxxxxxxxxxxxxxxxxxxxxx
Access Token Publish URL: xxxxxxxxxxxxxxxxxxxxxx

構文解析

sample_parse.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 構文解析対象文
    sentence = '数学が好き。'

    # 構文解析API実行
    result = cotoha_api_client.parse(sentence)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": [
        {
            "chunk_info": {
                "id": 0,
                "head": 1,
                "dep": "D",
                "chunk_head": 0,
                "chunk_func": 1,
                "links": []
            },
            "tokens": [
                {
                    "id": 0,
                    "form": "数学",
                    "kana": "スウガク",
                    "lemma": "数学",
                    "pos": "名詞",
                    "features": [],
                    "dependency_labels": [
                        {
                            "token_id": 1,
                            "label": "case"
                        }
                    ],
                    "attributes": {}
                },
                {
                    "id": 1,
                    "form": "が",
                    "kana": "ガ",
                    "lemma": "が",
                    "pos": "格助詞",
                    "features": [
                        "連用"
                    ],
                    "attributes": {}
                }
            ]
        },
        {
            "chunk_info": {
                "id": 1,
                "head": -1,
                "dep": "O",
                "chunk_head": 0,
                "chunk_func": 0,
                "links": [
                    {
                        "link": 0,
                        "label": "agent"
                    }
                ],
                "predicate": []
            },
            "tokens": [
                {
                    "id": 2,
                    "form": "好き",
                    "kana": "スキ",
                    "lemma": "好き",
                    "pos": "名詞",
                    "features": [
                        "形容"
                    ],
                    "dependency_labels": [
                        {
                            "token_id": 0,
                            "label": "nsubj"
                        },
                        {
                            "token_id": 3,
                            "label": "punct"
                        }
                    ],
                    "attributes": {}
                },
                {
                    "id": 3,
                    "form": "。",
                    "kana": "",
                    "lemma": "。",
                    "pos": "句点",
                    "features": [],
                    "attributes": {}
                }
            ]
        }
    ],
    "status": 0,
    "message": ""
}

固有表現抽出

sample_ne.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 固有表現抽出対象文
    sentence = '織田信長は戦国時代の武将。'

    # 固有表現抽出 API 実行
    result = cotoha_api_client.ne(sentence)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": [
        {
            "begin_pos": 0,
            "end_pos": 4,
            "form": "織田信長",
            "std_form": "織田信長",
            "class": "PSN",
            "extended_class": "",
            "source": "basic"
        },
        {
            "begin_pos": 5,
            "end_pos": 9,
            "form": "戦国時代",
            "std_form": "戦国時代",
            "class": "DAT",
            "extended_class": "",
            "source": "basic"
        },
        {
            "begin_pos": 10,
            "end_pos": 12,
            "form": "武将",
            "std_form": "武将",
            "class": "ART",
            "extended_class": "Position_Vocation",
            "source": "basic"
        }
    ],
    "status": 0,
    "message": ""
}

照応解析

sample_coreference.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 照応解析対象文
    document = '工藤新一を知っていますか?彼は日本が世界に誇る名探偵なのです。'

    # 照応解析 API 実行
    result = cotoha_api_client.coreference(document, do_segment=True)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "coreference": [
            {
                "representative_id": 0,
                "referents": [
                    {
                        "referent_id": 0,
                        "sentence_id": 0,
                        "token_id_from": 0,
                        "token_id_to": 0,
                        "form": "工藤新一"
                    },
                    {
                        "referent_id": 1,
                        "sentence_id": 1,
                        "token_id_from": 0,
                        "token_id_to": 0,
                        "form": "彼"
                    }
                ]
            }
        ],
        "tokens": [
            [
                "工藤新一",
                "を",
                "知",
                "っ",
                "て",
                "い",
                "ます",
                "か",
                "?"
            ],
            [
                "彼",
                "は",
                "日本",
                "が",
                "世界",
                "に",
                "誇",
                "る",
                "名",
                "探偵",
                "な",
                "の",
                "です",
                "。"
            ]
        ]
    },
    "status": 0,
    "message": "OK"
}

キーワード抽出

sample_keyword.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # キーワード抽出対象文
    document = '主人公のエレンが巨人の駆逐に挑む物語である。'

    # キーワード抽出 API 実行
    result = cotoha_api_client.keyword(document)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": [
        {
            "form": "エレン",
            "score": 21.2496
        },
        {
            "form": "物語",
            "score": 16.25554
        },
        {
            "form": "駆逐",
            "score": 9.59218
        },
        {
            "form": "巨人",
            "score": 8.97854
        },
        {
            "form": "主人公",
            "score": 7.86314
        }
    ],
    "status": 0,
    "message": ""
}

類似度算出

sample_similarity.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 類似度算出対象文1
    s1 = 'アニメは日本の文化である。'
    # 類似度算出対象文2
    s2 = '日本は海外からアニメーションの国として知られている。'

    # 類似度算出 API 実行
    result = cotoha_api_client.similarity(s1,s2)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "score": 0.96419173
    },
    "status": 0,
    "message": "OK"
}

文タイプ判定

sample_sentence_type.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 文タイプ判定対象文
    sentence = 'さっさと工数の入力をしてちょうだい。'

    # 文タイプ判定 API 実行
    result = cotoha_api_client.sentence_type(sentence)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "modality": "imperative",
        "dialog_act": [
            "directive"
        ]
    },
    "status": 0,
    "message": ""
}

ユーザ属性推定 (β)

sample_user_attribute.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # ユーザ属性推定対象文リスト
    document = ['勤続20年のベテラン。', '休日はゴルフをされる。', '奥様が投資に興味を持たれているとのこと。']

    # ユーザ属性推定 API 実行
    result = cotoha_api_client.user_attribute(document)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "age": "40-49歳",
        "civilstatus": "既婚",
        "habit": [],
        "hobby": [
            "CAMERA",
            "COOKING",
            "INTERNET",
            "MOVIE"
        ],
        "location": "関東",
        "moving": [
            "RAILWAY"
        ],
        "occupation": "会社員"
    },
    "status": 0,
    "message": "OK"
}

言い淀み除去 (β)

sample_remove_filler.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 言い淀み除去対象文
    text = 'えーその通りですね、えっと。'

    # 言い淀み除去 API 実行
    result = cotoha_api_client.remove_filler(text, do_segment=True)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": [
        {
            "fillers": [
                {
                    "begin_pos": 0,
                    "end_pos": 3,
                    "form": "えー、"
                },
                {
                    "begin_pos": 12,
                    "end_pos": 15,
                    "form": "えっと"
                }
            ],
            "normalized_sentence": "えー、その通りですね、、えっと、。",
            "fixed_sentence": "その通りですね、。"
        }
    ],
    "status": 0,
    "message": "OK"
}

音声認識誤り検知 (β)

sample_detect_misrecognition.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 音声認識誤り検知対象文
    sentence = '太陽は耕世です。'

    # 音声認識誤り検知 API 実行
    result = cotoha_api_client.detect_misrecognition(sentence)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "score": 0.9984314966326983,
        "candidates": [
            {
                "begin_pos": 3,
                "end_pos": 5,
                "form": "耕世",
                "detect_score": 0.9984314966326983,
                "correction": [
                    {
                        "form": "恒星",
                        "correct_score": 0.7583672550744078
                    },
                    {
                        "form": "こせ",
                        "correct_score": 0.7520636658676886
                    },
                    {
                        "form": "光",
                        "correct_score": 0.7520306689382251
                    },
                    {
                        "form": "光線",
                        "correct_score": 0.7395568642427626
                    },
                    {
                        "form": "頭部",
                        "correct_score": 0.7253305562918556
                    }
                ]
            }
        ]
    },
    "status": 0,
    "message": "OK"
}

感情分析

sample_sentiment.py
import os
import configparser
from cotoha_api_client import CotohaAPIClient

if __name__ == '__main__':
    # ソースファイルの場所取得
    APP_ROOT = os.path.dirname(os.path.abspath( __file__)) + "/"

    # 設定値取得
    config = configparser.ConfigParser()
    config.read(APP_ROOT + "config.ini")
    CLIENT_ID = config.get("COTOHA API", "Developer Client id")
    CLIENT_SECRET = config.get("COTOHA API", "Developer Client secret")
    DEVELOPER_API_BASE_URL = config.get("COTOHA API", "Developer API Base URL")
    ACCESS_TOKEN_PUBLISH_URL = config.get("COTOHA API", "Access Token Publish URL")

    # COTOHA APIインスタンス生成
    cotoha_api_client = CotohaAPIClient(CLIENT_ID, CLIENT_SECRET, DEVELOPER_API_BASE_URL, ACCESS_TOKEN_PUBLISH_URL)

    # 感情分析対象文
    sentence = '見た目は悪いけど味は抜群に良い。'

    # 感情分析 API 実行
    result = cotoha_api_client.sentiment(sentence)

    # 結果表示
    print(result)

実行結果
出力結果
{
    "result": {
        "sentiment": "Negative",
        "score": 0.5286873779011386,
        "emotional_phrase": [
            {
                "form": "抜群に良い",
                "emotion": "P"
            },
            {
                "form": "悪い",
                "emotion": "N"
            }
        ]
    },
    "status": 0,
    "message": "OK"
}


  1. 詳細は API リファレンスを参照してください。 

  2. 非公式のライブラリが公開されていますが本記事では使用しませんでした。 

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7