视频生成接口
NUWA 提供统一的视频生成接口,兼容 OpenAI SDK。支持以下多种主流模型:
OpenAI Sora 系列 :
sora-2sora-2-pro
Gemini Veo 系列 :
veo3.1veo3.1-proveo3.1-components
Sora 视频生成
- Python
- JavaScript
- TypeScript
from openai import OpenAI
import requests
from io import BytesIO
from PIL import Image
client = OpenAI(
base_url="https://api.nuwaapi.com/v1/",
api_key="API_KEY"
)
def prepare_image(image_url, save_path="input_ref.png"):
"""下载参考图片(可选)"""
if not image_url:
return None
resp = requests.get(image_url)
img = Image.open(BytesIO(resp.content)).convert("RGB")
img.save(save_path)
return save_path
def test_sora_model(prompt="测试视频:日落海边,一位画家在沙滩上作画,镜头从远景推进到近景"):
video_params = {
"model": "sora-2",
"prompt": prompt,
"seconds": "4", # 4/8/12 可选
"size": "720x1280", # 720x1280 或 1280x720
}
# 可选参考图,留空则不带参考图
image_url = "https://example.com/your_image.png"
ref_path = prepare_image(image_url) if image_url else None
if ref_path:
video_params["input_reference"] = open(ref_path, "rb")
video = client.videos.create(**video_params)
print("任务 ID:", video.id)
# 轮询状态
import time
while True:
info = client.videos.retrieve(video.id)
print("状态:", info.status)
if info.status in ("completed", "failed", "canceled"):
break
time.sleep(5)
if info.status == "completed":
filename = "sora_test_video.mp4"
resp = client.videos.download_content(video_id=video.id)
with open(filename, "wb") as f:
f.write(resp.read())
print(f"✅ 视频生成完成: {filename}")
else:
print(f"❌ 视频生成失败,状态: {info.status}")
if __name__ == "__main__":
test_sora_model()
const fs = require("fs");
const BASE_URL = "https://api.nuwaapi.com/v1";
const API_KEY = "sk-***";
const jsonHeaders = {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
};
const authHeaders = {
"Authorization": `Bearer ${API_KEY}`
};
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function main() {
const createRes = await fetch(`${BASE_URL}/videos`, {
method: "POST",
headers: jsonHeaders,
body: JSON.stringify({
model: "sora-2",
prompt: "测试视频:日落海边,一位画家在沙滩上作画,镜头从远景推进到近景",
seconds: "4",
size: "720x1280"
})
});
const task = await createRes.json();
console.log("任务 ID:", task.id);
if (!task.id) {
console.log("❌ 创建任务失败:", JSON.stringify(task, null, 2));
return;
}
const videoId = task.id;
let status = "";
while (true) {
const infoRes = await fetch(`${BASE_URL}/videos/${videoId}`, { headers: authHeaders });
const info = await infoRes.json();
status = info.status;
console.log("状态:", status);
if (["completed", "failed", "canceled"].includes(status)) break;
await sleep(5000);
}
if (status === "completed") {
const dlRes = await fetch(`${BASE_URL}/videos/${videoId}/content`, { headers: authHeaders });
const buffer = Buffer.from(await dlRes.arrayBuffer());
fs.writeFileSync("sora_test_video.mp4", buffer);
console.log("✅ 视频已保存到 sora_test_video.mp4");
} else {
console.log(`❌ 视频生成失败,状态: ${status}`);
}
}
main().catch(e => console.error("❌ 出错:", e.message));
import fs from "fs";
const BASE_URL = "https://api.nuwaapi.com/v1";
const API_KEY = "sk-***";
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${API_KEY}`
};
async function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main(): Promise<void> {
const createRes = await fetch(`${BASE_URL}/videos`, {
method: "POST",
headers,
body: JSON.stringify({
model: "sora-2",
prompt: "测试视频:日落海边,一位画家在沙滩上作画,镜头从远景推进到近景",
seconds: "4",
size: "720x1280"
})
});
const task = await createRes.json();
const videoId = task.id;
console.log("任务 ID:", videoId);
let status = "";
while (true) {
const infoRes = await fetch(`${BASE_URL}/videos/${videoId}`, { headers });
const info = await infoRes.json();
status = info.status;
console.log("状态:", status);
if (["completed", "failed", "canceled"].includes(status)) break;
await sleep(5000);
}
if (status === "completed") {
const dlRes = await fetch(`${BASE_URL}/videos/${videoId}/content`, { headers });
const buffer = Buffer.from(await dlRes.arrayBuffer());
fs.writeFileSync("sora_test_video.mp4", buffer);
console.log("✅ 视频已保存到 sora_test_video.mp4");
} else {
console.log(`❌ 视频生成失败,状态: ${status}`);
}
}
main().catch(e => console.error("❌ 出错:", e.message));
Veo 视频生成
- Python
- JavaScript
- TypeScript
- Curl
from openai import OpenAI
import re
import requests
client = OpenAI(
base_url="https://api.nuwaapi.com/v1/",
api_key="API_KEY"
)
prompt_text = "生成一个10秒的治愈风格小猫追蝴蝶的视频"
duration = "10s"
resolution = "1920x1080"
style = "治愈, 甜美"
fps = 30
video_format = "mp4"
completion = client.chat.completions.create(
model="veo3.1",
messages=[
{
"role": "system",
"content": (
"You are a video assistant. "
"You only respond with video generation task info. "
"Include prompt, duration, resolution, style, fps, format, and video URL when available."
)
},
{
"role": "user",
"content": (
f"生成视频:\n"
f"prompt: {prompt_text}\n"
f"duration: {duration}\n"
f"resolution: {resolution}\n"
f"style: {style}\n"
f"fps: {fps}\n"
f"format: {video_format}"
)
}
],
max_tokens=12800
)
response_text = completion.choices[0].message.content
print("Chat 输出:", response_text)
match = re.search(r'\\[▶️ 在线观看\\]\\((.*?)\\)', response_text or "")
video_url = match.group(1) if match else None
print("视频 URL:", video_url if video_url else "未找到视频 URL")
if video_url:
r = requests.get(video_url)
filename = f"output.{video_format}"
with open(filename, "wb") as f:
f.write(r.content)
print(f"视频已保存为 {filename}")
const fs = require("fs");
async function main() {
const response = await fetch("https://api.nuwaapi.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "sk-***"
},
body: JSON.stringify({
model: "veo3.1",
max_tokens: 12800,
messages: [
{
role: "system",
content: "You are a video assistant. You only respond with video generation task info. Include prompt, duration, resolution, style, fps, format, and video URL when available."
},
{
role: "user",
content: "生成视频:\nprompt: 生成一个10秒的治愈风格小猫追蝴蝶的视频\nduration: 10s\nresolution: 1920x1080\nstyle: 治愈, 甜美\nfps: 30\nformat: mp4"
}
]
})
});
const data = await response.json();
const responseText = data.choices?.[0]?.message?.content ?? "";
console.log("Chat 输出:", responseText);
const match = responseText.match(/\[.*?\]\((https?:\/\/[^\)]+)\)/);
const videoUrl = match ? match[1] : null;
console.log("视频 URL:", videoUrl ?? "未找到视频 URL");
if (videoUrl) {
const res = await fetch(videoUrl);
fs.writeFileSync("output.mp4", Buffer.from(await res.arrayBuffer()));
console.log("✅ 视频已保存为 output.mp4");
}
}
main().catch(e => console.error("❌ 出错:", e.message));
import OpenAI from "openai";
import fs from "fs";
const client = new OpenAI({
apiKey: "sk-***",
baseURL: "https://api.nuwaapi.com/v1"
});
async function main(): Promise<void> {
const completion = await client.chat.completions.create({
model: "veo3.1",
max_tokens: 12800,
messages: [
{
role: "system",
content: "You are a video assistant. You only respond with video generation task info. Include prompt, duration, resolution, style, fps, format, and video URL when available."
},
{
role: "user",
content: "生成视频:\nprompt: 生成一个10秒的治愈风格小猫追蝴蝶的视频\nduration: 10s\nresolution: 1920x1080\nstyle: 治愈, 甜美\nfps: 30\nformat: mp4"
}
]
});
const responseText = completion.choices[0].message.content ?? "";
console.log("Chat 输出:", responseText);
const match = responseText.match(/\[.*?\]\((https?:\/\/[^\)]+)\)/);
const videoUrl = match ? match[1] : null;
console.log("视频 URL:", videoUrl ?? "未找到视频 URL");
if (videoUrl) {
const res = await fetch(videoUrl);
fs.writeFileSync("output.mp4", Buffer.from(await res.arrayBuffer()));
console.log("✅ 视频已保存为 output.mp4");
}
}
main().catch(e => console.error("❌ 出错:", e.message));
#!/bin/bash
curl -s https://api.nuwaapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: sk-***" \
-d '{
"model": "veo3.1",
"max_tokens": 12800,
"messages": [
{
"role": "system",
"content": "You are a video assistant. You only respond with video generation task info. Include prompt, duration, resolution, style, fps, format, and video URL when available."
},
{
"role": "user",
"content": "Generate video:\nprompt: A cute cat chasing a butterfly, healing style\nduration: 10s\nresolution: 1920x1080\nstyle: healing, sweet\nfps: 30\nformat: mp4"
}
]
}' -o response.json
VIDEO_URL=$(cat response.json | python -c "
import sys, json, re
data = json.load(sys.stdin)
text = data['choices'][0]['message']['content']
match = re.search(r'\[.*?\]\((https?://[^\)]+)\)', text)
print(match.group(1) if match else '')
" | tr -d '\r' | tail -1)
echo "Video URL: $VIDEO_URL"
if [ -n "$VIDEO_URL" ]; then
curl -s "$VIDEO_URL" -o output.mp4
echo "✅ Video saved to output.mp4"
else
echo "❌ No video URL found"
fi