Pythonで音声ファイルの文字起こしを行うGUIアプリケーションを作成するためのコードを以下に示します。このプログラムは、Pythonのtkinterライブラリを使用してGUIを構築し、音声ファイルの文字起こしにはGoogle Cloud Speech-to-Text APIを使用します。また、文字起こしされたファイルは自動的にダウンロードされます。
まず、Google Cloud Speech-to-Text APIを利用するためにはGoogle Cloudのプロジェクトを作成し、APIキーを取得する必要があります。APIキーの設定についてはGoogle Cloudの公式ドキュメントを参照してください。
以下に、必要なPythonコードを示します。
### 依存パッケージのインストール
```bash
pip install tkinter google-cloud-speech pydub
```
### Pythonコード
```python
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from google.cloud import speech
import io
from pydub import AudioSegment
def transcribe_audio(file_path):
client = speech.SpeechClient()
audio = AudioSegment.from_file(file_path, format="m4a")
audio.export("audio.wav", format="wav")
with io.open("audio.wav", "rb") as audio_file:
content = audio_file.read()
audio = speech.RecognitionAudio(content=content)
config = speech.RecognitionConfig(
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=16000,
language_code="en-US",
enable_automatic_punctuation=True)
response = client.recognize(config=config, audio=audio)
return response
def select_file():
filetypes = (
('M4A files', '*.m4a'),
('All files', '*.*')
)
filepath = filedialog.askopenfilename(title='Open a file', initialdir='/', filetypes=filetypes)
if filepath:
response = transcribe_audio(filepath)
transcript = ""
for result in response.results:
transcript += result.alternatives[0].transcript + '\n'
save_transcript(filepath, transcript)
def save_transcript(filepath, transcript):
save_path = filepath.rsplit('.', 1)[0] + '_transcript.txt'
with open(save_path, 'w') as file:
file.write(transcript)
messagebox.showinfo("Success", f"Transcription saved to {save_path}")
os.startfile(save_path)
# GUI Setup
root = tk.Tk()
root.title("Audio Transcription")
root.geometry("400x200")
frame = tk.Frame(root)
frame.pack(pady=20)
label = tk.Label(frame, text="Select an M4A audio file (max 30 mins)")
label.pack(pady=10)
button = tk.Button(frame, text="Browse", command=select_file)
button.pack()
root.mainloop()
```
### 説明
1. **依存パッケージのインストール**: tkinter, google-cloud-speech, pydubをインストールします。
2. **transcribe_audio関数**: Google Cloud Speech-to-Text APIを使用して音声ファイルを文字起こしする関数です。音声ファイルをWAV形式に変換し、APIに送信します。
3. **select_file関数**: tkのfiledialogを使用してユーザーに音声ファイルを選択させる関数です。選択されたファイルを文字起こしのためにtranscribe_audio関数に渡します。
4. **save_transcript関数**: 文字起こし結果をテキストファイルに保存し、自動的にダウンロード(開く)します。
5. **GUIのセットアップ**: tkinterを使用して簡単なGUIを構築し、ユーザーが音声ファイルを選択できるようにします。
このコードを実行すると、GUIウィンドウが開き、「Browse」ボタンをクリックしてM4A形式の音声ファイルを選択することで、音声ファイルの文字起こしが行われ、結果がテキストファイルとして保存されます。