### Install Project Dependencies with Poetry Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/DEVELOPMENT.md Installs all project dependencies defined in the 'pyproject.toml' file using Poetry. Ensure Poetry is installed globally. ```shell poetry install ``` -------------------------------- ### Install epub-translator v0.1.1 using pip Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.1.md Provides instructions for installing the epub-translator version 0.1.1 using pip. It also includes a command to upgrade to the latest version if already installed. ```bash pip install epub-translator==0.1.1 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Complete epub-translator Pipeline Example with Advanced Features Source: https://context7.com/oomol-lab/epub-translator/llms.txt This comprehensive Python example integrates multiple features of the epub-translator library, including LLM configuration with caching and logging, concurrent translation, progress tracking, and detailed error handling for both recoverable and critical failures. ```python from epub_translator import LLM, translate, language, SubmitKind, FillFailedEvent from tqdm import tqdm import time # Configure LLM with caching and logging llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", cache_path="./translation_cache", log_dir_path="./logs", temperature=(0.3, 0.9), retry_times=5, ) # Track errors errors = {"recoverable": 0, "critical": 0} def error_handler(event: FillFailedEvent): if event.over_maximum_retries: errors["critical"] += 1 print(f"\n[CRITICAL] {event.error_message}") else: errors["recoverable"] += 1 # Example usage of translate function would follow here, integrating the above configurations and handlers. ``` -------------------------------- ### Install epub-translator using pip Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.8.md Provides commands to install or upgrade the epub-translator package using pip. This is the standard method for managing Python package installations. ```bash pip install epub-translator==0.1.8 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Install epub-translator using pip Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md Instructions for installing the epub-translator package using pip. This includes installing a specific version (0.1.2) and upgrading to the latest version. ```bash pip install epub-translator==0.1.2 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Configure OpenAI-Compatible LLM Service (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Provides an example for configuring any LLM service that offers an OpenAI-compatible API. Users need to supply their API key, the service's API endpoint, the model name, and the correct token encoding for that model. ```python llm = LLM( key="your-api-key", url="https://your-service.com/v1", model="your-model", token_encoding="o200k_base", # Match your model's encoding ) ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/DEVELOPMENT.md Creates and activates a Python virtual environment using the 'venv' module. This isolates project dependencies. ```shell python -m venv .venv . ./.venv/bin/activate ``` -------------------------------- ### Install and upgrade epub-translator (Bash) Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.4.md Provides bash commands for installing version 0.1.4 of the epub-translator library using pip. It also includes instructions for upgrading to the latest version. ```bash pip install epub-translator==0.1.4 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Install epub-translator v0.1.3 using pip Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.3.md This snippet shows how to install a specific version of the epub-translator package using pip. It also provides instructions for upgrading to the latest version. ```bash pip install epub-translator==0.1.3 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Dual-LLM Architecture for Translation and Filling in epub-translator Source: https://context7.com/oomol-lab/epub-translator/llms.txt This Python example showcases a dual-LLM architecture where different Large Language Models (LLMs) are configured for the translation and XML filling stages. This allows for task-specific optimization of parameters like temperature, improving both translation creativity and structural precision. ```python from epub_translator import LLM, translate, language, SubmitKind # Translation LLM: higher temperature for creative, natural translations translation_llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", temperature=0.8, # More creative output ) # Fill LLM: lower temperature for precise XML structure preservation fill_llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", temperature=(0.2, 0.9), # Start precise, increase on retries ) translate( source_path="book.epub", target_path="translated.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, translation_llm=translation_llm, fill_llm=fill_llm, ) # Track tokens separately for each stage print(f"Translation stage tokens: {translation_llm.total_tokens:,}") print(f"Fill stage tokens: {fill_llm.total_tokens:,}") print(f"Total tokens: {translation_llm.total_tokens + fill_llm.total_tokens:,}") ``` -------------------------------- ### Install epub-translator v0.1.5 Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.5.md Installs the specific version 0.1.5 of the epub-translator package using pip. This command is useful for users who need to revert to or install this particular hotfix release. ```bash pip install epub-translator==0.1.5 ``` -------------------------------- ### Install epub-translator using pip Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Installs the epub-translator package using pip. Requires Python 3.11, 3.12, or 3.13. ```bash pip install epub-translator ``` -------------------------------- ### Dual-LLM Token Tracking for EPUB Translation (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md This example illustrates how to manage token statistics when using separate LLM instances for translation and filling operations. Each `LLM` object independently tracks its token usage, allowing for granular cost analysis. ```python from epub_translator import LLM, translate, language, SubmitKind translation_llm = LLM(key="...", url="...", model="gpt-4", token_encoding="o200k_base") fill_llm = LLM(key="...", url="...", model="gpt-4", token_encoding="o200k_base") translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, translation_llm=translation_llm, fill_llm=fill_llm, ) print(f"Translation tokens: {translation_llm.total_tokens}") print(f"Fill tokens: {fill_llm.total_tokens}") print(f"Combined total: {translation_llm.total_tokens + fill_llm.total_tokens}") ``` -------------------------------- ### EPUB Translator Example Usage (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Demonstrates practical application of the `translate` function using `SubmitKind.APPEND_BLOCK` for bilingual output and `SubmitKind.REPLACE` for single-language output. It also shows the integration of language constants. ```python # Assuming 'llm' is an initialized LLM object and 'language' is imported from epub_translator import SubmitKind, language # Example for bilingual books (recommended) translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, llm=llm, ) # Example for single-language translation translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.REPLACE, llm=llm, ) ``` -------------------------------- ### Migrate translate() calls to new signature (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md Provides examples of how to update existing calls to the `translate` function to comply with the new signature in v0.1.2. It shows two common migration patterns: using keyword arguments for the `llm` parameter or utilizing the new dual-LLM architecture with separate `translation_llm` and `fill_llm` parameters. ```python # Old code: translate(llm, source_path, target_path, "English") # New code (option 1 - use keyword argument): translate(source_path, target_path, "English", llm=llm) # New code (option 2 - use dual LLMs): translate( source_path, target_path, "English", translation_llm=translation_llm, fill_llm=fill_llm, ) ``` -------------------------------- ### Install epub-translator v0.1.7 Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.7.md Installs or upgrades the epub-translator package to version 0.1.7 using pip. This command ensures you have the latest features and bug fixes. ```bash pip install epub-translator==0.1.7 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Verbose Error Logging with `on_fill_failed` (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Provides an example of a more verbose `on_fill_failed` callback function for debugging translation issues. It differentiates between critical errors that impact the final output and informational messages about ongoing retries. ```python def handle_fill_error(event: FillFailedEvent): if event.over_maximum_retries: # Critical: affects final output print(f"❌ CRITICAL: {event.error_message}") else: # Informational: system is retrying print(f"⚠️ Retry {event.retried_count}: {event.error_message}") ``` -------------------------------- ### Implement error handling with FillFailedEvent (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md Illustrates how to use the new `FillFailedEvent` and the `on_fill_failed` callback system to handle translation errors programmatically. The example defines a custom error handler function that logs details about the error and checks if maximum retries have been exceeded. ```python from epub_translator import FillFailedEvent def handle_error(event: FillFailedEvent): print(f"Error on attempt {event.retried_count}: {event.error_message}") if event.over_maximum_retries: print("Maximum retries exceeded!") translate( source_path="source.epub", target_path="translated.epub", target_language="English", llm=llm, on_fill_failed=handle_error, ) ``` -------------------------------- ### Concurrent Translation for Speed (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Explains how to speed up the translation process by enabling concurrent execution of translation tasks. The `concurrency` parameter controls the number of parallel tasks, with a recommendation to start at 4 and adjust based on system resources and API limits. ```python translate( source_path="source.epub", target_path="translated.epub", target_language="English", submit=SubmitKind.APPEND_BLOCK, llm=llm, concurrency=4, # Process 4 segments concurrently ) ``` -------------------------------- ### Install epub-translator v0.1.6 Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.6.md Installs or upgrades the epub-translator Python package to version 0.1.6. This command uses pip, the standard package installer for Python. ```bash pip install epub-translator==0.1.6 ``` ```bash pip install --upgrade epub-translator ``` -------------------------------- ### Initialize LLM Client for AI Translation Source: https://context7.com/oomol-lab/epub-translator/llms.txt Configures the connection to an OpenAI-compatible API service using the LLM class. Supports basic and advanced initialization with caching, logging, and retry logic. Azure OpenAI configuration is also demonstrated. ```python from epub_translator import LLM # Basic initialization with OpenAI llm = LLM( key="sk-your-openai-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", # Token encoding for the model ) # Advanced initialization with caching and logging llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", cache_path="./translation_cache", # Resume failed translations log_dir_path="./logs", # Save request logs for debugging timeout=120.0, # Request timeout in seconds retry_times=5, # Number of retries on failure retry_interval_seconds=6.0, # Wait between retries temperature=(0.2, 0.9), # Start at 0.2, increase to 0.9 on retries top_p=0.95, # Nucleus sampling parameter ) # Azure OpenAI configuration azure_llm = LLM( key="your-azure-key", url="https://your-resource.openai.azure.com/openai/deployments/your-deployment", model="gpt-4", token_encoding="o200k_base", ) # After translation, access token statistics print(f"Total tokens: {llm.total_tokens}") print(f"Input tokens: {llm.input_tokens}") print(f"Output tokens: {llm.output_tokens}") print(f"Cached input tokens: {llm.input_cache_tokens}") ``` -------------------------------- ### Dual-LLM Architecture for Translation and Filling (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Illustrates setting up two separate LLM instances with distinct `temperature` parameters for translation and XML structure filling. This allows for fine-tuning creativity in translation versus precision in structure preservation. ```python # Create two LLM instances with different temperatures translation_llm = LLM( key="your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", temperature=0.8, # Higher temperature for creative translation ) fill_llm = LLM( key="your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", temperature=0.3, # Lower temperature for structure preservation ) translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, translation_llm=translation_llm, fill_llm=fill_llm, ) ``` -------------------------------- ### Track Token Usage with LLM Class in Python Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.8.md Demonstrates how to initialize the LLM class and access token usage statistics after a translation operation. This feature helps monitor API costs and resource consumption. ```python from epub_translator import LLM, translate, language, SubmitKind llm = LLM( key="your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", ) translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, llm=llm, ) # Access token statistics after translation print(f"Total tokens: {llm.total_tokens}") print(f"Input tokens: {llm.input_tokens}") print(f"Output tokens: {llm.output_tokens}") ``` -------------------------------- ### Configure OpenAI LLM (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Shows the basic configuration for using an OpenAI LLM. It requires an API key, the API endpoint URL, the model name, and the token encoding. ```python llm = LLM( key="sk-...", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", ) ``` -------------------------------- ### Configure Azure OpenAI LLM (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Demonstrates how to configure an LLM to use Azure OpenAI services. This requires a specific Azure API key, a custom URL pointing to the deployment, the model name, and the token encoding. ```python llm = LLM( key="your-azure-key", url="https://your-resource.openai.azure.com/openai/deployments/your-deployment", model="gpt-4", token_encoding="o200k_base", ) ``` -------------------------------- ### Track EPUB Translation Progress with Callbacks Source: https://context7.com/oomol-lab/epub-translator/llms.txt Implements real-time progress tracking for EPUB translations using the `on_progress` callback. Supports simple print statements or advanced progress bars using libraries like `tqdm`. Progress is reported as a float between 0.0 and 1.0. ```python from epub_translator import LLM, translate, language, SubmitKind from tqdm import tqdm llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", ) # Simple progress tracking function def simple_progress(progress: float): print(f"Translation progress: {progress * 100:.1f}%") translate( source_path="book.epub", target_path="translated.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, on_progress=simple_progress, ) # Progress bar with tqdm with tqdm(total=100, desc="Translating", unit="%") as pbar: last_progress = 0.0 def update_progress(progress: float): nonlocal last_progress increment = (progress - last_progress) * 100 pbar.update(increment) last_progress = progress # Show token usage in real-time pbar.set_postfix({"tokens": llm.total_tokens}) translate( source_path="book.epub", target_path="translated.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, on_progress=update_progress, ) print(f"Total tokens used: {llm.total_tokens:,}") ``` -------------------------------- ### Real-time Token Usage Monitoring During EPUB Translation (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md This code snippet shows how to monitor token usage in real-time during the EPUB translation process using `tqdm` for progress visualization. It includes an `on_progress` callback function that updates the progress bar with token statistics and estimated cost. ```python from tqdm import tqdm import time # Assuming 'llm' is an initialized LLM instance from the previous snippet # llm = LLM(...) with tqdm(total=100, desc="Translating", unit="%") as pbar: last_progress = 0.0 start_time = time.time() def on_progress(progress: float): nonlocal last_progress increment = (progress - last_progress) * 100 pbar.update(increment) last_progress = progress # Update token stats in progress bar pbar.set_postfix({ 'tokens': llm.total_tokens, 'cost_est': f'${llm.total_tokens * 0.00001:.4f}' # Estimate based on your pricing }) translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, llm=llm, on_progress=on_progress, ) elapsed = time.time() - start_time print(f"\nTranslation completed in {elapsed:.1f}s") print(f"Total tokens used: {llm.total_tokens:,}") print(f"Average tokens/second: {llm.total_tokens/elapsed:.1f}") ``` -------------------------------- ### Translate EPUB with Progress and Stats (Python) Source: https://context7.com/oomol-lab/epub-translator/llms.txt This snippet demonstrates how to translate an EPUB file using the EPUB Translator library. It includes a progress handler to display real-time translation statistics like tokens, recoverable errors, and critical failures, along with final summary statistics after completion. Dependencies include `time`, `tqdm`, and the `epub_translator` library with its associated modules. ```python import time from tqdm import tqdm from epub_translator import translate, language, SubmitKind # Assume llm, errors, and error_handler are defined elsewhere # Example placeholders: class MockLLM: def __init__(self): self.total_tokens = 0 self.input_tokens = 0 self.output_tokens = 0 llm = MockLLM() errors = {"recoverable": 0, "critical": 0} def error_handler(error): print(f"Error encountered: {error}") errors["recoverable"] += 1 start_time = time.time() with tqdm(total=100, desc="Translating", unit="%", ncols=100) as pbar: last_progress = 0.0 def progress_handler(progress: float): nonlocal last_progress pbar.update((progress - last_progress) * 100) last_progress = progress elapsed = time.time() - start_time pbar.set_postfix({ "tokens": f"{llm.total_tokens:,}", "errors": errors["recoverable"], "failed": errors["critical"], }) translate( source_path="./books/original.epub", target_path="./books/bilingual.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, user_prompt="Translate naturally while preserving technical terms in English", max_retries=5, concurrency=4, on_progress=progress_handler, on_fill_failed=error_handler, ) # Final statistics elapsed = time.time() - start_time print(f"\n{'=' * 50}") print(f"Translation complete!") print(f"Time: {elapsed:.1f} seconds") print(f"Tokens: {llm.total_tokens:,} ({llm.input_tokens:,} input, {llm.output_tokens:,} output)") print(f"Errors: {errors['recoverable']} recovered, {errors['critical']} failed") if errors["critical"] > 0: print("Warning: Some segments failed to translate. Check the output file.") ``` -------------------------------- ### Custom Translation Prompts (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Shows how to provide custom instructions to the translation model using the `user_prompt` parameter. This allows for specific guidance, such as enforcing formal language or preserving technical terms. ```python translate( source_path="source.epub", target_path="translated.epub", target_language="English", submit=SubmitKind.APPEND_BLOCK, llm=llm, user_prompt="Use formal language and preserve technical terminology", ) ``` -------------------------------- ### Concurrent Translation with Progress Tracking in epub-translator Source: https://context7.com/oomol-lab/epub-translator/llms.txt This Python code demonstrates how to speed up the translation of large EPUB files using the `concurrency` parameter for parallel processing. It also includes progress tracking with `tqdm` and token monitoring, providing real-time feedback on the translation status and performance. ```python from epub_translator import LLM, translate, language, SubmitKind from tqdm import tqdm import time llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", cache_path="./cache", # Enable caching for resumable translation ) start_time = time.time() with tqdm(total=100, desc="Translating (4 workers)", unit="%") as pbar: last_progress = 0.0 def on_progress(progress: float): nonlocal last_progress pbar.update((progress - last_progress) * 100) last_progress = progress pbar.set_postfix({ "tokens": llm.total_tokens, "tokens/s": f"{llm.total_tokens / (time.time() - start_time):.0f}" }) translate( source_path="large_book.epub", target_path="translated.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, concurrency=4, # Process 4 segments in parallel on_progress=on_progress, ) elapsed = time.time() - start_time print(f"\nCompleted in {elapsed:.1f}s") print(f"Total tokens: {llm.total_tokens:,}") print(f"Average speed: {llm.total_tokens / elapsed:.0f} tokens/second") ``` -------------------------------- ### LLM Class Initialization Parameters (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Defines the parameters for initializing the LLM class in epub-translator. This includes API key, URL, model, token encoding, and optional parameters for caching, timeouts, and retries. ```python LLM( key: str, # API key url: str, # API endpoint URL model: str, # Model name (e.g., "gpt-4") token_encoding: str, # Token encoding (e.g., "o200k_base") cache_path: PathLike | None = None, # Cache directory path timeout: float | None = None, # Request timeout in seconds top_p: float | tuple[float, float] | None = None, temperature: float | tuple[float, float] | None = None, retry_times: int = 5, # Number of retries on failure retry_interval_seconds: float = 6.0, # Interval between retries log_dir_path: PathLike | None = None, # Log directory path ) ``` -------------------------------- ### User Prompt Template Update Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.7.md This Jinja template snippet shows how user prompts are now correctly wrapped in `` tags when passed to the LLM. This ensures custom prompts are properly included in the translation process. ```jinja {% if user_prompt -%} {{ user_prompt }} {% endif -%} ``` -------------------------------- ### Translate EPUB with Progress Tracking (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Translates an EPUB file while displaying progress using the tqdm library. A callback function `on_progress` is provided to update the progress bar. ```python from tqdm import tqdm from epub_translator import LLM, translate, language, SubmitKind # Initialize LLM (assuming llm is already initialized as in the previous example) llm = LLM( key="your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", ) with tqdm(total=100, desc="Translating", unit="%") as pbar: last_progress = 0.0 def on_progress(progress: float): nonlocal last_progress increment = (progress - last_progress) * 100 pbar.update(increment) last_progress = progress translate( source_path="source.epub", target_path="translated.epub", target_language="English", submit=SubmitKind.APPEND_BLOCK, llm=llm, on_progress=on_progress, ) ``` -------------------------------- ### LLM Class - Initialize AI Translation Client Source: https://context7.com/oomol-lab/epub-translator/llms.txt The LLM class is used to configure the connection to an OpenAI-compatible API service. It handles token encoding, caching, retry logic, and supports parameters like temperature and top_p. ```APIDOC ## LLM Class - Initialize AI Translation Client ### Description Configures the connection to an OpenAI-compatible API service. Handles token encoding, caching, retry logic, and supports temperature/top_p parameters. ### Method Instantiate the `LLM` class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (str) - Required - API key for the LLM service. - **url** (str) - Required - Endpoint URL for the LLM service. - **model** (str) - Required - The name of the LLM model to use. - **token_encoding** (str) - Required - The token encoding scheme for the model (e.g., "o200k_base"). - **cache_path** (str) - Optional - Path to a directory for caching translation results to resume failed translations. - **log_dir_path** (str) - Optional - Path to a directory to save request logs for debugging. - **timeout** (float) - Optional - Request timeout in seconds. Defaults to a reasonable value. - **retry_times** (int) - Optional - Number of retries on failure. Defaults to 3. - **retry_interval_seconds** (float) - Optional - Wait time in seconds between retries. Defaults to 2.0. - **temperature** (tuple[float, float]) - Optional - A tuple defining the starting and maximum temperature for generation. Can increase across retries to escape stuck states. - **top_p** (float) - Optional - Nucleus sampling parameter. Defaults to 1.0. ### Request Example ```python from epub_translator import LLM # Basic initialization llm = LLM( key="sk-your-openai-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base" ) # Advanced initialization with caching and logging llm = LLM( key="sk-your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", cache_path="./translation_cache", log_dir_path="./logs", timeout=120.0, retry_times=5, retry_interval_seconds=6.0, temperature=(0.2, 0.9), top_p=0.95 ) # Azure OpenAI configuration azure_llm = LLM( key="your-azure-key", url="https://your-resource.openai.azure.com/openai/deployments/your-deployment", model="gpt-4", token_encoding="o200k_base" ) ``` ### Response #### Success Response (200) An instance of the `LLM` class is created. #### Response Example ```python # Access token statistics after translation print(f"Total tokens: {llm.total_tokens}") print(f"Input tokens: {llm.input_tokens}") print(f"Output tokens: {llm.output_tokens}") print(f"Cached input tokens: {llm.input_cache_tokens}") ``` ``` -------------------------------- ### Enable Caching for Progress Recovery (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/README.md Demonstrates how to enable caching for translation progress. By specifying a `cache_path`, the translator can resume interrupted or failed translations from where it left off, saving time and resources. ```python llm = LLM( key="your-api-key", url="https://api.openai.com/v1", model="gpt-4", token_encoding="o200k_base", cache_path="./translation_cache", # Translations are cached here ) ``` -------------------------------- ### Utilize Language Constants for EPUB Translation Source: https://context7.com/oomol-lab/epub-translator/llms.txt Shows how to use predefined language constants from the `epub_translator.language` module for specifying the target language in EPUB translations. Supports numerous languages and allows custom language strings. ```python from epub_translator import LLM, translate, language, SubmitKind llm = LLM(key="...", url="...", model="gpt-4", token_encoding="o200k_base") # Example using a language constant translate( source_path="english_book.epub", target_path="chinese_translation.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, ) # You can also use custom language strings, e.g., target_language="French" ``` -------------------------------- ### Update translate function signature for llm parameter Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md Demonstrates the change in the `translate` function signature from version 0.1.1 to 0.1.2. The `llm` parameter now requires keyword arguments. ```python # Old (v0.1.1) translate(llm, source_path, target_path, "English") # New (v0.1.2) translate(source_path, target_path, "English", llm=llm) ``` -------------------------------- ### Update translate() function signature (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md Demonstrates the changes in the `translate` function signature between v0.1.1 and v0.1.2. The order of parameters has shifted, and new optional LLM parameters for translation and XML filling have been added, along with an error callback. The `source_path` and `target_path` parameters now accept string types directly. ```python def translate( llm: LLM, # Required first parameter source_path: Path, target_path: Path, target_language: str, user_prompt: str | None = None, max_retries: int = 5, max_group_tokens: int = 1200, on_progress: Callable[[float], None] | None = None, ) -> None: # ... implementation for v0.1.1 ``` ```python def translate( source_path: PathLike | str, # Now the first parameter target_path: PathLike | str, # Now the second parameter target_language: str, user_prompt: str | None = None, max_retries: int = 5, max_group_tokens: int = 1200, llm: LLM | None = None, # Optional keyword parameter translation_llm: LLM | None = None, # NEW: Separate LLM for translation fill_llm: LLM | None = None, # NEW: Separate LLM for XML filling on_progress: Callable[[float], None] | None = None, on_fill_failed: Callable[[FillFailedEvent], None] | None = None, # NEW ) -> None: # ... implementation for v0.1.2 ``` -------------------------------- ### Enable Concurrent Translation in Python Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.6.md Demonstrates how to enable concurrent translation using the `translate` function by setting the `concurrency` parameter. This allows for parallel processing of text segments, significantly speeding up translation of large EPUB files. The `concurrency` parameter defaults to 1 for backward compatibility. ```python from epub_translator import translate, SubmitKind # Assuming 'llm' is an initialized language model object llm = None # Replace with your actual LLM initialization translate( source_path="source.epub", target_path="translated.epub", target_language="English", submit=SubmitKind.APPEND_BLOCK, llm=llm, concurrency=4, # Process 4 segments concurrently ) ``` ```python from epub_translator import translate, SubmitKind, language # Assuming 'llm' is an initialized language model object llm = None # Replace with your actual LLM initialization translate( source_path="source.epub", target_path="translated.epub", target_language=language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, llm=llm, concurrency=4, # Add this line to enable concurrent translation ) ``` -------------------------------- ### Using SubmitKind for translation modes (Python) Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.4.md Illustrates the usage of the `SubmitKind` enum in the `translate()` function to specify different translation submission modes. This includes options for bilingual books and single-language replacements. ```python # Bilingual book translate(source_path, target_path, language.ENGLISH, submit=SubmitKind.APPEND_BLOCK, llm=llm) # Single-language translation translate(source_path, target_path, language.ENGLISH, submit=SubmitKind.REPLACE, llm=llm) ``` -------------------------------- ### Fix Windows Path Separator Issue in ZIP Handling Source: https://github.com/oomol-lab/epub-translator/blob/main/docs/changelog/v0.1.2.md This code snippet illustrates the fix for handling Windows path separators in ZIP files. It involves using `.as_posix()` for cross-platform compatibility, resolving read failures on Windows systems. ```python # Example of path handling change (conceptual) # Original might have used os.path.join which can be problematic with ZIPs on Windows # New approach ensures POSIX-style paths are used internally for ZIP operations # For instance, a path like 'C:\\Users\\file.txt' would be treated as 'C:/Users/file.txt' within the ZIP context. ``` -------------------------------- ### Translate EPUB with Different Submission Modes Source: https://context7.com/oomol-lab/epub-translator/llms.txt Demonstrates how to translate an EPUB file using different submission modes: APPEND_BLOCK (adds translated text as a new block), APPEND_TEXT (inlines translated text), and REPLACE (replaces original text with translation). Requires source and target paths, target language, submission mode, and an LLM instance. ```python from epub_translator import LLM, translate, language, SubmitKind llm = LLM(key="...", url="...", model="gpt-4", token_encoding="o200k_base") # APPEND_BLOCK (Original and translated text in separate blocks) translate( source_path="book.epub", target_path="bilingual_block.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_BLOCK, llm=llm, ) # APPEND_TEXT (Inline bilingual text) translate( source_path="book.epub", target_path="bilingual_inline.epub", target_language=language.CHINESE, submit=SubmitKind.APPEND_TEXT, llm=llm, ) # REPLACE (Translated text only) translate( source_path="book.epub", target_path="translated_only.epub", target_language=language.CHINESE, submit=SubmitKind.REPLACE, llm=llm, ) ```