def get_headers():
return {
"Accept": "application/json",
"Content-Type": "application/json",
"X-Api-Key": API_KEY
}
...
def create_avatar_group(name, image_key):
...
payload = {"name": name, "image_key": image_key}
...
response = requests.post("https://api.heygen.com/v2/photo_avatar/avatar_group/create",
headers=get_headers(), json=payload)
When these functions are called, this snippet of code tells HeyGen to create a new avatar group.
def train_avatar_group(group_id):
...
payload = {"group_id": group_id}
...
response = requests.post("https://api.heygen.com/v2/photo_avatar/train",
headers=get_headers(), json=payload)
if response.status_code == 200:
data = response.json()
if data.get("error") is None:
return True, "Training started successfully"
else:
return False, f"Error starting training: {data.get('error')}"
elif response.status_code == 400:
...
return False, "Unable to train avatar. Please check the status of your API key (there are usage limits)."
...
When this function is called, this snippet of code tells HeyGen to train the avatar with the given group_id.
def generate_heygen_video(character_id, text, selected_voice_id):
headers = {
"Content-Type": "application/json",
"X-Api-Key": API_KEY
}
character_config = {
"type": "talking_photo",
"talking_photo_id": character_id
}
payload = {
"video_inputs": [
{
"character": character_config,
"voice": {
"type": "text",
"input_text": text,
"voice_id": selected_voice_id
},
"background": {"type": "color", "value": "#ffffff"}
}
],
"dimension": {"width": 720, "height": 406},
...
}
...
response = requests.post(
"https://api.heygen.com/v2/video/generate",
headers=headers,
json=payload
)
response_json = response.json()
...
video_id = response_json["data"].get("video_id")
...
while True:
time.sleep(0.5)
status_response = requests.get(
f"https://api.heygen.com/v1/video_status.get?video_id={video_id}",
headers=headers
)
if status_response.status_code != 200:
continue
status_data = status_response.json()
if status_data.get("data", {}).get("status") == "completed":
video_url = status_data["data"].get("video_url")
return video_url
...
when the generate_heygen_video function is called (with the photo ID, text that must be spoken, and voice ID passed in), a request will be made to the HeyGen API for the video to be generated.