Communitygithub.com

TerminalSkills/skills

使用 AI 自動化生成短影片——腳本撰寫、文字轉語音旁白、素材挑選、字幕生成與影片合成。適合製作 TikTok、YouTube Shorts、Instagram Reels 內容、自動化影片生產及建立內容管線。

skills 是什麼?

這項技能提供了一個完整的自動化管線,用於生成 TikTok、YouTube Shorts 和 Instagram Reels 等短影片格式。它整合了多個 AI 服務,包括使用 Claude 或 OpenAI 進行腳本撰寫、使用 ElevenLabs 或 OpenAI TTS 進行文字轉語音、使用 Pexels API 挑選免費版權素材,以及使用 WhisperX 生成逐字字幕。最終影片透過 FFmpeg 合成,輸出解析度為 1080x1920 的直立式影片。本技能靈感來自知名開源專案 MoneyPrinterTurbo,支援批次處理與排程自動化,適合內容創作者行銷團隊與希望建立自動化內容管線的開發者。

相容平台✓Claude Code✓Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/TerminalSkills/skills/tree/HEAD/skills/ai-video-generator

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

AI 影片生成器 — 短內容製片管線

概述

使用 AI 自動化短影片(TikTok、YouTube Shorts、Instagram Reels)的每個步驟:主題研究、腳本撰寫、文字轉語音旁白、素材配對、字幕生成與最終合成。靈感來自 MoneyPrinterTurbo(53k+ stars)。

操作說明

步驟 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"""寫一段 {duration_seconds} 秒的影片腳本,主題是:{topic}
    格式:
    HOOK(前 3 秒):一個驚人陳述或問題,能讓觀眾停止滑動
    主體(主要內容):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 工具",
    "用起來像違法但其實免費的 App",
    "讓你大開眼界的網站",
    "每個學生都需要的免費 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 $0.05 每支影片)使用 ElevenLabs + Claude Sonnet

範例 2:每日 YouTube 財經短片

一個財經頻道透過排程自動化每日上傳 Trending 金錢主題短片:

import schedule

def daily_finance_video():
    topic = "2025 年真正可行的 3 種被動收入點子"
    script = generate_script(topic, duration_seconds=55)
    # 腳本輸出:
    # HOOK: "你每一天都在賠錢,卻還不知道這些方法。"
    # 主體:1. 接單印刷商店($500-2k/月)
    #       2. AI 生成內容授權($300-1k/月)
    #       3. 股息 ETF 累積策略($200-800/月 被動收入)
    # CTA: "追蹤以獲取更多沒人告訴你的理財祕訣。"
    narration = generate_voice_openai(script, './daily/narration.mp3')
    videos = search_pexels_videos("money finance investing", count=4)
    # 下載 4 段直立素材(金錢/圖表/生活風格)
    # 以粗體白色字幕合成,輸出 55 秒 Short 影片
    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 秒 — 鉤子決定觀眾是留下還是滑走
  • 測試多種語音 — ElevenLabs 提供數十種語音;選擇適合你主題的聲音
  • 監控成效 — 追蹤觀看數、留存率和點擊率,以迭代內容風格

參考資料

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.

相關技能