Creating/downloading videos from Azure OpenAI Sora by PowerShell/API

Finally the OpenAI Sora model is released in preview for Azure AI Foundry. You can read more about it here. Sora is a text to video model that lets you input a description of a scene and it generates a video from it.

Using the Video playground in AI Foundry its super easy to generate videos and download them. Maybe you want to automate the video creation or create som sort of application using this model? There is a great Learn article here that describes how you can create and download videos using Python.
I don’t know Python, so therefore I have convert/created the script for use in PowerShell. The script first sends the prompt to start the video creation job, then it continuously checks the status of the job and at last save the video as a mp4 file on your computer.

Before you try out the script, you need to have a project in Azure AI Foundry, and go to the Video playground.

Click on Deploy Now

Select Sora and click Confirm. Next click Create resource and deploy.

After the model is deployed, go back to the Overview menu of Azure AI Foundry, and copy the API Key and Azure OpenAI endpoint.

Here is the PowerShell script you need to create and download videos with the API:

# Set environment variables or edit the corresponding values here.
$endpoint = "XXXXXXXXXXXXXXXXX"
$api_key = "XXXXXXXXXXXXXXXXX"
$api_version = 'preview'
$headers = @{
"api-key" = $api_key
"Content-Type" = "application/json"
}
# 1. Create a video generation job
# Videoresolutions to choose from: 480x480, 480x854, 854x480, 720x720, 720x1280, 1280x720, 1080x1080, 1080x1920, 1920x1080.
$create_url = "$endpoint/openai/v1/video/generations/jobs?api-version=$api_version"
$body = @"
{
"prompt": "Detailed close up view of a astronauts eyes framed by a knitted fabric mask",
"width": 1920,
"height": 1080,
"n_seconds": 15,
"model": "sora"
}
"@
$response = Invoke-RestMethod -Uri $create_url -Method Post -Headers $headers -Body $body -ContentType "application/json"
# 2. Poll for job status
$status_url = "$endpoint/openai/v1/video/generations/jobs/$($response.id)?api-version=$api_version"
$status_reponse = Invoke-RestMethod -Uri $status_url -Method Get -Headers $headers -ContentType "application/json"
while ($status_reponse.status -ne "succeeded" -and $status_reponse.status -ne "failed" -and $status_reponse.status -ne "cancelled") {
Start-Sleep -Seconds 5 # Wait before polling again
$status_reponse = Invoke-RestMethod -Uri $status_url -Method Get -Headers $headers -ContentType "application/json"
Write-Host "Job status: $($status_reponse.status)"
}
# 3. Download the generated video
$video_url = "$endpoint/openai/v1/video/generations/$($status_reponse.generations.id)/content/video?api-version=$api_version"
Invoke-RestMethod -Uri $video_url -Method Get -Headers $headers -OutFile "output.mp4"

Leave a comment