Adding Captions to a Video
Choose your preferred language to add captions to videos using the ZapCap API
- Node.js
- Python
- cURL
import axios, { isAxiosError } from "axios";
import { createReadStream, createWriteStream } from "fs";
import FormData from "form-data";
// Get this from https://platform.zapcap.ai/dashboard/api-key
const API_KEY = "YOUR_API_KEY";
// Get this from /templates endpoint or https://platform.zapcap.ai/dashboard/templates
const TEMPLATE_ID = "your_template_id";
const API_BASE = "https://api.zapcap.ai";
const VIDEO_PATH = "/path/to/your/video.mp4"
export async function addCaptions(videoPath) {
try {
// 1. Upload video
console.log("Uploading video...");
const form = new FormData();
form.append("file", createReadStream(videoPath));
const uploadResponse = await axios.post(`${API_BASE}/videos`, form, {
headers: {
"x-api-key": API_KEY,
},
});
const videoId = uploadResponse.data.id;
console.log("Video uploaded, Video ID:", videoId);
// 2. Create task
console.log("Creating captioning task...");
const taskResponse = await axios.post(
`${API_BASE}/videos/${videoId}/task`,
{
templateId: TEMPLATE_ID,
// Read about it here: https://platform.zapcap.ai/docs//docs/guides/tasks#-transcript-approval
autoApprove: true,
language: "en",
},
{
headers: {
"x-api-key": API_KEY,
"Content-Type": "application/json",
},
}
);
const taskId = taskResponse.data.taskId;
console.log("Task created, Task ID:", taskId);
// 3. Poll for completion
console.log("Processing video...");
let attempts = 0;
while (true) {
const statusResponse = await axios.get(
`${API_BASE}/videos/${videoId}/task/${taskId}`,
{
headers: { "x-api-key": API_KEY },
}
);
const { status, downloadUrl, error } = statusResponse.data;
console.log("Status:", status);
if (status === "completed") {
// Download the video
console.log("Downloading captioned video...");
const videoResponse = await axios.get(downloadUrl, {
responseType: "stream",
});
const outputPath = "./captioned_video.mp4";
await new Promise<void>((resolve, reject) => {
const writeStream = createWriteStream(outputPath);
videoResponse.data.pipe(writeStream);
writeStream.on("finish", () => {
console.log("Video saved to:", outputPath);
resolve();
});
writeStream.on("error", reject);
});
console.log("Video saved to:", outputPath);
break;
} else if (status === "failed") {
throw new Error(`Task failed: ${error}`);
}
const delay = 2000;
await new Promise((resolve) => setTimeout(resolve, delay));
attempts++;
}
} catch (error) {
if (isAxiosError(error)) {
console.log(error.response?.data);
}
console.error("Error:", error.message);
}
}
const main = async () => {
await addCaptions(VIDEO_PATH);
};
main().then(() => process.exit(0));
import requests
import time
import math
# Get this from https://platform.zapcap.ai/dashboard/api-key
API_KEY = 'YOUR_API_KEY'
# Get this from /templates endpoint
TEMPLATE_ID = 'your_template_id'
API_BASE = 'https://api.zapcap.ai'
VIDEO_PATH="/path/to/your/video.mp4"
def add_captions(video_path):
try:
# 1. Upload video
print('Uploading video...')
with open(video_path, 'rb') as f:
upload_response = requests.post(
f'{API_BASE}/videos',
headers={'x-api-key': API_KEY},
files={'file': f}
)
upload_response.raise_for_status()
video_id = upload_response.json()['id']
print('Video uploaded, ID:', video_id)
# 2. Create task
print('Creating captioning task...')
task_response = requests.post(
f'{API_BASE}/videos/{video_id}/task',
headers={
'x-api-key': API_KEY,
'Content-Type': 'application/json'
},
json={
'templateId': TEMPLATE_ID,
'autoApprove': True,
'language': 'en'
}
)
task_response.raise_for_status()
task_id = task_response.json()['taskId']
print('Task created, ID:', task_id)
# 3. Poll for completion
print('Processing video...')
attempts = 0
while True:
status_response = requests.get(
f'{API_BASE}/videos/{video_id}/task/{task_id}',
headers={'x-api-key': API_KEY}
)
status_response.raise_for_status()
data = status_response.json()
status = data['status']
print('Status:', status)
if status == 'completed':
# Download the video
print('Downloading captioned video...')
download_response = requests.get(data['downloadUrl'])
download_response.raise_for_status()
output_path = 'captioned_video.mp4'
with open(output_path, 'wb') as f:
f.write(download_response.content)
print('Video saved to:', output_path)
break
elif status == 'failed':
raise Exception(f"Task failed: {data.get('error')}")
time.sleep(2)
attempts += 1
except Exception as e:
print('Error:', str(e))
add_captions(VIDEO_PATH)
#!/bin/bash
# Get this from https://platform.zapcap.ai/dashboard/api-key
API_KEY="YOUR_API_KEY"
# Get this from /templates endpoint
TEMPLATE_ID="your_template_id"
API_BASE="https://api.zapcap.ai"
VIDEO_PATH="/path/to/your/video.mp4"
check_status() {
local video_id=$1
local task_id=$2
local attempt=0
while true; do
echo "Checking status..."
response=$(curl -s -H "x-api-key: $API_KEY" \
"$API_BASE/videos/$video_id/task/$task_id")
status=$(echo $response | jq -r '.status')
echo "Status: $status"
if [ "$status" = "completed" ]; then
download_url=$(echo $response | jq -r '.downloadUrl')
echo "Downloading captioned video..."
curl -o captioned_video.mp4 "$download_url"
echo "Video saved to: captioned_video.mp4"
break
elif [ "$status" = "failed" ]; then
error=$(echo $response | jq -r '.error')
echo "Task failed: $error"
exit 1
fi
delay=2
sleep $delay
((attempt++))
done
}
# 1. Upload video
echo "Uploading video..."
upload_response=$(curl -s -X POST "$API_BASE/videos" \
-H "x-api-key: $API_KEY" \
-F "file=@$VIDEO_PATH")
video_id=$(echo $upload_response | jq -r '.id')
echo "Video uploaded, ID: $video_id"
# 2. Create task
echo "Creating captioning task..."
task_response=$(curl -s -X POST "$API_BASE/videos/$video_id/task" \
-H "x-api-key: $API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"templateId\": \"$TEMPLATE_ID\",
\"autoApprove\": true,
\"language\": \"en\"
}")
task_id=$(echo $task_response | jq -r '.taskId')
echo "Task created, ID: $task_id"
# 3. Poll for completion
echo "Processing video..."
check_status "$video_id" "$task_id"