tkasr_common.py ダウンロード/コピー

tkasr_common.py をダウンロード

tkasr_common.py
tkasr_common.py
  1"""
  2tkasrプロジェクトで共有されるデータ型やファイル/音声処理のヘルパー関数を提供します。
  3
  4音声認識(ASR)関連のアプリケーションで共通して利用されるユーティリティ機能を集約しています。
  5ファイル操作、FFmpeg/FFprobeの利用、ASR結果のデータ構造などが含まれます。
  6
  7:doc:`tkasr_usage`
  8"""
  9from __future__ import annotations
 10
 11import json
 12import subprocess
 13from dataclasses import dataclass, field
 14from pathlib import Path
 15from typing import Any, Optional
 16
 17
 18class OptionalDependencyError(RuntimeError):
 19    """
 20    オプションのバックエンドまたは機能がインストールされていない場合に発生するエラー。
 21    """
 22
 23
 24@dataclass
 25class Segment:
 26    """
 27    音声認識結果の1セグメントを表すデータクラス。
 28
 29    :param start: セグメントの開始時間(秒)。
 30    :param end: セグメントの終了時間(秒)。
 31    :param text: セグメントのテキスト。
 32    """
 33    start: Optional[float]
 34    end: Optional[float]
 35    text: str
 36
 37
 38@dataclass
 39class ASRResult:
 40    """
 41    音声認識全体の単一結果を表すデータクラス。
 42
 43    :param text: 音声認識された完全なテキスト。
 44    :param segments: テキストを時間情報付きのセグメントに分割したリスト。
 45    :param language: 認識された言語コード(例: "en", "ja")。
 46    :param metadata: その他のメタデータ。
 47    """
 48    text: str
 49    segments: list[Segment] = field(default_factory=list)
 50    language: Optional[str] = None
 51    metadata: dict[str, Any] = field(default_factory=dict)
 52
 53
 54def run_command(command: list[str]) -> str:
 55    """
 56    外部コマンドを実行し、その標準出力を取得します。
 57
 58    `subprocess.run` を使用してコマンドを実行し、エラーが発生した場合は適切な `RuntimeError` を発生させます。
 59    コマンドが見つからない場合や、コマンドがエラー終了した場合に詳細なエラーメッセージを提供します。
 60
 61    :param command: 実行するコマンドとその引数を表す文字列のリスト。
 62    :type command: list[str]
 63    :returns: コマンドの標準出力。
 64    :rtype: str
 65    :raises RuntimeError: コマンドが見つからない場合、またはコマンドがエラー終了した場合。
 66    """
 67    try:
 68        result = subprocess.run(command, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 69    except FileNotFoundError as exc:
 70        raise RuntimeError(f"'{command[0]}' が見つかりません。FFmpeg を PATH に追加するか --ffmpeg-dir を指定してください。") from exc
 71    except subprocess.CalledProcessError as exc:
 72        raise RuntimeError(exc.stderr.strip() or exc.stdout.strip() or f"コマンドが失敗しました: {command}") from exc
 73    return result.stdout.strip()
 74
 75
 76def ffmpeg_commands(directory: Optional[Path]) -> tuple[str, str]:
 77    """
 78    FFmpegとFFprobeの実行可能ファイルのパスを決定します。
 79
 80    指定されたディレクトリが存在しない場合、またはディレクトリ内に`ffmpeg`と`ffprobe`が見つからない場合はエラーとなります。
 81    Windows環境では実行ファイルに`.exe`拡張子が付与されます。
 82    `directory`が`None`の場合、システムPATHから`ffmpeg`と`ffprobe`を検索します。
 83
 84    :param directory: FFmpegバイナリが格納されているディレクトリのパス。`None` の場合はシステムのPATHから検索されます。
 85    :type directory: Optional[Path]
 86    :returns: FFmpegとFFprobeのフルパスのタプル。
 87    :rtype: tuple[str, str]
 88    :raises RuntimeError: 指定されたディレクトリに `ffmpeg` または `ffprobe` が見つからない場合。
 89    """
 90    if directory is None:
 91        return "ffmpeg", "ffprobe"
 92    suffix = ".exe" if __import__("sys").platform == "win32" else ""
 93    directory = directory.expanduser().resolve()
 94    ffmpeg, ffprobe = directory / f"ffmpeg{suffix}", directory / f"ffprobe{suffix}"
 95    if not ffmpeg.is_file() or not ffprobe.is_file():
 96        raise RuntimeError("--ffmpeg-dir には ffmpeg と ffprobe がある bin フォルダを指定してください。")
 97    return str(ffmpeg), str(ffprobe)
 98
 99
100def audio_duration(source: Path, ffprobe: str) -> float:
101    """
102    音声ファイルの長さを取得します。
103
104    `ffprobe` コマンドを使用して音声ファイルの `duration` 情報を抽出し、
105    秒単位の浮動小数点数として返します。
106
107    :param source: 音声ファイルへのパス。
108    :type source: Path
109    :param ffprobe: `ffprobe` 実行ファイルのフルパス。
110    :type ffprobe: str
111    :returns: 音声ファイルの長さ(秒)。
112    :rtype: float
113    :raises RuntimeError: 音声ファイルの長さを取得できなかった場合。
114    """
115    try:
116        return float(run_command([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", str(source)]))
117    except ValueError as exc:
118        raise RuntimeError("音声長を取得できませんでした。") from exc
119
120
121def extract_wav(source: Path, start: float, length: float, destination: Path, ffmpeg: str) -> None:
122    """
123    音声ファイルから指定された範囲をWAV形式で抽出します。
124
125    `ffmpeg` コマンドを使用して、元の音声ファイルから指定された開始時間と長さの部分を
126    モノラル、16kHzサンプリングレート、PCM_s16le形式のWAVファイルとして出力します。
127
128    :param source: 元の音声ファイルへのパス。
129    :type source: Path
130    :param start: 抽出開始時間(秒)。
131    :type start: float
132    :param length: 抽出する長さ(秒)。
133    :type length: float
134    :param destination: 抽出されたWAVファイルの出力パス。
135    :type destination: Path
136    :param ffmpeg: `ffmpeg` 実行ファイルのフルパス。
137    :type ffmpeg: str
138    :returns: None
139    :rtype: None
140    """
141    run_command([ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-ss", f"{start:.3f}", "-t", f"{length:.3f}", "-i", str(source), "-vn", "-map", "0:a:0", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", str(destination)])
142
143
144def hms(seconds: Optional[float]) -> str:
145    """
146    秒数を `HH:MM:SS.ss` 形式の文字列に変換します。
147
148    `None` が指定された場合は `??:??:??.??` を返します。
149    負の秒数は0として扱われます。
150
151    :param seconds: 変換する秒数。
152    :type seconds: Optional[float]
153    :returns: フォーマットされた時間文字列。
154    :rtype: str
155    """
156    if seconds is None:
157        return "??:??:??.??"
158    seconds = max(0.0, seconds)
159    return f"{int(seconds // 3600):02d}:{int(seconds % 3600 // 60):02d}:{seconds % 60:05.2f}"
160
161
162def save_json(path: Path, value: dict[str, Any]) -> None:
163    """
164    指定されたパスに辞書をJSON形式で保存します。
165
166    一時ファイルに書き込んだ後、元のファイルを置き換えることで、
167    ファイル破損のリスクを低減するアトミックな保存を試みます。
168    非ASCII文字も正しく保存されます。
169
170    :param path: 保存先のファイルパス。
171    :type path: Path
172    :param value: 保存する辞書データ。
173    :type value: dict[str, Any]
174    :returns: None
175    :rtype: None
176    """
177    temporary = path.with_suffix(path.suffix + ".tmp")
178    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8")
179    temporary.replace(path)
180
181
182def write_outputs(output: Path, result: ASRResult, report: dict[str, Any], corrected: Optional[str]) -> None:
183    """
184    音声認識結果とレポートを複数のファイル形式で出力します。
185
186    以下のファイルを出力します:
187    - 時刻付きテキストファイル (例: ``{output_stem}-time.txt``)
188    - プレーンテキストファイル (例: ``{output_stem}.txt``)
189    - JSON形式のレポートファイル (例: ``{output_stem}-info.json``)
190    `corrected` が提供されている場合、校正済みテキストファイルも出力されます (例: ``{output_stem}.corrected.txt``)。
191
192    :param output: 出力ファイル名のベースパス(拡張子なし)。
193                   例: `Path("output/audio")` と指定すると、`output/audio-time.txt` などが生成されます。
194    :type output: Path
195    :param result: 音声認識の結果データ。
196    :type result: ASRResult
197    :param report: その他のレポート情報。
198    :type report: dict[str, Any]
199    :param corrected: 校正済みのテキスト。提供されている場合のみ出力されます。
200    :type corrected: Optional[str]
201    :returns: None
202    :rtype: None
203    """
204    time_file = output.with_name(output.stem + "-time.txt")
205    plain_file = output.with_suffix(".txt")
206    info_file = output.with_name(output.stem + "-info.json")
207    with time_file.open("w", encoding="utf-8") as handle:
208        for segment in result.segments:
209            handle.write(f"[{hms(segment.start)} - {hms(segment.end)}] {segment.text}\n")
210        if not result.segments:
211            handle.write(result.text + "\n")
212    plain_file.write_text(result.text + ("\n" if result.text else ""), encoding="utf-8")
213    info_file.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
214    print(f"時刻付き: {time_file}\nASR原文 : {plain_file}\n情報     : {info_file}")
215    if corrected is not None:
216        corrected_file = plain_file.with_name(plain_file.stem + ".corrected.txt")
217        corrected_file.write_text(corrected + "\n", encoding="utf-8")
218        print(f"校正済み: {corrected_file}")