Skip to content

Commit

Permalink
fix: Add source_url as parameter and modify the structure
Browse files Browse the repository at this point in the history
  • Loading branch information
devman0129 committed May 6, 2024
1 parent e37c460 commit e8627d5
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 79 deletions.
44 changes: 3 additions & 41 deletions examples/dubbing/python/create_a_dub_from_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from elevenlabs.client import ElevenLabs
from typing import Optional

from dubbing_utils import wait_for_dubbing_completion, download_dubbed_file

# Load environment variables
load_dotenv()

Expand All @@ -20,7 +22,6 @@

def create_dub_from_file(
input_file_path: str,
output_file_path: str,
file_format: str,
source_language: str,
target_language: str,
Expand All @@ -30,7 +31,6 @@ def create_dub_from_file(
Args:
input_file_path (str): The file path of the audio or video to dub.
output_file_path (str): The file path to save the dubbed file.
file_format (str): The file format of the input file.
source_language (str): The language of the input file.
target_language (str): The target language to dub into.
Expand All @@ -53,45 +53,7 @@ def create_dub_from_file(

dubbing_id = response.dubbing_id
if wait_for_dubbing_completion(dubbing_id, target_language):
with open(output_file_path, "wb") as file:
file.write(response.content)
print(f"Dubbing complete and saved to {output_file_path}.")
output_file_path = download_dubbed_file(dubbing_id, target_language)
return output_file_path
else:
return None


def wait_for_dubbing_completion(dubbing_id: str, language_code: str) -> bool:
"""
Waits for the dubbing process to complete by periodically checking the status.
Args:
dubbing_id (str): The dubbing project id.
language_code (str): The language code of the target language.
Returns:
bool: True if the dubbing is successful, False otherwise.
"""
MAX_ATTEMPTS = 120
CHECK_INTERVAL = 10 # In seconds

for _ in range(MAX_ATTEMPTS):
metadata = client.dubbing.get_dubbing_project_metadata(dubbing_id=dubbing_id)
if metadata.status == "dubbed":
response = client.dubbing.get_dubbed_file(
dubbing_id=dubbing_id, language_code=language_code
)
return response.status_code == 200
elif metadata.status == "dubbing":
print(
"Dubbing in progress... Will check status again in",
CHECK_INTERVAL,
"seconds.",
)
time.sleep(CHECK_INTERVAL)
else:
print("Dubbing failed:", metadata.error_message)
return False

print("Dubbing timed out")
return False
64 changes: 27 additions & 37 deletions examples/dubbing/python/create_a_dub_from_url.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,27 @@
import os
import time
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs
from typing import Optional
from pytube import YouTube

from dubbing_utils import wait_for_dubbing_completion, download_dubbed_file

def download_youtube_video(video_url: str, download_path: str) -> str:
"""
Downloads a YouTube video at the highest resolution available to a specified path.
Args:
video_url (str): The URL of the YouTube video to download.
download_path (str): The directory path where the video will be downloaded.
# Load environment variables
load_dotenv()

Returns:
str: The file path to the downloaded video.
"""
yt = YouTube(video_url)
stream = yt.streams.get_highest_resolution()

if not os.path.exists(download_path):
os.makedirs(download_path)
# Retrieve the API key
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
if not ELEVENLABS_API_KEY:
raise ValueError(
"ELEVENLABS_API_KEY environment variable not found. "
"Please set the API key in your environment variables."
)

downloaded_file_path = stream.download(output_path=download_path)
return downloaded_file_path
client = ElevenLabs(api_key=ELEVENLABS_API_KEY)


def create_dub_from_url(
source_url: str,
output_file_path: str,
file_format: str,
source_language: str,
target_language: str,
) -> Optional[str]:
Expand All @@ -36,29 +30,25 @@ def create_dub_from_url(
Args:
source_url (str): The URL of the source video to download and dub.
output_file_path (str): The file path to save the dubbed file.
file_format (str): The file format of the input file (used for dubbing).
source_language (str): The language of the source video.
target_language (str): The target language to dub into.
Returns:
Optional[str]: The file path of the dubbed file or None if operation failed.
"""
download_path = "downloads"
input_file_path = download_youtube_video(source_url, download_path)

# Assuming `create_a_dub_from_file` is imported from some other module as before
from create_a_dub_from_file import create_dub_from_file

dubbed_result = create_dub_from_file(
input_file_path=input_file_path,
output_file_path=output_file_path,
file_format=file_format,
source_language=source_language,
target_language=target_language,
response = client.dubbing.dub_a_video_or_an_audio_file(
source_url=source_url,
target_lang=target_language,
mode="automatic",
source_lang=source_language,
num_speakers=1,
watermark=True, # reduces the characters used
)

# Optionally remove the downloaded file after dubbing
os.remove(input_file_path)

return dubbed_result
dubbing_id = response.dubbing_id
if wait_for_dubbing_completion(dubbing_id, target_language):
output_file_path = download_dubbed_file(dubbing_id, target_language)
return output_file_path
else:
return None
72 changes: 72 additions & 0 deletions examples/dubbing/python/dubbing_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import os
import logging
import time
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs

# Load environment variables
load_dotenv()

# Retrieve the API key
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
if not ELEVENLABS_API_KEY:
raise ValueError(
"ELEVENLABS_API_KEY environment variable not found. "
"Please set the API key in your environment variables."
)

client = ElevenLabs(api_key=ELEVENLABS_API_KEY)


def download_dubbed_file(dubbing_id: str, language_code: str) -> str:
"""
Downloads the dubbed file for a given dubbing ID and language code.
Args:
dubbing_id: The ID of the dubbing project.
language_code: The language code for the dubbing.
Returns:
The file path to the downloaded dubbed file.
"""
dir_path = f"data/{dubbing_id}"
os.makedirs(dir_path, exist_ok=True)

file_path = f"{dir_path}/{language_code}.mp4"
with open(file_path, "wb") as file:
for chunk in client.dubbing.get_dubbed_file(dubbing_id, language_code):
file.write(chunk)

return file_path


def wait_for_dubbing_completion(dubbing_id: str) -> bool:
"""
Waits for the dubbing process to complete by periodically checking the status.
Args:
dubbing_id (str): The dubbing project id.
Returns:
bool: True if the dubbing is successful, False otherwise.
"""
MAX_ATTEMPTS = 120
CHECK_INTERVAL = 10 # In seconds

for _ in range(MAX_ATTEMPTS):
metadata = client.dubbing.get_dubbing_project_metadata(dubbing_id)
if metadata.status == "dubbed":
return True
elif metadata.status == "dubbing":
print(
"Dubbing in progress... Will check status again in",
CHECK_INTERVAL,
"seconds.",
)
time.sleep(CHECK_INTERVAL)
else:
print("Dubbing failed:", metadata.error_message)
return False

print("Dubbing timed out")
return False
1 change: 0 additions & 1 deletion examples/dubbing/python/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
def main():
result = create_dub_from_file(
"../example_speech.mp3", # Input file path
"dubbed_file.mp4", # Output file path
"audio/mpeg", # File format
"en", # Source language
"es", # Target language
Expand Down

0 comments on commit e8627d5

Please sign in to comment.