> ## Documentation Index
> Fetch the complete documentation index at: https://developers.autocaption.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Examples

> A few examples of scripts

<CodeGroup>
  ```javascript Node.JS theme={null}
  import axios from 'axios';
  import FormData from 'form-data';
  import fs from 'fs';
  import path from 'path';

  const API_ENDPOINT = 'https://api.autocaption.io/v1'
  const API_KEY = 'YOUR_API_KEY'

  const videoName = 'video.mp4'
  const videoLang = 'fr'
  const videoPath = path.join('./', videoName);

  const axiosInstance = axios.create({
  baseURL: API_ENDPOINT
  });

  axiosInstance.defaults.headers.common['x-api-key'] = API_KEY;

  const video = fs.createReadStream(videoPath);

  // Get signed url to upload video
  const getSignedUrlData = async () => {
  return axiosInstance.get(`/signedUrl?file=${videoName}`).then(res => res.data);
  }

  // Upload video to signed url
  const uploadVideo = async (url, fields) => {
  const formData = new FormData();
  for (const [key, value] of Object.entries(fields)) {
      formData.append(key, value);
  }
  formData.append('file', video);
  await axios.post(url, formData, {
      headers: {
          'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
      }
  }).catch(err => console.log(err));
  }

  // Transcript video
  const transcriptVideo = async (fileKey, lang) => {
  return axiosInstance.post('/transcript', {
      input: fileKey,
      language: lang
  }).then(res => res.data);
  }

  // Get transcript status
  const getTranscriptStatus = async (jobId) => {
  return axiosInstance.get(`/transcript/${jobId}`).then(res => res.data).catch(err => err.response.data);
  }

  // Get template by id
  const getTemplateById = async (id) => {
  return axiosInstance.get(`/templates/${id}`).then(res => res.data);
  }

  // Generate video
  const generateVideo = async (file, config, words) => {
  return axiosInstance.post('/generate', {
      input: file,
      config,
      words
  }).then(res => res.data);
  }

  // Get fonts list
  const getFontsList = async () => {
  return axiosInstance.get(`/fonts?lang=${videoLang}`).then(res => res.data);
  }

  const main = async () => {
  try {
      const { file, url, fields } = await getSignedUrlData();
      await uploadVideo(url, fields);
      console.log('file uploaded')
      const { job_id } = await transcriptVideo(file, videoLang);

      // Initial check without delay
      let transcriptResponse = await getTranscriptStatus(job_id);

      // Loop until the transcript is ready or an error occurs
      while (transcriptResponse.status !== 'COMPLETED') {
          if (transcriptResponse.status == 'FAILED') {
              throw new Error('Transcription failed'); // Throws an error to exit the loop and catch block
          }

          await new Promise(resolve => setTimeout(resolve, 5000)); // Wait for 5 seconds
          transcriptResponse = await getTranscriptStatus(job_id); // Update the response
      }

      console.log('Transcript ready');

      // Get the template DEFAULT
      const { config } = await getTemplateById('0');

      /* 
          - If the template doesn't have a font, get the list of fonts and use the first one
          /!\ Set a value to the config.font otherwise it will throw an error during the video generation
      */
      if (config.font == undefined) {
          const fonts = await getFontsList();
          config.font = fonts[0];
      }

      /* 
          - Instead of a custom template, the default templates don't have the sizes defined, so we need to define them.
          /!\ Set a value to the config.sizes.fontSize otherwise it will throw an error during the video generation
      */
      config.sizes = {
          fontSize: 56,
          strokeSize: 15,
          //...
      };

      // Generate the video and wait the download url - Can take a few minutes
      console.log('Generating video...');
      const { download_url } = await generateVideo(file, config, transcriptResponse.words);
      console.log(download_url);
  } catch (error) {
      console.error("An error occurred:", error);
  }
  };

  main();
  ```

  ```python Python theme={null}
  import requests
  from requests_toolbelt.multipart.encoder import MultipartEncoder
  import os
  import time

  API_ENDPOINT = 'https://api.autocaption.io/v1'
  API_KEY = 'YOUR_API_KEY'

  video_name = 'video.mp4'
  video_lang = 'fr'
  video_path = os.path.join('./', video_name)

  session = requests.Session()
  session.headers.update({'x-api-key': API_KEY})

  # Get signed url to upload video
  def get_signed_url_data():
      return session.get(f'{API_ENDPOINT}/signedUrl?file={video_name}').json()

  # Upload video to signed url
  def upload_video(url, fields):
      with open(video_path, 'rb') as f:
          fields['file'] = (video_name, f, 'video/mp4')
          m = MultipartEncoder(fields=fields)
          response = requests.post(url, data=m, headers={'Content-Type': m.content_type})
          print(response.text)
          response.raise_for_status()

  # Transcript video
  def transcript_video(file_key, lang):
      return session.post(f'{API_ENDPOINT}/transcript', json={
          'input': file_key,
          'language': lang
      }).json()

  # Get transcript status
  def get_transcript_status(job_id):
      try:
          return session.get(f'{API_ENDPOINT}/transcript/{job_id}').json()
      except requests.exceptions.RequestException as e:
          return e.response.json()

  # Get template by id
  def get_template_by_id(id):
      return session.get(f'{API_ENDPOINT}/templates/{id}').json()

  # Generate video
  def generate_video(file, config, words):
      return session.post(f'{API_ENDPOINT}/generate', json={
          'input': file,
          'config': config,
          'words': words
      }).json()

  # Get fonts list
  def get_fonts_list():
      return session.get(f'{API_ENDPOINT}/fonts?lang={video_lang}').json()

  def main():
      try:
          signed_url_data = get_signed_url_data()
          file = signed_url_data['file']
          url = signed_url_data['url']
          fields = signed_url_data['fields']
          upload_video(url, fields)
          print('file uploaded ' + file)
          transcript_response = transcript_video(file, video_lang)
          job_id = transcript_response['job_id']

          # Initial check without delay
          transcript_status = get_transcript_status(job_id)

          # Loop until the transcript is ready or an error occurs
          while 'status' not in transcript_status or transcript_status['status'] != 'COMPLETED':
              if 'status' in transcript_status and transcript_status['status'] == 'FAILED':
                  raise Exception('Transcription failed')  # Throws an error to exit the loop and catch block
              time.sleep(5)  # Wait for 5 seconds
              transcript_status = get_transcript_status(job_id)  # Update the response

          print('Transcript ready')

          # Get the template DEFAULT
          template_response = get_template_by_id('0')
          config = template_response['config']

          # If the template doesn't have a font, get the list of fonts and use the first one
          if 'font' not in config:
              fonts = get_fonts_list()
              config['font'] = fonts[0]

          # Set values for config.sizes
          config['sizes'] = {
              'fontSize': 56,
              'strokeSize': 15,
              #...
          }

          # Generate the video and wait the download url - Can take a few minutes
          print('Generating video...')
          video_generation_response = generate_video(file, config, transcript_status['words'])
          download_url = video_generation_response['download_url']
          print(download_url)
      except Exception as error:
          print("An error occurred:", error)

  if __name__ == '__main__':
      main()
  ```
</CodeGroup>
