This script, crafted with care by Tharindu Madushan, leverages the powerful googletrans library to seamlessly translate subtitles from one language to another. It's designed to handle subtitle files (.srt), translating their content while preserving the original timing and formatting.
- Automatic Translation: Utilizes
googletransfor effortless translation across languages supported by Google Translate. - Retries on Failure: Built-in retry logic to handle temporary network issues or API limitations.
- Progress Display: Utilizes
tqdmto show progress during translation, providing a visual indication of completion. - Flexible Language Selection: Easily target translations to a specific language by modifying the destination language code.
To run this script, you'll need Python installed on your system along with the following libraries:
googletransfor translation capabilities.tqdmfor progress bar visualization.refor regular expression support, which is included with Python.
First, ensure you have Python installed. Then, install the required packages using pip:
pip install googletrans==4.0.0-rc1 tqdmNote: The version of
googletransmight change. Please check for the latest version compatible with this script.
-
Prepare Your Subtitle File: Ensure your subtitle file is in the
.srtformat and encoded in UTF-8 to avoid any encoding issues. -
Set the Input and Output Paths: Modify the
input_file_pathandoutput_file_pathvariables in the script to point to your source subtitle file and the desired output file location, respectively. -
Run the Script: Execute the script with Python. Example:
python subtitle_translator.py- The script initializes a
Translatorobject fromgoogletrans. - It reads the source subtitle file line by line, identifying timestamps and text.
- Non-timestamp lines are translated using the
safe_translatefunction, which retries failed translations up to a specified limit before giving up and leaving the text as-is. - The translated text, along with unaltered timestamps, are written to the output file, preserving the original file's structure.
- Language Selection: Change the
destparameter in thesafe_translatefunction to translate to a different language (use ISO language codes, e.g., 'en' for English, 'si' for Sinhala). - Retry Logic: Adjust the
retriesanddelayparameters in thesafe_translatefunction to change the retry behavior.
Thanks to the developers of googletrans and tqdm for their fantastic libraries that made this script possible.