import subprocess
import time
from pathlib import Path
from agno.agent import Agent
from agno.media import Video
from agno.models.google import Gemini
from agno.utils.log import logger
from google.generativeai import get_file, upload_file
video_path = Path(__file__).parent.joinpath("sample.mp4")
output_dir = Path("tmp/shorts")
agent = Agent(
name="Video2Shorts",
description="处理视频并生成引人入胜的短视频。",
model=Gemini(id="gemini-2.0-flash-exp"),
markdown=True,
debug_mode=True,
instructions=[
"直接分析提供的视频——**请勿**引用或分析任何外部来源或 YouTube 视频。",
"识别符合短内容格式要求的吸引人片段。",
"""以**表格格式**提供您的分析,包含以下列:
- 开始时间 | 结束时间 | 描述 | 重要性得分""",
"确保所有时间戳都使用 MM:SS 格式,重要性得分范围为 1-10。",
"仅关注时长在 15 到 60 秒之间的片段。",
"分析仅基于提供的视频内容。",
"提供可操作的见解,以改进已识别片段以优化短内容。",
],
)
# 上传并处理视频
video_file = upload_file(video_path)
while video_file.state.name == "PROCESSING":
time.sleep(2)
video_file = get_file(video_file.name)
# 多模态查询视频分析
query = """
您是视频内容创作专家,擅长为 YouTube Shorts 和 Instagram Reels 等平台制作吸引人的短视频。您的任务是分析提供的视频并识别能最大程度吸引观众的片段。
对于每个视频,您将:
1. 识别能吸引观众注意力的关键时刻,重点关注:
- 高能序列
- 情感爆发点
- 令人惊讶或意想不到的时刻
- 强大的视听元素
- 具有引人入胜的故事的清晰叙事片段
2. 提取最适合短视频内容的片段,考虑:
- 最佳时长(严格控制在 15-60 秒)
- 能确保流畅过渡的自然起始和结束点
- 能保持观众注意力的吸引人节奏
- 视听协调以获得沉浸式体验
- 垂直格式兼容性和必要的调整
3. 提供每个片段的详细分析,包括:
- 精确的时间戳(开始时间 | 结束时间,MM:SS 格式)
- 对该片段为何吸引人的清晰描述
- 关于如何增强该片段以适应短视频内容的建议
- 基于吸引力潜力的重要性得分(1-10)
您的目标是识别在视觉上引人注目、情感上吸引人且针对短视频平台进行了完美优化的时刻。
"""
# 生成视频分析
response = agent.run(query, videos=[Video(content=video_file)])
# 创建输出目录
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# 提取和剪辑视频片段
def extract_segments(response_text):
import re
segments_pattern = r"\|\s*(\d+:\d+)\s*\|\s*(\d+:\d+)\s*\|\s*(.*?)\s*\|\s*(\d+)\s*\|"
segments: list[dict] = []
for match in re.finditer(segments_pattern, str(response_text)):
start_time = match.group(1)
end_time = match.group(2)
description = match.group(3)
score = int(match.group(4))
start_seconds = sum(x * int(t) for x, t in zip([60, 1], start_time.split(":")))
end_seconds = sum(x * int(t) for x, t in zip([60, 1], end_time.split(":")))
duration = end_seconds - start_seconds
if 15 <= duration <= 60 and score > 7:
output_path = output_dir / f"short_{len(segments) + 1}.mp4"
command = [
"ffmpeg",
"-ss",
str(start_seconds),
"-i",
video_path,
"-t",
str(duration),
"-vf",
"scale=1080:1920,setsar=1:1",
"-c:v",
"libx264",
"-c:a",
"aac",
"-y",
str(output_path),
]
try:
subprocess.run(command, check=True)
segments.append(
{"path": output_path, "description": description, "score": score}
)
except subprocess.CalledProcessError:
print(f"处理片段失败: {start_time} - {end_time}")
return segments
logger.debug(f"{response.content}")
# 处理片段
shorts = extract_segments(response.content)
# 打印结果
print("\n--- 生成的短视频 ---")
for short in shorts:
print(f"短视频位置: {short['path']}")
print(f"描述: {short['description']}")
print(f"吸引力得分: {short['score']}/10\n")
创建虚拟环境
打开 Terminal
并创建一个 python 虚拟环境。
python3 -m venv .venv
source .venv/bin/activate
设置您的 API 密钥
export GOOGLE_API_KEY=xxx
安装库
pip install -U opencv-python google-generativeai sqlalchemy ffmpeg-python agno
安装 ffmpeg
brew install ffmpeg
运行代理
python cookbook/agent_concepts/multimodal/video_to_shorts.py