Juliusの音声認識結果をソケット通信で受け取って表示・保存するPythonプログラム

前回の記事の関連として。
Juliusのdictation kitをダウンロードしておく。

以下のコマンドによりJuliusをmoduleモードで立ち上げる。

julius -n 5 -output 1 -rejectshort 800 -C main.jconf -C am-dnn.jconf -dnnconf julius.dnnconf -module &

ポート番号10500におけるTCP/IP経由でクライアントからの接続を待つ状態になる。一種のサーバーモードである。

クライアント側はJuliusと接続後、上記のポートを介して認識結果を受け取る。音声認識結果はログに保存される(example.log)。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import socket
import logging

# create logger
logger = logging.getLogger('simple_example')
logging.basicConfig(filename='example.log', level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

host = '127.0.0.1'   # IPアドレス
port = 10500         # Juliusとの通信用ポート番号

# Juliusにソケット通信で接続
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

data = ""
try:
    while True:
        # 音声認識結果のみをXMLで取得
        while (data.find("</RECOGOUT>\n.") == -1):
            soc = sock.recv(1024)
            data = data + soc.decode('utf-8')

        # 音声認識結果のXMLから単語部分のみを抜き出して連結
        recog_text = ""
        for line in data.split('\n'):
            index = line.find('WORD="')
            if index != -1:
                line = line[index+6:line.find('"', index+6)]
                recog_text = recog_text + line

        logging.info("認識結果: " + recog_text)
        print("認識結果: " + recog_text)
        data = ""

# Command + C などで強制終了した場合、JuliusサーバーをDIEコマンドにより落とす
# https://julius.osdn.jp/juliusbook/ja/desc_module.html
except KeyboardInterrupt:
    print('finished')
    sock.send("DIE".encode('utf-8'))
    sock.close()

後ほど記事は追記・更新予定。