Communitygithub.com

AI動画生成 — ショート動画パイプライン

AIを活用して短尺動画(TikTok、YouTube Shorts、Instagram Reels)を自動生成します。スクリプト作成、テキスト読み上げナレーション、ストック映像選択、字幕生成、動画編集までを一貫して実行できます。

AI動画生成 — ショート動画パイプライン とは?

このスキルは、短尺動画の制作プロセス全体をAIで自動化するための、実践的かつ包括的なツールセットです。開発者は、提供されるPythonコードを利用して、トピックのリサーチからスクリプト作成、テキスト読み上げナレーション、ストック映像の検索・ダウンロード、WhisperXによる高精度な単語レベルの字幕生成、そしてFFmpegによる最終的な動画アセンブリまでを、わずか数行のコードで実行できます。特にTikTokやYouTubeショート、Instagramリールのような縦型ショート動画の制作に最適化されており、コンテンツ制作パイプラインの自動化や、複数の動画を一括生成するバッチ処理に役立ちます。Claude SonnetやElevenLabs、Pexels APIといった外部サービスを組み合わせることで、低コストで高品質な動画を量産することが可能です。

対応✓Claude Code✓Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/ai-video-generator

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

AI動画生成 — ショート動画コンテンツパイプライン

概要

AIを活用して短尺動画(TikTok、YouTube Shorts、Instagram Reels)の作成を自動化します。トピックリサーチ、スクリプト作成、テキスト読み上げナレーション、ストック映像マッチング、字幕生成、最終アセンブリまでをすべてカバー。53,000以上のスターを誇るMoneyPrinterTurboから着想を得ています。

手順

ステップ1:環境セットアップ

pip install anthropic openai requests moviepy pydub whisperx srt
sudo apt install ffmpeg  # Linux — または:brew install ffmpeg(macOS)

必要なAPIキー: AnthropicまたはOpenAI(スクリプト)、ElevenLabsまたはOpenAI TTS(音声)、Pexels(無料ストック映像)。

ステップ2:AIスクリプト作成

import anthropic

def generate_script(topic, duration_seconds=45):
    """ショート動画向けに最適化された動画スクリプトを生成します。"""
    client = anthropic.Anthropic()
    prompt = f"""{topic}について{duration_seconds}秒の動画スクリプトを作成してください。
    フォーマット:
    HOOK(最初の3秒):スクロールを止める衝撃的な発言や質問
    BODY(メインコンテンツ):3~5個の簡潔な事実やポイント、それぞれ1~2文
    CTA(最後の5秒):アクションを促す呼びかけ — フォロー、いいね、コメント
    ルール:
    - 会話調で、複雑な文は避ける
    - 各文は独立した行に
    - 約{duration_seconds * 2.5:.0f}語({duration_seconds}秒、毎分150語)
    - パワーワードを使用:秘密、衝撃的、誰も教えてくれない、実は
    - 絵文字やハッシュタグは使用しない — これはナレーション用スクリプトです
    """
    response = client.messages.create(
        model="claude-sonnet-4-20250514", max_tokens=500,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

ステップ3:テキスト読み上げナレーション

import requests, os

def generate_voice_elevenlabs(text, output_path='narration.mp3'):
    """ElevenLabsを使用してナレーションを生成します。"""
    url = "https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM"
    headers = {"xi-api-key": os.environ["ELEVENLABS_API_KEY"], "Content-Type": "application/json"}
    data = {"text": text, "model_id": "eleven_turbo_v2_5",
            "voice_settings": {"stability": 0.5, "similarity_boost": 0.75}}
    response = requests.post(url, json=data, headers=headers)
    with open(output_path, 'wb') as f:
        f.write(response.content)
    return output_path

def generate_voice_openai(text, output_path='narration.mp3'):
    """OpenAI TTSを使用してナレーションを生成します(より安価な代替手段)。"""
    from openai import OpenAI
    client = OpenAI()
    response = client.audio.speech.create(model="tts-1-hd", voice="onyx", input=text)
    response.stream_to_file(output_path)
    return output_path

ステップ4:ストック映像の選択

def search_pexels_videos(query, count=5):
    """Pexelsで縦向きのストック動画クリップを検索します。"""
    url = "https://api.pexels.com/videos/search"
    headers = {"Authorization": os.environ["PEXELS_API_KEY"]}
    params = {"query": query, "per_page": count, "orientation": "portrait", "size": "medium"}
    response = requests.get(url, headers=headers, params=params)
    videos = response.json().get('videos', [])
    results = []
    for v in videos:
        files = sorted(v['video_files'], key=lambda x: x.get('height', 0), reverse=True)
        hd = next((f for f in files if f.get('height', 0) >= 720), files[0])
        results.append({'id': v['id'], 'url': hd['link'], 'duration': v['duration']})
    return results

ステップ5:字幕生成

def generate_subtitles(audio_path, output_srt='subtitles.srt'):
    """WhisperXを使用して単語レベルの字幕を生成します。"""
    import whisperx, srt
    from datetime import timedelta
    model = whisperx.load_model("base", device="cpu")
    audio = whisperx.load_audio(audio_path)
    result = model.transcribe(audio)
    align_model, metadata = whisperx.load_align_model(language_code="en")
    aligned = whisperx.align(result["segments"], align_model, metadata, audio)
    subs = []
    words = [w for seg in aligned["segments"] for w in seg.get("words", [])]
    for i in range(0, len(words), 4):
        group = words[i:i + 4]
        if not group: continue
        start = timedelta(seconds=group[0].get('start', 0))
        end = timedelta(seconds=group[-1].get('end', 0))
        text = ' '.join(w['word'] for w in group)
        subs.append(srt.Subtitle(index=len(subs)+1, start=start, end=end, content=text))
    with open(output_srt, 'w') as f:
        f.write(srt.compose(subs))
    return output_srt

ステップ6:FFmpegによる動画アセンブリ

import subprocess

def assemble_video(clips, narration, subtitles, output='final.mp4'):
    """最終動画をアセンブリ:クリップの連結、ナレーションと字幕の追加。"""
    concat_list = 'concat_list.txt'
    with open(concat_list, 'w') as f:
        for clip in clips:
            f.write(f"file '{clip}'\n")
    subprocess.run([
        'ffmpeg', '-y', '-f', 'concat', '-safe', '0', '-i', concat_list,
        '-vf', 'scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920',
        '-c:v', 'libx264', '-preset', 'fast', '-an', 'temp_video.mp4'
    ], check=True)
    subtitle_filter = (f"subtitles={subtitles}:force_style='"
        "FontName=Arial,FontSize=18,PrimaryColour=&H00FFFFFF,"
        "OutlineColour=&H00000000,Outline=2,Bold=1,Alignment=2'")
    subprocess.run([
        'ffmpeg', '-y', '-i', 'temp_video.mp4', '-i', narration,
        '-vf', subtitle_filter, '-c:v', 'libx264', '-c:a', 'aac',
        '-shortest', output
    ], check=True)
    return output

ステップ7:完全パイプライン

def generate_video(topic, output_dir='./output'):
    """完全なパイプライン:トピックから完成動画まで。"""
    import os
    os.makedirs(output_dir, exist_ok=True)
    script = generate_script(topic)
    narration = generate_voice_elevenlabs(script, f'{output_dir}/narration.mp3')
    keywords = topic.split()[:3]
    videos = search_pexels_videos(' '.join(keywords), count=3)
    clips = []
    for i, v in enumerate(videos):
        path = f'{output_dir}/clip_{i}.mp4'
        requests.get(v['url'], stream=True)  # クリップをダウンロード
        clips.append(path)
    subs = generate_subtitles(narration, f'{output_dir}/subs.srt')
    return assemble_video(clips, narration, subs, f'{output_dir}/final.mp4')

使用例

例1:テクノロジー系ファクト動画の一括生成

クリエイターがTikTok向けに5本のテクノロジー関連ショート動画を一度の実行で作成します:

topics = [
    "誰も語らないAIツール",
    "無料なのに使うのが違法に感じるアプリ",
    "あなたの常識を覆すウェブサイト",
    "学生に必要な無料AIツール",
    "私の人生を変えた50ドル以下のテクノロジーガジェット"
]
for topic in topics:
    output = generate_video(topic, output_dir=f'./output/{topic[:30]}')
    print(f"動画準備完了:{output}")
# 各動画:約45秒、縦1080x1920、字幕とナレーション付き
# 総コスト:約$0.25(5本 x 1本あたり$0.05)ElevenLabs + Claude Sonnet使用

例2:YouTube向け毎日の金融ショート動画

金融チャンネルが話題のお金に関するトピックで毎日のショート動画アップロードを自動化:

import schedule

def daily_finance_video():
    topic = "2025年に実際に機能する3つの不労所得アイデア"
    script = generate_script(topic, duration_seconds=55)
    # スクリプト出力:
    # HOOK:「あなたはこれらを知らないせいで、毎日お金を失っています。」
    # BODY:1. プリントオンデマンドストア(月500~2000ドル)
    #       2. AI生成コンテンツライセンス(月300~1000ドル)
    #       3. 配当ETF積立(月200~800ドルの不労所得)
    # CTA:「もっとお金のヒントを知りたい方はフォローを。」
    narration = generate_voice_openai(script, './daily/narration.mp3')
    videos = search_pexels_videos("money finance investing", count=4)
    # お金/チャート/ライフスタイルの縦型クリップを4本ダウンロード
    # 太字の白い字幕でアセンブリ、55秒のショート動画を出力
    final = assemble_video(['./daily/clip_0.mp4', './daily/clip_1.mp4'],
                           narration, './daily/subs.srt', './daily/final.mp4')

schedule.every().day.at("08:00").do(daily_finance_video)

ガイドライン

  • 著作権を尊重 — ロイヤリティフリーのストック映像(Pexels、Pixabay)または自身のコンテンツのみ使用
  • AI利用を開示 — YouTubeとTikTokではAI生成コンテンツの開示が必要
  • 公開前に確認 — 常に最終動画を視聴;AIスクリプトには不正確な情報が含まれる可能性がある
  • 最初の3秒を最適化 — HOOKが視聴者の離脱を防ぐ
  • 複数の音声をテスト — ElevenLabsは数十の音声を提供;あなたのニッチに合うものを見つける
  • パフォーマンスを監視 — 視聴回数、維持率、クリック率を追跡し、コンテンツスタイルを改善

参考文献

  • MoneyPrinterTurbo — 元となったインスピレーション(53,000スター)
  • Pexels API — 無料ストック動画
  • ElevenLabs — リアルなテキスト読み上げ
  • WhisperX — 単語レベルの字幕アライメント

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

TerminalSkills/skills

>- Run GitHub Actions locally with act. Use when a user asks to test GitHub Actions workflows locally, debug CI pipelines without pushing, or run workflows offline.

TerminalSkills/skills

>- You are an expert in AG2 (formerly AutoGen), the open-source multi-agent conversation framework. You help developers build systems where multiple AI agents collaborate through structured conversations — with tool use, human-in-the-loop, code execution, group chat orchestration, and nested conversations — for complex tasks like software development, research, and data analysis.

TerminalSkills/skills

>- Animate 3D objects and characters in Blender with Python. Use when the user wants to keyframe properties, create armatures and rigs, set up IK/FK chains, animate shape keys for facial animation, edit F-Curves, use the NLA editor to blend actions, add drivers for expression-based animation, or script any animation workflow in Blender.

TerminalSkills/skills

>- Automate motion capture and tracking workflows in Blender with Python. Use when the user wants to import BVH or FBX mocap data, retarget motion to armatures, track camera or object motion from video, solve camera motion, clean up motion capture data, or script any tracking pipeline in Blender.

TerminalSkills/skills

>- You are an expert in Bolt.new by StackBlitz, the AI-powered full-stack development environment that runs entirely in the browser. You help developers go from idea to deployed app in minutes using natural language prompts — Bolt generates complete applications with frontend, backend, database, and deployment, all running in a WebContainer without local setup.

TerminalSkills/skills

>- Assists with using Bun as an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Use when building HTTP servers, managing packages, running tests, or migrating from Node.js. Trigger words: bun, bun serve, bun install, bun test, bun build, javascript runtime, bun runtime.

TerminalSkills/skills

>- Self-host customer support with Chatwoot. Use when a user asks to set up open-source customer support, add live chat without SaaS costs, build a multi-channel inbox, or deploy a free Intercom alternative.

TerminalSkills/skills

>- You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.

TerminalSkills/skills

When the user wants to edit, review, or improve existing marketing copy. Also use when the user mentions 'edit this copy,' 'review my copy,' 'copy feedback,' 'proofread,' 'polish this,' 'make this better,' or 'copy sweep.' This skill provides a systematic approach to editing marketing copy through multiple focused passes.

TerminalSkills/skills

>- Add live chat and customer support with Crisp. Use when a user asks to add a chat widget, implement live customer support, set up a help desk, create a knowledge base, or add a chatbot to a website.

TerminalSkills/skills

>- Assists with building custom interactive data visualizations using D3.js. Use when creating charts, graphs, maps, force layouts, or hierarchical diagrams that require fine-grained control beyond what charting libraries provide. Trigger words: d3, data visualization, chart, svg, scales, force graph, treemap, choropleth.

TerminalSkills/skills

dbt (data build tool) transforms data in your warehouse using SQL SELECT statements. Learn project setup, models, tests, documentation, incremental materializations, and integration with data warehouses like PostgreSQL, BigQuery, and Snowflake.

TerminalSkills/skills

>- You are an expert in dlt, the open-source Python library for building data pipelines. You help developers load data from any API, file, or database into warehouses and lakes using simple Python decorators — with automatic schema inference, incremental loading, and built-in data contracts. dlt is the "requests library for data pipelines.

TerminalSkills/skills

Data Version Control for ML projects. Track large datasets and models alongside Git, build reproducible ML pipelines, and run experiments with metric comparison. Works with any storage backend including S3, GCS, Azure, and local filesystems.

TerminalSkills/skills

>- You are an expert in E2B, the cloud platform for running AI-generated code in secure sandboxes. You help developers give AI agents the ability to execute code, install packages, read/write files, and run long processes in isolated cloud environments — each sandbox is a lightweight VM that boots in ~150ms with full Linux, filesystem, and networking.

TerminalSkills/skills

>- Transcode, convert, edit, and process audio and video with FFmpeg. Use when a user asks to convert video formats (webm to mp4, mkv to mp4), extract audio from video, compress video files, trim or cut clips, concatenate videos, add subtitles, create thumbnails, apply filters, change resolution or bitrate, re-encode media, create GIFs from video, add watermarks, normalize audio, stream media, or build automated media processing pipelines.

TerminalSkills/skills

>- Create advanced animations with GSAP. Use when building complex timelines, scroll-driven animations, SVG morphing, text animations, or high-performance web animations beyond CSS capabilities.

TerminalSkills/skills

>- Generate deterministic MP4 videos from HTML, CSS, media, and seekable animations using HeyGen's HyperFrames framework. Use when someone asks to "render HTML to video", "make a video with HyperFrames", "create a programmatic video", "turn an animation into MP4", "build a launch/product video from HTML", "render GSAP/Lottie/Three.js to video", or set up an agent-driven video pipeline. Covers init/preview/render/add/lint/inspect commands, data-* timing attributes, animation adapters, and the component catalog.

TerminalSkills/skills

When the user wants to perform load testing, stress testing, or performance testing of APIs and websites using k6. Also use when the user mentions "k6," "load test," "performance test," "stress test," "spike test," "soak test," "thresholds," "virtual users," or "VUs." For browser-based testing, see selenium.

TerminalSkills/skills

>- Lovable (formerly GPT Engineer) is a browser-based AI app builder that turns a natural-language description into a working full-stack web app with a built-in backend, authentication, database and one-click publishing. Use when the user wants to prototype or ship a web app with Lovable, write effective Lovable prompts, connect Supabase or GitHub, review generated security rules, or move a Lovable project into their own editor.

関連スキル