YouTube Shorts台本をAIで自動生成するPythonスクリプト
YouTube ShortsやTikTokなど短尺動画コンテンツの需要が急速に高まっています。しかし、毎日複数の動画を公開するとなると、台本・字幕・ハッシュタグの作成が大きな負担になります。本記事では、LLM(Large Language Model)を活用して、これらのコンテンツを自動生成するPythonスクリプトの実装方法を解説します。
短尺動画コンテンツ生成の課題
YouTube Shortsで成功するには、高頻度での投稿が欠かせません。ただし、手作業で台本から字幕、ハッシュタグまでを毎回準備するのは現実的ではありません。
一般的な課題として以下が挙げられます:
- 時間コスト: 1本の動画につき30分〜1時間の準備時間が必要
- クオリティのばらつき: 手作業では一貫性が保ちづらい
- スケーラビリティの限界: 投稿数を増やすと品質が低下しやすい
LLMを使ったコンテンツ生成パイプラインなら、これらの課題を大幅に軽減できます。
LLMを活用したコンテンツ生成パイプラインの設計
効率的なコンテンツ生成には、適切なパイプライン設計が必須です。基本的な流れは以下の通りです:
- 入力: トピックやキーワード
- 台本生成: LLMによるスクリプト作成
- 字幕最適化: 短尺動画向けの字幕形式への変換
- ハッシュタグ生成: 視聴数を伸ばすタグの自動生成
- 出力: 統合されたコンテンツデータ
このパイプラインの特徴は、各段階で異なるプロンプトを使い分けることで、目的に特化した出力が得られる点です。
必要なライブラリのセットアップ
まずは必要なライブラリをインストールします。OpenAI APIを使用する場合:
pip install openai python-dotenv requests
環境変数の設定:
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
台本生成モジュールの実装
トピックから YouTube Shorts向けの台本を生成するモジュールです:
import openai
def generate_script(topic: str, tone: str = "casual") -> str:
"""
トピックからShortsの台本を生成
Args:
topic: 動画のテーマ
tone: トーン(casual, professional, entertaining)
Returns:
生成された台本
"""
prompt = f"""
You are a YouTube Shorts script writer. Create a short, engaging script for a {tone} YouTube Shorts video.
Topic: {topic}
Requirements:
- 30-60 seconds of speaking (approximately 75-150 words)
- Hook the viewer in the first 3 seconds
- Use simple, conversational language
- Include a clear call-to-action at the end
Return ONLY the script text, without any additional commentary.
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=300
)
return response.choices[0].message.content.strip()
字幕とハッシュタグの自動生成
台本から字幕とハッシュタグを生成するモジュール:
def generate_subtitles(script: str, max_chars_per_line: int = 30) -> list:
"""
台本を字幕形式に変換
Args:
script: 生成された台本
max_chars_per_line: 1行あたりの最大文字数
Returns:
字幕リスト
"""
sentences = script.split('。')
subtitles = []
for sentence in sentences:
sentence = sentence.strip()
if not sentence:
continue
# 指定文字数ごとに改行
words = sentence.split()
current_line = ""
for word in words:
if len(current_line) + len(word) > max_chars_per_line:
if current_line:
subtitles.append(current_line)
current_line = word
else:
current_line += word if not current_line else word
if current_line:
subtitles.append(current_line)
return subtitles
def generate_hashtags(topic: str, count: int = 10) -> list:
"""
動画のテーマからハッシュタグを生成
Args:
topic: 動画のテーマ
count: 生成するハッシュタグの数
Returns:
ハッシュタグリスト
"""
prompt = f"""
Generate {count} relevant and trending hashtags for a YouTube Shorts video about: {topic}
Requirements:
- Mix popular hashtags with niche ones
- Focus on discoverability
- Include both general and specific tags
Return ONLY hashtags separated by spaces, starting with #
"""
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=100
)
hashtags_str = response.choices[0].message.content.strip()
return hashtags_str.split()
統合パイプラインの実装
すべてを統合した完全なコンテンツ生成パイプライン:
from dataclasses import dataclass
from typing import List
@dataclass
class ShortsContent:
topic: str
script: str
subtitles: List[str]
hashtags: List[str]
def to_dict(self):
return {
"topic": self.topic,
"script": self.script,
"subtitles": self.subtitles,
"hashtags": " ".join(self.hashtags)
}
def generate_shorts_content(topic: str, tone: str = "casual") -> ShortsContent:
"""
トピックからYouTube Shorts用の全コンテンツを生成
Args:
topic: 動画のテーマ
tone: トーン設定
Returns:
ShortsContent オブジェクト
"""
print(f"🎬 Generating content for: {topic}")
# 1. 台本生成
print("📝 Generating script...")
script = generate_script(topic, tone)
# 2. 字幕生成
print("📋 Generating subtitles...")
subtitles = generate_subtitles(script)
# 3. ハッシュタグ生成
print("#️⃣ Generating hashtags...")
hashtags = generate_hashtags(topic)
print("✅ Content generation completed!")
return ShortsContent(
topic=topic,
script=script,
subtitles=subtitles,
hashtags=hashtags
)
# 使用例
if __name__ == "__main__":
content = generate_shorts_content("AI-powered productivity tips")
print("\n" + "="*50)
print("GENERATED CONTENT")
print("="*50)
print(f"📌 Topic: {content.topic}\n")
print(f"📝 Script:\n{content.script}\n")
print(f"📋 Subtitles:")
for i, subtitle in enumerate(content.subtitles, 1):
print(f" {i}. {subtitle}")
print(f"\n#️⃣ Hashtags: {' '.join(content.hashtags)}")
実装のポイントと最適化のコツ
実運用では以下の工夫が有効です:
プロンプトエンジニアリング:
- 目的に応じて異なるプロンプトを使い分ける
- 「トーン」や「対象オーディエンス」を明示する
- 出力形式を厳密に指定する
エラーハンドリング:
import time
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def generate_script_with_retry(topic: str) -> str:
return generate_script(topic)
キャッシング:
同じトピックで複数回生成する場合、結果をキャッシュして API コストを削減できます。
バッチ処理:
複数のトピックを一括処理する場合は、非同期処理で効率化します。
まとめ・ツール紹介
本記事で紹介した手法を手軽に試したい方には、ShortsAIが便利です。
設定不要ですぐに使えます。
Python スクリプトで実装することで、YouTube Shorts のコンテンツ制作を大幅に自動化できます。LLM の活用により、品質を保ちながら投稿頻度を大幅に増やすことが可能になります。ぜひ自社のコンテンツ戦略に組み込んでみてください。