Clicky

Google ColaboratoryでGoogleドライブに保存している動画の文字起こしをしてGoogleドキュメントで保存する

Google Colaboratory
Google Colaboratory
この記事は約5分で読めます。

※記事中に広告情報を含みます。

スキルを手に入れた時、人は強くなれる。
Youtubeでスキルアップを始める 電子書籍でスキルアップを始める
\ワードプレスのスキルアップはこちら!/ WordPress入門読本

Google Colaboratoryを使用して、Googleドライブに保存している動画の文字起こしを行い、その結果をGoogleドキュメントに保存する方法を説明します。

基本的には、前回の手順と同じ+アルファの続きとなります。

環境設定

  1. Google Colaboratoryで新しいノートブックを作成します。
  2. ランタイムタイプをGPUに設定します。

必要なライブラリのインストール

以下のコードを実行して、必要なライブラリをインストールします。

!pip install git+https://github.com/openai/whisper.git
!sudo apt update && sudo apt install ffmpeg
!pip install google-auth google-auth-oauthlib google-api-python-client

Googleドライブのマウント

Googleドライブをマウントして、フォルダにアクセスできるようにします。

from google.colab import drive
drive.mount('/content/drive')

文字起こし処理

  1. Whisperモデルをロードします。
  2. 動画ファイルから音声を抽出し、文字起こしを行います。
import whisper
import os

model = whisper.load_model("base")

video_folder = "/content/drive/MyDrive/Whisper/videos"
text_folder = "/content/drive/MyDrive/Whisper/text"

for video_file in os.listdir(video_folder):
if video_file.endswith(('.mp4', '.avi', '.mov')):
video_path = os.path.join(video_folder, video_file)
result = model.transcribe(video_path)

text_path = os.path.join(text_folder, os.path.splitext(video_file)[0] + '.txt')
with open(text_path, "w", encoding="utf-8") as f:
f.write(result["text"])

Googleドキュメントへの保存

文字起こし結果をGoogleドキュメントに保存するために、Google Docs APIを使用します:

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

# 認証設定(詳細は省略)
creds = Credentials.from_authorized_user_file("token.json", ["https://www.googleapis.com/auth/documents"])

# Docs APIサービスを構築
service = build("docs", "v1", credentials=creds)

for text_file in os.listdir(text_folder):
if text_file.endswith('.txt'):
with open(os.path.join(text_folder, text_file), "r", encoding="utf-8") as f:
content = f.read()

# 新しいドキュメントを作成
document = service.documents().create(body={"title": f"Transcription: {text_file}"}).execute()

# テキストを追加
requests = [
{
'insertText': {
'location': {'index': 1},
'text': content
}
}
]
service.documents().batchUpdate(documentId=document['documentId'], body={'requests': requests}).execute()

print(f"ドキュメントが作成されました: {document['title']}")

注意点

  • Google Cloud Projectの設定とGoogle Docs APIの有効化が必要です。
  • 適切な認証情報(token.json)を用意する必要があります。
  • 大量の動画や長時間の動画を処理する場合、Colaboratoryのセッション時間制限に注意してください。
  • 文字起こしの精度は音声の品質や言語によって異なる場合があります。

まとめ

この方法を使用することで、Googleドライブに保存された動画から効率的に文字起こしを行い、その結果をGoogleドキュメントとして保存できます。必要に応じて、生成されたドキュメントを編集したり共有したりすることが可能です。