import os import requests import time from dotenv import load_dotenv load_dotenv() # Get HeyGen token TOKEN = os.getenv("HEY_GEN_TOKEN") # POST TO CREATE VIDEO CREATE_VIDEO_URL = 'https://api.heygen.com/v1/video.generate' GET_VIDEO_URL = 'https://api.heygen.com/v1/video_status.get' POST_HEADER = { 'X-Api-Key': TOKEN, 'Content-Type': 'application/json' } GET_HEADER = { 'X-Api-Key': TOKEN } def create_video(text): # POST TO CREATE VIDEO data = { "background": "#ffffff", "clips": [ { "avatar_id": "Mido-lite-20221128", "avatar_style": "normal", "input_text": text, "offset": { "x": 0, "y": 0 }, "scale": 1, "voice_id": "ccb30e87c6b34ca8941f88352c71612d" } ], "ratio": "16:9", "test": True, "version": "v1alpha" } response = requests.post(CREATE_VIDEO_URL, headers=POST_HEADER, json=data) print(response.status_code) print(response.json()) # GET TO CHECK STATUS AND GET VIDEO WHEN READY video_id = response.json()["data"]["video_id"] params = { 'video_id': response.json()["data"]["video_id"] } response = {} status = "processing" error = None while status != "completed" and error is None: response = requests.get(GET_VIDEO_URL, headers=GET_HEADER, params=params) response_data = response.json() status = response_data["data"]["status"] error = response_data["data"]["error"] if status != "completed" and error is None: print(f"Status: {status}") time.sleep(5) # Wait for 5 second before the next request print(response.status_code) print(response.json()) # DOWNLOAD VIDEO download_url = response.json()['data']['video_url'] output_directory = 'download-video/' output_filename = video_id + '.mp4' response = requests.get(download_url) if response.status_code == 200: os.makedirs(output_directory, exist_ok=True) # Create the directory if it doesn't exist output_path = os.path.join(output_directory, output_filename) with open(output_path, 'wb') as f: f.write(response.content) print(f"File '{output_filename}' downloaded successfully.") return output_filename else: print(f"Failed to download file. Status code: {response.status_code}") return None