import subprocess import json import importlib.resources import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from utils.logger import setup_logger from utils.json import get_file_path_from_config # --- ロギングの設定 --- log = setup_logger(__name__) def main(): """ SudachiPyのユーザー辞書をビルドするPythonスクリプト。 Reference: https://github.com/WorksApplications/SudachiPy/blob/develop/docs/tutorial.md """ log.info("SudachiPyのユーザー辞書をビルドします。") # 入力用のユーザー辞書CSVファイルのパス user_dict_path = get_file_path_from_config( "sudachi.user_dict", "resources/user_dict.csv" ) # 出力のユーザー辞書のパス output_path = get_file_path_from_config( "sudachi.user_dict_generated", "data/generated/user.dic" ) # sudachi.jsonから辞書の種類を取得 sudachi_config_path = get_file_path_from_config( "sudachi.sudachi_config", "scripts/sudachi.json" ) with open(sudachi_config_path, "r") as f: try: sudachi_dict = json.load(f) sudachi_dict_size = sudachi_dict.get("systemDict", "full") sudachi_dict_name = f"sudachidict_{sudachi_dict_size}" except FileNotFoundError: log.error(f"sudachi.jsonが見つかりません: {sudachi_config_path}") sys.exit(1) # sudachidict_パッケージ内のシステム辞書のパスを取得 try: system_dict_ref = importlib.resources.files(sudachi_dict_name).joinpath( "resources", "system.dic" ) log.info(f"システム辞書のパス: {system_dict_ref}") except ModuleNotFoundError: log.error(f"{sudachi_dict_name}パッケージが見つかりません。") log.error(f"`pip install {sudachi_dict_name}`を試してください。") sys.exit(1) except Exception as e: log.error(f"予期しないエラーが発生しました: {e}") sys.exit(1) # 出力ディレクトリが存在しない場合は作成 os.makedirs(os.path.dirname(output_path), exist_ok=True) with importlib.resources.as_file(system_dict_ref) as system_dict_path: command = [ "sudachipy", "ubuild", "-o", output_path, # 出力ファイルのパス "-s", str(system_dict_path), # システム辞書のパス user_dict_path, ] log.info("辞書をビルドします...") log.info(f"コマンド: {' '.join(command)}") try: # コマンドを実行 result = subprocess.run( command, check=True, capture_output=True, text=True, encoding="utf-8", ) log.info("ビルドが正常に完了しました。") log.info(f"出力先: {output_path}") if result.stdout: log.info(f"--- SudachiPyからのメッセージ ---\n{result.stdout}") except FileNotFoundError: log.error("sudachipyコマンドが見つかりません。") log.error("SudachiPyがインストールされていることを確認してください。") sys.exit(1) except subprocess.CalledProcessError as e: log.error("辞書のビルド中にエラーが発生しました。") log.error(f"エラーコード: {e.returncode}") if e.stderr: log.error(f"--- 標準エラー出力 ---\n{e.stderr}") sys.exit(1) except Exception as e: log.error(f"予期しないエラーが発生しました: {e}") sys.exit(1) sys.exit(0) if __name__ == "__main__": main()