def test_invalid_option_command(self):
        """不正なコマンド引数を与えた時のエラー発生をテスト"""
        seq_input = [{
            'text-id': 'test-1',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }, {
            'text-id': 'test-2',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }, {
            'text-id': 'test-3',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }]

        with self.assertRaises(Exception):
            knp_job.main(seq_input_dict_document=seq_input,
                         is_normalize_text=True,
                         n_jobs=-1,
                         juman_options='-LL',
                         knp_options='-KK')

        with self.assertRaises(Exception):
            knp_job.main(seq_input_dict_document=seq_input,
                         is_normalize_text=True,
                         n_jobs=-1,
                         knp_options='-KK')
    def test_stress_test_pattern2(self):
        """大量の入力文を与えた場合の挙動をチェックする
        ### with normalization is False
        """
        seq_long_test_input = self.seq_docs * 20

        result_obj = knp_job.main(seq_input_dict_document=seq_long_test_input,
                                  is_normalize_text=False)
        self.assertTrue(
            len(result_obj.seq_document_obj) == len(seq_long_test_input))
    def test_input_document_with_args(self):
        """入力documentにargsが付属しているときの挙動をテスト"""
        seq_input_docs = copy.deepcopy(self.seq_docs)
        for doc in seq_input_docs:
            doc.update({"args": {"date": "2018/12/12"}})

        result_docs = knp_job.main(seq_input_dict_document=seq_input_docs,
                                   n_jobs=-1,
                                   is_normalize_text=True,
                                   is_split_text=True)
        for doc_obj in result_docs.seq_document_obj:
            assert doc_obj.document_args is not None
            assert isinstance(doc_obj.document_args, dict)
            assert "date" in doc_obj.document_args and doc_obj.document_args[
                "date"] == "2018/12/12"
    def test_exception_during_sentence(self):
        """KNPの解析結果文字列が例外を起こすときの処理"""
        seq_input = [{
            'text-id': 'test-1',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }, {
            'text-id': 'test-2',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }, {
            'text-id': 'test-3',
            'text': 'ベッキー♪#も、なんかもう世代交代じゃね?'
        }]

        result_obj = knp_job.main(seq_input_dict_document=seq_input,
                                  is_normalize_text=False,
                                  is_delete_working_db=True)
Example #5
0
parser.add_argument('--juman-server-host')
parser.add_argument('--juman-server-port')
parser.add_argument('--knp-server-host')
parser.add_argument('--knp-server-port')"""
args = parser.parse_args()

if not os.path.exists(args.path_input_json_path):
    raise Exception('There is no file at {}'.format(args.path_input_json_path))
else:
    if six.PY2:
        with codecs.open(args.path_input_json_path, 'r', 'utf-8') as f:
            seq_input_dict_document = json.loads(f.read())
    else:
        with open(args.path_input_json_path, 'r') as f:
            seq_input_dict_document = json.loads(f.read())

result_obj = knp_job.main(seq_input_dict_document=seq_input_dict_document,
                          n_jobs=args.n_jobs,
                          knp_command=args.knp_command,
                          juman_command=args.juman_command,
                          path_juman_rc=args.path_juman_rc,
                          process_mode=args.process_mode,
                          work_dir=args.working_dir,
                          file_name=args.file_name,
                          is_delete_working_db=args.is_delete_working_db,
                          is_normalize_text=args.is_normalize_text)

if six.PY2:
    print(json.dumps(result_obj.to_dict(), ensure_ascii=True))
else:
    print(json.dumps(result_obj.to_dict(), ensure_ascii=False))
 def test_subprocess_mode(self):
     result = knp_job.main(self.seq_docs,
                           is_normalize_text=True,
                           n_jobs=1,
                           process_mode='subprocess')
Example #7
0
def example_interface():
    """This functions shows you how to use interface function"""
    if six.PY2:
        input_document = [
            {
                u"text-id": u"input-1",
                u"text": "おじいさんは山に芝刈りへ、おばあさんは川に洗濯へ行きました。"
            },
            {
                u"text-id":
                u"input-2",
                u"text":
                u"東京 3日 ロイター] - 日銀は3日、急激な金利上昇を止めるため、特定の年限の国債買い入れを増やす「指値オペ」を実施した。トランプ米大統領による円安誘導批判を受け、日銀が長期金利を押し下げるようなオペは難しくなるとの思惑が浮上。長期金利は3日、一時、0.15%を超えて上昇した。日銀は、指し値オペの実行によってゼロ%に抑える政策に変化がないことを明確にし、圧力を意識した市場に「強い意思」を示した格好だ。"
            },
            {
                u"text-id":
                u"input-3",
                u"text":
                u"指値オペの実施は現在の金融政策「長短金利操作(イールドカーブ・コントロール、YCC)」を開始した2016年9月以来、2度目となる。"
            },
            {
                u"text-id":
                u"input-4",
                u"text":
                u"ドナルド・トランプ米大統領が有権者の心をつかんだ理由の一つは、その率直な物言いだ。ドルに関して言えば、米国の歴代財務長官が昔から繰り返してきた「強いドルは米国の国益にかなう」という妄言と決別するという新政権の意向は歓迎されよう。"
            },
        ]
    else:
        input_document = [
            {
                "text-id": "input-1",
                "text": "おじいさんは山に芝刈りへ、おばあさんは川に洗濯へ行きました。"
            },
            {
                "text-id":
                "input-2",
                "text":
                "東京 3日 ロイター] - 日銀は3日、急激な金利上昇を止めるため、特定の年限の国債買い入れを増やす「指値オペ」を実施した。トランプ米大統領による円安誘導批判を受け、日銀が長期金利を押し下げるようなオペは難しくなるとの思惑が浮上。長期金利は3日、一時、0.15%を超えて上昇した。日銀は、指し値オペの実行によってゼロ%に抑える政策に変化がないことを明確にし、圧力を意識した市場に「強い意思」を示した格好だ。"
            },
            {
                "text-id":
                "input-3",
                "text":
                "指値オペの実施は現在の金融政策「長短金利操作(イールドカーブ・コントロール、YCC)」を開始した2016年9月以来、2度目となる。"
            },
            {
                "text-id":
                "input-4",
                "text":
                "ドナルド・トランプ米大統領が有権者の心をつかんだ理由の一つは、その率直な物言いだ。ドルに関して言えば、米国の歴代財務長官が昔から繰り返してきた「強いドルは米国の国益にかなう」という妄言と決別するという新政権の意向は歓迎されよう。"
            },
        ]

    result_obj = knp_job.main(
        seq_input_dict_document=input_document,
        n_jobs=-1,
        is_normalize_text=True,
        is_get_processed_doc=True,
        is_split_text=True,
        juman_command=
        PATH_JUMAN_COMMAND,  # Note: You can set jumanpp also (if it's available in your system)
        knp_command=PATH_KNP_COMMAND,
        process_mode="pexpect")

    import json
    logger.info(msg="--- example of parsed result ---")
    print(json.dumps(result_obj.to_dict()[0], ensure_ascii=False))
    logger.info('---')
    """You call get associated with pyknp which is official python wrapper for KNP"""
    ### With pyknp
    try:
        import pyknp
    except:
        logger.error(msg="Failed to install pyknp. Skip this process.")
    else:
        from pyknp import KNP
        knp_obj = KNP()
        for knp_parsed_obj in result_obj.seq_document_obj:
            pyknp_parsed_result = knp_obj.result(
                input_str=knp_parsed_obj.parsed_result)
            bnst_surface = [
                "".join(mrph.midasi for mrph in bnst_obj.mrph_list())
                for bnst_obj in pyknp_parsed_result.bnst_list()
            ]
            print(bnst_surface)
Example #8
0
def performance_comparison():
    """This function shows you comparison of processing speed"""
    if six.PY2:
        input_document = [
            {
                u"text-id": u"input-1",
                u"text": "おじいさんは山に芝刈りへ、おばあさんは川に洗濯へ行きました。"
            },
            {
                u"text-id":
                u"input-2",
                u"text":
                u"東京 3日 ロイター] - 日銀は3日、急激な金利上昇を止めるため、特定の年限の国債買い入れを増やす「指値オペ」を実施した。トランプ米大統領による円安誘導批判を受け、日銀が長期金利を押し下げるようなオペは難しくなるとの思惑が浮上。長期金利は3日、一時、0.15%を超えて上昇した。日銀は、指し値オペの実行によってゼロ%に抑える政策に変化がないことを明確にし、圧力を意識した市場に「強い意思」を示した格好だ。"
            },
            {
                u"text-id":
                u"input-3",
                u"text":
                u"指値オペの実施は現在の金融政策「長短金利操作(イールドカーブ・コントロール、YCC)」を開始した2016年9月以来、2度目となる。"
            },
            {
                u"text-id":
                u"input-4",
                u"text":
                u"ドナルド・トランプ米大統領が有権者の心をつかんだ理由の一つは、その率直な物言いだ。ドルに関して言えば、米国の歴代財務長官が昔から繰り返してきた「強いドルは米国の国益にかなう」という妄言と決別するという新政権の意向は歓迎されよう。"
            },
        ] * 10
    else:
        input_document = [
            {
                "text-id": "input-1",
                "text": "おじいさんは山に芝刈りへ、おばあさんは川に洗濯へ行きました。"
            },
            {
                "text-id":
                "input-2",
                "text":
                "東京 3日 ロイター] - 日銀は3日、急激な金利上昇を止めるため、特定の年限の国債買い入れを増やす「指値オペ」を実施した。トランプ米大統領による円安誘導批判を受け、日銀が長期金利を押し下げるようなオペは難しくなるとの思惑が浮上。長期金利は3日、一時、0.15%を超えて上昇した。日銀は、指し値オペの実行によってゼロ%に抑える政策に変化がないことを明確にし、圧力を意識した市場に「強い意思」を示した格好だ。"
            },
            {
                "text-id":
                "input-3",
                "text":
                "指値オペの実施は現在の金融政策「長短金利操作(イールドカーブ・コントロール、YCC)」を開始した2016年9月以来、2度目となる。"
            },
            {
                "text-id":
                "input-4",
                "text":
                "ドナルド・トランプ米大統領が有権者の心をつかんだ理由の一つは、その率直な物言いだ。ドルに関して言えば、米国の歴代財務長官が昔から繰り返してきた「強いドルは米国の国益にかなう」という妄言と決別するという新政権の意向は歓迎されよう。"
            },
        ] * 10
    import time
    ## process_mode is pexpect(multi-thread, keep running processes) ##
    start = time.time()
    knp_job.main(seq_input_dict_document=input_document,
                 n_jobs=-1,
                 process_mode='pexpect',
                 is_normalize_text=True,
                 is_get_processed_doc=True,
                 juman_command=PATH_JUMAN_COMMAND,
                 knp_command=PATH_KNP_COMMAND)
    elapsed_time = time.time() - start
    print("pexpect mode, finished with :{0}".format(elapsed_time) + "[sec]")

    ## process_mode is everytime(multi-thread, launch processes everytime you call) ##
    start = time.time()
    knp_job.main(seq_input_dict_document=input_document,
                 n_jobs=-1,
                 process_mode='everytime',
                 is_normalize_text=True,
                 is_get_processed_doc=True,
                 juman_command=PATH_JUMAN_COMMAND,
                 knp_command=PATH_KNP_COMMAND)
    elapsed_time = time.time() - start
    print("everytime mode, finished with :{0}".format(elapsed_time) + "[sec]")

    ## pyknp which is official KNP wrapper ##
    ### With pyknp
    try:
        import pyknp
    except:
        logger.error(msg="Failed to install pyknp. Skip this process.")
    else:
        start = time.time()
        from pyknp import KNP
        knp_obj = KNP(command=PATH_KNP_COMMAND,
                      jumancommand=PATH_JUMAN_COMMAND,
                      jumanpp=True)
        for document_obj in input_document:
            knp_obj.knp(
                sentence=knp_job.func_normalize_text(document_obj['text']))
        elapsed_time = time.time() - start
        print("pyknp, finished with :{0}".format(elapsed_time) + "[sec]")