Text to Video with Save Project

This example demonstrates how to create a video storyboard and save it as an editable project in your Pictory account. This allows you to later edit the video through the Pictory web interface.

Overview

This example covers:

  • Getting an access token
  • Creating a video storyboard and saving it as a project
  • Accessing saved projects for future editing
  • Monitoring job status and retrieving the final video

Node.js Example

Prerequisites

npm install axios

Complete Code

import axios from "axios";

const API_BASE_URL = "https://api.pictory.ai/pictoryapis";
const CLIENT_ID = "YOUR_CLIENT_ID";
const CLIENT_SECRET = "YOUR_CLIENT_SECRET";

const STORY_TEXT =
  "AI is poised to significantly impact educators and course creators on social media. By automating tasks like content generation, visual design, and video editing, AI will save time and enhance consistency.";

async function createTextToVideoAndSaveProject() {
  try {
    // Step 1: Get Access Token
    console.log("Step 1: Getting access token...");
    const tokenResponse = await axios.post(
      `${API_BASE_URL}/v1/oauth2/token`,
      {
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );

    const accessToken = tokenResponse.data.access_token;
    console.log("Access token obtained successfully");
    console.log("Token expires in:", tokenResponse.data.expires_in, "seconds\n");

    // Step 2: Create Video and Save as Project
    console.log("Step 2: Creating video storyboard and saving as project...");
    const storyboardResponse = await axios.post(
      `${API_BASE_URL}/v2/video/storyboard`,
      {
        videoName: "my_saved_project",
        saveProject: true, // Set to true to save the project for future editing
        scenes: [
          {
            story: STORY_TEXT,
            createSceneOnNewLine: true,
            createSceneOnEndOfSentence: true,
          },
        ],
      },
      {
        headers: {
          "Content-Type": "application/json",
          Authorization: accessToken,
        },
      }
    );

    const renderJobId = storyboardResponse.data.data.jobId;
    console.log("Storyboard with saved project job created");
    console.log("Job ID:", renderJobId, "\n");

    // Step 3: Monitor Job Status
    console.log("Step 3: Monitoring job status...");
    let jobCompleted = false;
    let jobResult = null;

    while (!jobCompleted) {
      const jobStatusResponse = await axios.get(`${API_BASE_URL}/v1/jobs/${renderJobId}`, {
        headers: {
          Authorization: accessToken,
        },
      });

      const status = jobStatusResponse.data.data.status;
      console.log("Current status:", status);

      if (status === "completed") {
        jobCompleted = true;
        jobResult = jobStatusResponse.data;
        console.log("\nStoryboard created and project saved successfully!");
        console.log("Project URL:", jobResult.data.projectUrl);
        console.log("Preview URL:", jobResult.data.previewUrl);
        console.log("\nYou can now edit this project in your Pictory account.");
      } else if (status === "failed") {
        throw new Error("Job failed: " + JSON.stringify(jobStatusResponse.data));
      } else {
        // Wait 5 seconds before checking again
        await new Promise(resolve => setTimeout(resolve, 5000));
      }
    }

    return jobResult;
  } catch (error) {
    console.error("Error:", error.response?.data || error.message);
    throw error;
  }
}

// Run the function
createTextToVideoAndSaveProject();

Python Example

Prerequisites

pip install requests

Complete Code

import requests
import time
import json

API_BASE_URL = 'https://api.pictory.ai/pictoryapis'
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'

STORY_TEXT = "AI is poised to significantly impact educators and course creators on social media. By automating tasks like content generation, visual design, and video editing, AI will save time and enhance consistency."

def create_text_to_video_and_save_project():
    try:
        # Step 1: Get Access Token
        print('Step 1: Getting access token...')
        token_response = requests.post(
            f'{API_BASE_URL}/v1/oauth2/token',
            json={
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET
            },
            headers={
                'Content-Type': 'application/json'
            }
        )
        token_response.raise_for_status()

        access_token = token_response.json()['access_token']
        print('Access token obtained successfully')
        print(f"Token expires in: {token_response.json()['expires_in']} seconds\n")

        # Step 2: Create Video and Save as Project
        print('Step 2: Creating storyboard and saving as project...')
        storyboard_response = requests.post(
            f'{API_BASE_URL}/v2/video/storyboard',
            json={
                'videoName': 'my_saved_project',
                'saveProject': True,  # Set to True to save the project for future editing
                'scenes': [
                    {
                        'story': STORY_TEXT,
                        'createSceneOnNewLine': True,
                        'createSceneOnEndOfSentence': True
                    }
                ]
            },
            headers={
                'Content-Type': 'application/json',
                'Authorization': access_token
            }
        )
        storyboard_response.raise_for_status()

        render_job_id = storyboard_response.json()['data']['jobId']
        print('Storyboard with saved project job created')
        print(f'Job ID: {render_job_id}\n')

        # Step 3: Monitor Job Status
        print('Step 3: Monitoring job status...')
        job_completed = False
        job_result = None

        while not job_completed:
            job_status_response = requests.get(
                f'{API_BASE_URL}/v1/jobs/{render_job_id}',
                headers={
                    'Authorization': access_token
                }
            )
            job_status_response.raise_for_status()

            status = job_status_response.json()['data']['status']
            print(f'Current status: {status}')

            if status == 'completed':
                job_completed = True
                job_result = job_status_response.json()
                print('\nStoryboard created and project saved successfully!')
                print(f"Project URL: {job_result['data']['projectUrl']}")
                print(f"Preview URL: {job_result['data'].get('previewUrl')}")
                print('\nYou can now edit this project in your Pictory account.')
            elif status == 'failed':
                raise Exception(f"Job failed: {json.dumps(job_status_response.json())}")
            else:
                # Wait 5 seconds before checking again
                time.sleep(5)

        return job_result

    except requests.exceptions.RequestException as error:
        print(f'Error: {error}')
        if hasattr(error, 'response') and error.response is not None:
            print(f'Response: {error.response.text}')
        raise

# Run the function
if __name__ == '__main__':
    create_text_to_video_and_save_project()

Key Parameters

  • saveProject: Boolean value
    • true - Saves the video as an editable project in your Pictory account
    • false or omitted - Creates only the storyboard preview without saving the project

Difference Between Saved and Non-Saved Projects

With saveProject: true

  • Video is rendered and available for download
  • Project is saved in your Pictory account
  • You can edit the project later through the web interface
  • You can make changes to scenes, text, visuals, etc.
  • Useful for iterative work and future modifications

With saveProject: false (or omitted)

  • No editable project is saved
  • Cannot be edited later through the web interface
  • Useful for one-time video generation

Use Cases

Save Project When:

  • You want to review and manually adjust the video
  • The video may need updates in the future
  • You're creating templates for repeated use
  • You want to experiment with different settings
  • Collaborative work requiring review and approval

Don't Save Project When:

  • Generating large volumes of videos programmatically
  • Videos are final and won't need editing
  • Faster processing is a priority

Accessing Saved Projects

After saving a project:

  1. Log in to your Pictory account
  2. Navigate to "My Projects"
  3. Find the project by name (videoName)
  4. Click to open and edit in the Pictory editor
  5. Make any desired changes
  6. Re-render the video with your edits

Response

The API returns:

  • Job ID for monitoring progress
  • Project URL if the project was saved
  • Preview URL when completed

Notes

  • Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual API credentials
  • The videoName helps you identify the project in your account