SRTranslator

repository·master·Indexed 42 days ago

https://github.com/sinedie/srtranslator

A tool for translating .srt and .ass subtitle files using translation engines such as DeepL, TranslatePy, and PyDeepLX. It provides a Command Line Interface (CLI), a Python library for programmatic translation, and a GUI powered by flet. Features include support for custom translator classes, line wrapping, and batch processing of subtitle directories.

Tokens
4.4K
Snippets
13
Records
23
Agent score
53%

What's inside SRTranslator

  1. Create a custom translator class

    master

    To implement a custom translator, create a class that inherits from stranslator.translators.base.Translator. You must implement a translate method with the following signature:

    translate(self, text: str, source_language: str, destination_language: str)

    Optional features:

    • Constructor: You can define an __init__ method to handle setup (e.g., API keys).
    • max_char attribute: You can define a max_char: int attribute to specify the maximum character limit for a single translation request. This is useful for APIs with strict length constraints.

    Once defined, your custom translator can be used interchangeably with the built-in translators provided by the library.

    from stranslator.translators.base import Translator
    
    class CustomTranslator(Translator):
        # Optional: define character limit for the translator
        max_char: int = 5000
    
        def translate(self, text: str, source_language: str, destination_language: str):
            # Implement your translation logic here
            # e.g., calling an external API
            return "translated text"
  2. Build the SRTranslator GUI from source

    master

    The GUI is powered by flet. To package your own executable, navigate to the GUI folder and run the following commands:

    1. Install requirements and PyInstaller.
    2. Use flet pack to build the application.
    3. Copy the assets folder to the dist directory to ensure the UI renders correctly.
    cd ./GUI
    pip install -r requirements.txt
    pip install pyinstaller
    flet pack main.py
    cp -r ./assets ./dist/assets
  3. Translate subtitle files using a Python script

    master

    You can programmatically translate .srt or .ass files by importing the appropriate file class and a translator implementation.

    Supported translator imports include:

    • DeeplApi (requires API key)
    • DeeplTranslator (scraping based)
    • TranslatePy
    • PyDeepLX

    Workflow:

    1. Initialize the translator.
    2. Load the file using SrtFile or AssFile.
    3. Call .translate(translator, src_lang, dest_lang).
    4. (Optional) Call .wrap_lines() to improve subtitle formatting.
    5. Call .save(new_filepath) to write the result.
    6. Call translator.quit() to clean up resources.
    import os
    from srtranslator import SrtFile, AssFile
    from srtranslator.translators.deepl_scrap import DeeplTranslator
    
    filepath = "./filepath/to/srt"
    
    # Load
    sub = SrtFile(filepath)
    
    # Translate
    translator = DeeplTranslator()
    sub.translate(translator, "en", "es")
    
    # Formatting and Saving
    sub.wrap_lines()
    sub.save(f"{os.path.splitext(filepath)[0]}_translated.srt")
    
    # Cleanup
    translator.quit()
  4. Translation Progress Management

    master

    When a translation task is initiated, the application creates a TranslationProgress instance for each file. This object manages the lifecycle of a single file's translation:

    • Tracking: It tracks the filepath, translator_id, src_lang, dest_lang, and wrap_limit.
    • Progress Reporting: It provides a show_progress(total, progress) method to update a visual progress bar.
    • Cancellation: Users can cancel a specific file translation by clicking the close button, which sets self.cancelled = True and prevents further processing for that file.
    • Error Handling: If a translation fails, the progress bar turns red and the error is caught to prevent the entire batch from crashing.
  5. How the GUI handles file selection and translation batches

    master

    The GUI allows users to select either specific files or an entire directory.

    1. File Selection: Users can pick multiple .srt or .ass files.
    2. Directory Selection: If a directory is selected, the application recursively searches for all .srt and .ass files within that directory tree using glob.
    3. Batch Processing: Once the 'Translate' button is clicked, the handle_translation function iterates through all identified files, creating a TranslationProgress object for each and executing the translation sequentially.
  6. Configure the Wrap Lines Limit

    master
    The wrap_limit setting controls how lines are wrapped in the resulting subtitle file. In the GUI, this is managed via a counter component that allows users to increment or decrement the value. This value is passed to the sub.wrap_lines(self.wrap_limit) method during the translation process.
  7. Use the DeepL scraping translator in Python

    master

    The DeeplTranslator class allows you to translate text by scraping DeepL. If you do not provide a driver argument, the class will automatically create a new Firefox driver using geckodriver (installing it and adding it to the PATH if necessary) and set up free proxies to prevent IP bans.

    Use the .translate(text, source_language, destination_language) method to perform translations and ensure you call .quit() to clean up the driver instance.

    from srtranslator.translators.deepl_scrap import DeeplTranslator
    
    translator = DeeplTranslator(driver=driver)
    
    translator.translate(text, source_language, destination_language)
    
    translator.quit()