npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

watson-nlc-qa

v1.0.2

Published

Watson NLC Q&A Model

Downloads

49

Readme

watson-nlc-qa

NPM

Build Status codecov

はじめに

Q&A Chatbot を作成するためのモデルです。

コンセプト

fig-1

使い方

const QaModel = require('watson-nlc-qa');
const qa = new QaModel(cloudantCreds, 'answer', nlcCreds);
qa.ask('こんにちは', (answer) => {
    console.log('answer:', answer);
});

システム要件

次のサービスを使用してください。

インストール

$ npm install watson-nlc-qa

参考情報

  • このモデルを使用した Q&A Chatbot をこちらに開発しました。
    • https://github.com/ippei0605/qa-chatbot

目次


APIs

QaModel(cloudantCreds, dbname, nlcCreds, [classifierid])

Q&A モデルを生成します。

const QaModel = require('watson-nlc-qa');
const qa = new QaModel(cloudantCreds, 'answer', nlcCreds);

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------ | -------------------------------------------------- | |cloudantCreds |Yes |object |Cloudant NoSQL DB のサービス資格情報 | |dbName |Yes |string |データベース名 | |nlcCreds |Yes |object |Natural Language Classifier のサービス資格情報 | |classifierId |No |string |Classifier ID。未設定または空文字の場合は使用可能な最新の Classifier を選択します。|

  • cloudantCreds {object} Cloudant NoSQL DB のサービス資格情報

    {
        "username": "{username}",
        "password": "{password}",
        "host": "{host}",
        "port": 443,
        "url": "{url}"
    }
  • nlcCreds {object} Natural Language Classifier のサービス資格情報

    {
        "url": "{url}",
        "username": "{username}",
        "password": "{password}"
    }

目次に戻る


ask(text, callback)

テキスト分類で回答 answer を取得します。

qa.ask('こんにちは', (answer) => {
    console.log(answer);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | --------------------------------------------------- | |text |Yes |string |質問 | |callback |Yes |function |取得した回答 answer を引数にコールバックする。 |

  • 回答 answer
{
  "class_name": "{string} クラス名",
  "message": "{string} メッセージ",
  "confidence": "{number} 自信度"
}

目次に戻る


askAnswers(text, count, callback)

テキスト分類で回答配列 [answer] を取得します。取得する回答件数は1から10までの整数で指定できます。回答件数が1件の場合は回答 (配列ではない) を取得します。

qa.askAnswers('こんにちは', 10, (answers) => {
    console.log(answers);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | --------------------------------------------------- | |text |Yes |string |質問 | |count |Yes |number |取得する回答件数 (1〜10) | |callback |Yes |function |取得した回答 answer を引数にコールバックする。 |

  • 回答 answer
{
  "class_name": "{string} クラス名",
  "message": "{string} メッセージ",
  "confidence": "{number} 自信度"
}

目次に戻る


askClassName(text, callback)

クラス名により回答 answer を取得します。

qa.askClassName('general_hello', (answer) => {
    console.log(answer);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | --------------------------------------------------- | |text |Yes |string |クラス名 | |callback |Yes |function |取得した回答 answer を引数にコールバックします。 |

目次に戻る


getAppSettings(callback)

アプリケーション設定 value を取得します。

qa.getAppSettings((value) => {
    console.log(value);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | ----------------------------------------------------------- | |callback |Yes |function |取得したアプリケーション設定 value を引数にコールバックします。 |

  • アプリケーション設定 value
{
  "name": "名前"
}

ID「app_settings」でデータベースに登録した文書をそのまま取得できます。

目次に戻る


createDatabase([callback])

データベースを作成します。

qa.createDatabase((result)=>{
    console.log(result);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | ----------------------------------------------------------- | |callback |No |function |取得した結果 result を引数にコールバックします。 |

目次に戻る


insertDesignDocument([mapFunction], [callback])

データベースに設計文書を登録します。

qa.insertDesignDocument('', (result) => {
    console.log(result);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | ----------------------------------------------------------- | |mapFunction |No |string |マップファンクション。未設定または空文字の場合はデフォルトのマップファンクションで設計文書を作成します。| |callback |No |function |取得した結果 result を引数にコールバックします。 |

  • 設計文書

    {
        "_id": "_design/answers",
        "views": {
            "list": {
                "map": "{マップファンクション}"
            }
        }
    }
  • デフォルトのマップファンクション

    const MAP_FUNCTION = `function (doc) {
        if (doc._id !== 'app_settings') {
            var row = {
                "_id": doc._id,
                "_rev": doc._rev,
                "message": doc.message,
                "questions": doc.questions
            };
            emit(doc._id, row);
        }
    }`;

目次に戻る


insertDocuments(data, [callback])

データを登録します。

qa.insertDocuments(data, (result) => {
    console.log(result);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | ----------------------------------------------------------- | |data |Yes |object |データ | |callback |No |function |取得した結果 result を引数にコールバックします。 |

  • データ

    {
      "docs": [
        {
          "_id": "app_settings",
          "name": "Watson Diet Trainer"
        },
        {
          "_id": "general_hello",
          "message": "こんにちは。私はワトソンです。",
          "questions": [
            "こんばんは。",
            "はじめまして。",
            "はじめまして。こんにちは。 ",
            "こんにちは。",
            "よろしくお願いします。",
            "おはようございます。"
          ]
        }
      ]
    }

目次に戻る


train(file, metadata, [mode], [callback])

Classifier を作成します。

const trainingFile = fs.createReadStream(__dirname + '/classifier.csv');
const metadata = {
    "language": "ja",
    "name": "My Classifier"
};
qa.train(trainingFile, metadata, false, (result) => {
    console.log(result);
});

|パラメータ |必須 |型 |説明 | | ------------ | --- | ------- | ----------------------------------------------------------- | |file |Yes |file |トレーニング CSV ファイル | |metadata |Yes |object |トレーニングメタデータ | |mode |No |boolean |true: Classifier を作成します / false: Classifier が一つ以上ある場合は作成しません。| |callback |No |function |取得した結果 result を引数にコールバックします。 |

  • トレーニング CSV ファイル

    "こんにちは。","general_hello"
    "間違っています。","general_sorry"
    "ありがとう。","general_thanks"
    "自己紹介して。","general_whoareyou"
  • トレーニングメタデータ

    {
        "language": "ja",
        "name": "{Classifier 名}"
    }

目次に戻る


Tips

データを初期登録する

データベース作成、設計文書登録、データ登録は個別にも実行できますが、次のようにすることでデータベース作成後に設計文書登録とデータ登録を実行できます。

// データベースを作成する。
qa.createDatabase(() => {
    // 設計文書を作成する。
    qa.insertDesignDocument();
    // データを登録する。
    const data = fs.readFileSync(__dirname + '/' + CONTENT_FILENAME).toString();
    qa.insertDocuments(JSON.parse(data));
});

目次に戻る


取得した回答を変更する

ask メソッドで取得した回答を条件によって変更したい場合は、コールバックに処理を記述することで実現できます。 以下は現在時刻 now によりあいさつを「おはようございます」、「こんにちは」、「こんばんは」、「お疲れ様です」に変更する例です。

// Q&A モデルを作成する。
const qa = new QaModel(context.cloudantCreds, context.DB_NAME, context.nlcCreds);
// こんにちはを変換する。
const replaceHello = (text, replaceText) => {
    return text.replace(/こんにちは/g, replaceText);
};
// 条件により回答を確定する。
const modify = (answer, now) => {
    switch (answer.class_name) {
        case 'general_hello':
            let regexp = /(\d+)年(\d+)月(\d+)日 (\d+)時(\d+)分(\d+)秒/;
            let hour = parseInt(regexp.exec(now)[4], 10);
            if (hour >= 17) {
                answer.message = replaceHello(value.message, 'こんばんは');
            } else if (hour < 11 && hour >= 5) {
                answer.message = replaceHello(value.message, 'おはようございます');
            } else if (hour < 5) {
                answer.message = replaceHello(value.message, 'お疲れ様です');
            }
            break;
        default:
            break;
    }
    return answer;
};
// 質問する。
const text = 'こんにちは';
qa.ask(text, (answer) => {
    const now = '2017年7月29日 14時26分44秒';
    console.log(modify(answer, now));
});

目次に戻る


Natural Language Classifier を多段構成にする

次のように、連想配列に必要なQ&Aモデルを生成してください。この例は、classification で切り分け、general または diet に問合せる構成です。

const qa = {
    "classification": new QaModel(cloudantCreds, 'classification', nlcCreds, '{classification の Classifier ID}'),
    "general": new QaModel(cloudantCreds, 'general', nlcCreds, '{general の Classifier ID}'),
    "diet": new QaModel(cloudantCreds, 'diet', nlcCreds, '{diet の Classifier ID}')
};
const text = 'こんにちは';
qa["classification"].ask(text, (classification) => {
    qa[classification.message].ask(text, (answer) => {
        console.log(answer);
    })
});

classification の回答 answer は質問により general または diet が返るようにデータ登録とトレーニングをしてください。

  • データの例

        {
          "docs": [
            {
              "_id": "general",
              "message": "general"
            },
            {
              "_id": "diet",
              "message": "diet"
            }
          ]
        }
  • トレーニングデータ (csv) の例

    "こんにちは。","general"
    "ありがとう。","general"
    "全身運動でダイエットしたい。","diet"
    "小顔になりたい。","diet"

目次に戻る