更新readme

This commit is contained in:
xunbu
2025-08-18 20:19:03 +08:00
parent befbca41c8
commit c645fc142a
2 changed files with 348 additions and 334 deletions

317
README.md
View File

@@ -12,28 +12,19 @@
[**简体中文**](/README_ZH.md) / [**English**](/README.md) / [**日本語**](/README_JP.md)
**DocuTranslate** is a file translation tool that combines advanced document parsing engines (such
as [docling](https://github.com/docling-project/docling) and [minerU](https://mineru.net/)) with large language models (
LLMs) to accurately translate documents in various formats.
**DocuTranslate** is a file translation tool that combines advanced document analysis engines (such as [docling](https://github.com/docling-project/docling) and [minerU](https://mineru.net/)) with large language models (LLMs). It can accurately translate documents in a wide variety of formats.
The new version adopts a **Workflow-centric** architecture, providing highly configurable and scalable solutions for
various types of translation tasks.
The new version's architecture adopts **Workflow** as its core, providing a highly configurable and extensible solution for various types of translation tasks.
-**Support for Diverse Formats**: Capable of translating various file formats such as `pdf`, `docx`, `xlsx`, `md`,
`txt`, `json`, `epub`, `srt`, etc.
-**Table, Formula, and Code Recognition**: Utilizes `docling` and `minerU` to recognize and translate tables,
formulas, and code frequently found in academic papers.
-**JSON Translation**: Allows specifying translatable values within JSON using jsonpath-ng syntax.
-**High-Fidelity Word/Excel Translation**: Preserves the formatting of `docx` and `xlsx` files (note: `doc` and `xls`
are not supported).
-**Multiple AI Platform Support**: Covers major AI platforms and enables high-parallel AI translation with custom
prompts.
-**Asynchronous Support**: Designed for high-performance scenarios, offering full asynchronous support and multi-task
parallel processing APIs.
-**Interactive Web Interface**: Equipped with a ready-to-use Web UI and RESTful API.
-**Supports a wide variety of formats**: Capable of translating files such as `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, `epub`, `srt`, etc.
-**Recognition of tables, formulas, and code**: Utilizes `docling` and `mineru` to recognize and translate tables, formulas, and code commonly found in academic papers.
-**JSON translation**: Supports specifying values within JSON that need translation through JSON paths (following the `jsonpath-ng` syntax specification).
-**High-fidelity translation for Word/Excel**: Supports translation of `docx` and `xlsx` files (currently does not support `doc` and `xls` files) while preserving the original formatting.
-**Support for multiple AI platforms**: Compatible with most AI platforms, enabling high-performance parallel AI translation with custom prompts.
-**Asynchronous support**: Designed for high-performance scenarios, offering full asynchronous support and implementing a service interface capable of multitask parallel processing.
-**Interactive web interface**: Provides an out-of-the-box Web UI and RESTful API for easy integration and use.
> When translating `pdf` files, they are converted to markdown, **resulting in loss of the original layout**. Please be
> cautious if layout preservation is a priority.
> When translating `pdf` files, they are first converted to markdown, so the original typesetting will be **lost**. Users with typesetting requirements should note this.
> QQ Discussion Group: 1047781902
@@ -46,15 +37,12 @@ various types of translation tasks.
**Novel Translation**:
![翻译效果](/images/小说翻译.png)
## Bundled Version
## Integrated Packages
For users who want to get started quickly, we provide a bundled version
on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). Simply download, extract, and input the API key
of your preferred AI platform to start using it.
For users who want to get started quickly, we provide integrated packages on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). Simply download, unzip, and enter your AI platform's API key to start using.
- **DocuTranslate**: Standard version, uses the online `minerU` engine.
- **DocuTranslate_full**: Full version, includes the local `docling` parsing engine, ideal for offline environments or
scenarios prioritizing data privacy.
- **DocuTranslate**: The standard version, which uses the online `minerU` engine to parse documents. Recommended for most users.
- **DocuTranslate_full**: The full version, which includes the `docling` local parsing engine. Suitable for offline scenarios or those with higher data privacy requirements.
## Installation
@@ -64,97 +52,92 @@ of your preferred AI platform to start using it.
# Basic installation
pip install docutranslate
# When using the docling local analysis engine
# If using the docling local parsing engine
pip install docutranslate[docling]
```
### Using uv
```bash
# Environment initialization
# Initialize the environment
uv init
# Basic installation
uv add docutranslate
# Extended installation with docling
# Install docling extension
uv add docutranslate[docling]
```
### Using git
```bash
# Environment initialization
# Initialize the environment
git clone https://github.com/xunbu/docutranslate.git
cd docutranslate
uv sync
```
## Core Concept: Workflow
The heart of the new version of DocuTranslate is the **Workflow**. Each workflow is a complete end-to-end translation
pipeline designed for a specific file type. Instead of interacting with large classes, you select and configure the
appropriate workflow based on the file type.
The core of the new version of DocuTranslate is the **Workflow**. Each workflow is a complete end-to-end translation pipeline designed for a specific file type. Instead of interacting with large classes as before, you will select and configure the appropriate workflow according to the file type.
**The basic usage steps are as follows:**
1. **Select a Workflow**: Choose a workflow such as `MarkdownBasedWorkflow` or `TXTWorkflow` based on the input file
type (e.g., PDF/Word or TXT).
2. **Build the Configuration**: Create a configuration object (e.g., `MarkdownBasedWorkflowConfig`) corresponding to the
selected workflow. This configuration object includes all necessary sub-configurations, such as:
* **Converter Config**: Defines how to convert the original file (e.g., PDF) into Markdown.
* **Translator Config**: Defines the LLM to use, API keys, target language, etc.
1. **Select a Workflow**: Choose a workflow based on the input file type (e.g., PDF/Word or TXT). For example, `MarkdownBasedWorkflow` or `TXTWorkflow`.
2. **Build Configuration**: Create a configuration object corresponding to the selected workflow (such as `MarkdownBasedWorkflowConfig`). This configuration object contains all the necessary sub-configurations, such as:
* **Converter Config**: Defines how to convert the original file (e.g., PDF) to Markdown.
* **Translator Config**: Defines the LLM to use, API-Key, target language, etc.
* **Exporter Config**: Defines specific options for the output format (e.g., HTML).
3. **Instantiate the Workflow**: Use the configuration object to create an instance of the workflow.
4. **Execute the Translation**: Call the workflow's `.read_*()` and `.translate()` / `.translate_async()` methods.
5. **Export/Save the Results**: Call the `.export_to_*()` or `.save_as_*()` methods to retrieve or save the translated
results.
3. **Instantiate the Workflow**: Create an instance of the workflow using the configuration object.
4. **Execute Translation**: Call the workflow's `.read_*()` method and `.translate()` / `.translate_async()` method.
5. **Export/Save Results**: Call the `.export_to_*()` method or `.save_as_*()` method to retrieve or save the translation results.
## Available Workflows
| Workflow | Applicable Scenarios | Input Formats | Output Formats | Core Configuration Class |
|:----------------------------|:----------------------------------------------------------------------------------------------------------------------|:---------------------------------------------|:-----------------------|:------------------------------|
| **`MarkdownBasedWorkflow`** | Processes rich-text documents like PDF, Word, and images. Follows the flow: "File Markdown Translation Export". | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | Processes plain text documents. Follows the flow: "txt Translation Export". | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | Processes JSON files. Follows the flow: "json Translation Export". | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | Processes DOCX files. Follows the flow: "docx Translation Export". | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | Processes XLSX files. Follows the flow: "xlsx Translation Export". | `.xlsx` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | Processes SRT files. Follows the flow: "srt Translation Export". | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | Processes EPUB files. Follows the flow: "epub Translation Export". | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | Processes HTML files. Follows the flow: "html Translation Export". | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
| Workflow | Application Scenario | Input Format | Output Format | Core Configuration Class |
|:---------------------------|:-------------------------------------------------------------------------------------|:-------------------------------------------|:-----------------------|:----------------------------------|
| **`MarkdownBasedWorkflow`** | Process rich text documents such as PDF, Word, and images. Flow: `File -> Markdown -> Translation -> Export`. | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | Process plain text documents. Flow: `txt -> Translation -> Export`. | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | Process json files. Flow: `json -> Translation -> Export`. | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | Process docx files. Flow: `docx -> Translation -> Export`. | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | Process xlsx files. Flow: `xlsx -> Translation -> Export`. | `.xlsx` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | Process srt files. Flow: `srt -> Translation -> Export`. | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | Process epub files. Flow: `epub -> Translation -> Export`. | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | Process html files. Flow: `html -> Translation -> Export`. | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
> The interactive interface supports exporting in PDF format.
> The interactive interface allows export in pdf format.
## Launching Web UI and API Services
## Starting the Web UI and API Service
For convenience, DocuTranslate provides a feature-rich web interface and RESTful API.
For ease of use, DocuTranslate provides a feature-rich web interface and RESTful API.
**Starting the Service:**
```bash
# Start the service (default port: 8010)
# Start the service, which monitors port 8010 by default
docutranslate -i
# Start with a specified port
docutranslate -i -p 8011
# Alternatively, specify the port via environment variable
# You can also specify the port using an environment variable
export DOCUTRANSLATE_PORT=8011
docutranslate -i
```
- **Interactive Interface**: After starting the service, access `http://127.0.0.1:8010` (or the specified port) in your
browser.
- **API Documentation**: Complete API documentation (Swagger UI) is available at `http://127.0.0.1:8010/docs`.
- **Interactive Interface**: After starting the service, access `http://127.0.0.1:8010` (or the specified port) in your browser.
- **API Documentation**: The complete API documentation (Swagger UI) is available at `http://127.0.0.1:8010/docs`.
## Usage
### Example 1: Translating PDF Files (Using `MarkdownBasedWorkflow`)
### Example 1: Translating a PDF File (Using `MarkdownBasedWorkflow`)
This is the most common use case. The `minerU` engine is used to convert PDFs to Markdown, followed by translation via
LLM. Here, an asynchronous approach is demonstrated.
This is the most common use case. Convert the PDF to Markdown using the `minerU` engine and translate it with an LLM. Here, we use the asynchronous method as an example.
```python
import asyncio
@@ -168,45 +151,45 @@ async def main():
# 1. Build translator configuration
translator_config = MDTranslatorConfig(
base_url="https://open.bigmodel.cn/api/paas/v4", # Base URL of the AI platform
api_key="YOUR_ZHIPU_API_KEY", # API Key for the AI platform
api_key="YOUR_ZHIPU_API_KEY", # API Key of the AI platform
model_id="glm-4-air", # Model ID
to_lang="English", # Target language
chunk_size=3000, # Text chunk size
concurrent=10 # Number of concurrent processes
concurrent=10 # Number of concurrent executions
)
# 2. Build converter configuration (using minerU)
converter_config = ConverterMineruConfig(
mineru_token="YOUR_MINERU_TOKEN", # minerU token
mineru_token="YOUR_MINERU_TOKEN", # Your minerU Token
formula_ocr=True # Enable formula recognition
)
# 3. Build main workflow configuration
workflow_config = MarkdownBasedWorkflowConfig(
convert_engine="mineru", # Specify the parsing engine
converter_config=converter_config, # Apply converter configuration
translator_config=translator_config, # Apply translator configuration
converter_config=converter_config, # Pass the converter configuration
translator_config=translator_config, # Pass the translator configuration
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export configuration
)
# 4. Instantiate the workflow
workflow = MarkdownBasedWorkflow(config=workflow_config)
# 5. Load file and execute translation
# 5. Load the file and execute translation
print("Starting file loading and translation...")
workflow.read_path("path/to/your/document.pdf")
await workflow.translate_async()
# Or use synchronous method
# Or use the synchronous method
# workflow.translate()
print("Translation completed!")
# 6. Save results
# 6. Save the results
workflow.save_as_html(name="translated_document.html")
workflow.save_as_markdown_zip(name="translated_document.zip")
workflow.save_as_markdown(name="translated_document.md") # Image-embedded Markdown
print("Files have been saved in the ./output folder.")
workflow.save_as_markdown(name="translated_document.md") # Markdown with embedded images
print("Files saved to the ./output folder.")
# Or directly retrieve content strings
# Or directly get the content string
html_content = workflow.export_to_html()
html_content = workflow.export_to_markdown()
# print(html_content)
@@ -216,6 +199,10 @@ if __name__ == "__main__":
asyncio.run(main())
```
### Example 2: Translating TXT Files (Using `TXTWorkflow`)
For pure text files, the process is simpler as there is no need for document parsing (conversion). Here is an example using the asynchronous method.
```python
import asyncio
from docutranslate.workflow.txt_workflow import TXTWorkflow, TXTWorkflowConfig
@@ -224,15 +211,15 @@ from docutranslate.exporter.txt.txt2html_exporter import TXT2HTMLExporterConfig
async def main():
# 1. Build translator configuration
# 1. Build the translator configuration
translator_config = TXTTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="Japanese",
to_lang="中文",
)
# 2. Build main workflow configuration
# 2. Build the main workflow configuration
workflow_config = TXTWorkflowConfig(
translator_config=translator_config,
html_exporter_config=TXT2HTMLExporterConfig(cdn=True)
@@ -241,17 +228,17 @@ async def main():
# 3. Instantiate the workflow
workflow = TXTWorkflow(config=workflow_config)
# 4. Load the file and execute translation
# 4. Read the file and execute translation
workflow.read_path("path/to/your/notes.txt")
await workflow.translate_async()
# Alternatively, use the synchronous method
# Or use the synchronous method
# workflow.translate()
# 5. Save the results
# 5. Save the result
workflow.save_as_txt(name="translated_notes.txt")
print("TXT file has been saved.")
print("TXT file saved.")
# It's also possible to export the translated plain text
# You can also export the translated plain text
text = workflow.export_to_txt()
@@ -259,6 +246,13 @@ if __name__ == "__main__":
asyncio.run(main())
```
### Example 3: Translating a JSON file (using `JsonWorkflow`)
Here, we show an example using the asynchronous method. In the `json_paths` item of `JsonTranslatorConfig`, you need to specify the JSON paths to be translated (following the jsonpath-ng syntax rules).
Only the values matching the JSON paths will be translated.
```python
import asyncio
@@ -268,16 +262,16 @@ from docutranslate.workflow.json_workflow import JsonWorkflowConfig, JsonWorkflo
async def main():
# 1. Configure the translator
# 1. Build the translator configuration
translator_config = JsonTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="Japanese",
json_paths=["$.*", "$.name"] # Complies with jsonpath-ng syntax; values matching these paths will be translated
to_lang="Chinese",
json_paths=["$.*", "$.name"] # Compliant with the jsonpath-ng path syntax; all values matching the path will be translated
)
# 2. Configure the main workflow
# 2. Build the main workflow configuration
workflow_config = JsonWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Json2HTMLExporterConfig(cdn=True)
@@ -286,17 +280,17 @@ async def main():
# 3. Instantiate the workflow
workflow = JsonWorkflow(config=workflow_config)
# 4. Load the file and execute the translation
# 4. Read the file and execute translation
workflow.read_path("path/to/your/notes.json")
await workflow.translate_async()
# Alternatively, use the synchronous method
# Or use the synchronous method
# workflow.translate()
# 5. Save the results
workflow.save_as_json(name="translated_notes.json")
print("JSON file has been saved.")
print("The JSON file has been saved.")
# The translated JSON text can also be exported
# You can also export the translated json text
text = workflow.export_to_json()
@@ -304,6 +298,12 @@ if __name__ == "__main__":
asyncio.run(main())
```
### Example 4: Translating a docx File (Using `DocxWorkflow`)
Here, the asynchronous method is shown as an example.
```python
import asyncio
@@ -313,17 +313,17 @@ from docutranslate.workflow.docx_workflow import DocxWorkflowConfig, DocxWorkflo
async def main():
# 1. Configure the translator
# 1. Build the translator configuration
translator_config = DocxTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="Japanese",
insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used in "append" or "prepend" mode
to_lang="日本語",
insert_mode="replace", # Optional: "replace", "append", "prepend"
separator="\n", # Separator used in "append" and "prepend" modes
)
# 2. Configure the main workflow
# 2. Build the main workflow configuration
workflow_config = DocxWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Docx2HTMLExporterConfig(cdn=True)
@@ -335,14 +335,14 @@ async def main():
# 4. Load the file and execute translation
workflow.read_path("path/to/your/notes.docx")
await workflow.translate_async()
# Alternatively, use the synchronous method
# Or use the synchronous method
# workflow.translate()
# 5. Save the results
# 5. Save the result
workflow.save_as_docx(name="translated_notes.docx")
print("The docx file has been saved.")
# The translated docx can also be exported as binary
# You can also export the translated docx as binary
text_bytes = workflow.export_to_docx()
@@ -350,6 +350,12 @@ if __name__ == "__main__":
asyncio.run(main())
```
### Example 5: Translating an xlsx file (using `XlsxWorkflow`)
Here, we will use the asynchronous method as an example.
```python
import asyncio
@@ -359,17 +365,17 @@ from docutranslate.workflow.xlsx_workflow import XlsxWorkflowConfig, XlsxWorkflo
async def main():
# 1. Build translator configuration
# 1. Build the translator configuration
translator_config = XlsxTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="Japanese",
insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used in "append" or "prepend" mode
to_lang="日本語",
insert_mode="replace", # Optional: "replace", "append", "prepend"
separator="\n", # Separator used in "append" and "prepend" modes
)
# 2. Build main workflow configuration
# 2. Build the main workflow configuration
workflow_config = XlsxWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True)
@@ -381,14 +387,14 @@ async def main():
# 4. Load the file and execute translation
workflow.read_path("path/to/your/notes.xlsx")
await workflow.translate_async()
# Alternatively, use the synchronous method
# Or use the synchronous method
# workflow.translate()
# 5. Save the results
# 5. Save the result
workflow.save_as_xlsx(name="translated_notes.xlsx")
print("The xlsx file has been saved.")
print("The XLSX file has been saved.")
# It's also possible to export the translated xlsx as binary
# You can also export the binary data of the translated XLSX
text_bytes = workflow.export_to_xlsx()
@@ -396,56 +402,59 @@ if __name__ == "__main__":
asyncio.run(main())
```
### 1. Obtaining API Keys for Large-Scale Language Models
The translation functionality relies on large-scale language models, requiring the retrieval of `base_url`, `api_key`,
and `model_id` from the corresponding AI platform.
> Recommended models: Volcano Engine's `doubao-seed-1-6-250615`, `doubao-seed-1-6-flash-250715`, Zhipu's `glm-4-flash`,
> Alibaba Cloud's `qwen-plus`,
> `qwen-turbo`, DeepSeek's `deepseek-chat`, etc.
## Detailed Explanation of Prerequisites and Settings
| Platform Name | API Key Retrieval Method | Base URL |
|-----------------------|----------------------------------------------------------------------------------------------------|----------------------------------------------------------|
### 1. Obtaining a Large Language Model API Key
The translation function relies on a large language model, and you need to obtain the `base_url`, `api_key`, and `model_id` from the corresponding AI platform.
> Recommended models: Volcano Engine's `doubao-seed-1-6-250615`, `doubao-seed-1-6-flash-250715`, Zhipu's `glm-4-flash`, Alibaba Cloud's `qwen-plus`, `qwen-turbo`, DeepSeek's `deepseek-chat`, etc.
| Platform Name | Method to Obtain API Key | baseurl |
|------------|-----------------------------------------------------------------------------------|----------------------------------------------------------|
| ollama | | http://127.0.0.1:11434/v1 |
| lm studio | | http://127.0.0.1:1234/v1 |
| openrouter | [Click to retrieve](https://openrouter.ai/settings/keys) | https://openrouter.ai/api/v1 |
| openai | [Click to retrieve](https://platform.openai.com/api-keys) | https://api.openai.com/v1/ |
| gemini | [Click to retrieve](https://aistudio.google.com/u/0/apikey) | https://generativelanguage.googleapis.com/v1beta/openai/ |
| deepseek | [Click to retrieve](https://platform.deepseek.com/api_keys) | https://api.deepseek.com/v1 |
| Zhipu AI | [Click to retrieve](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 |
| Tencent Hunyuan | [Click to retrieve](https://console.cloud.tencent.com/hunyuan/api-key) | https://api.hunyuan.cloud.tencent.com/v1 |
| Alibaba Cloud Bailian | [Click to retrieve](https://bailian.console.aliyun.com/?tab=model#/api-key) | https://dashscope.aliyuncs.com/compatible-mode/v1 |
| Volcano Engine | [Click to retrieve](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | https://ark.cn-beijing.volces.com/api/v3 |
| Silicon Flow | [Click to retrieve](https://cloud.siliconflow.cn/account/ak) | https://api.siliconflow.cn/v1 |
| DMXAPI | [Click to retrieve](https://www.dmxapi.cn/token) | https://www.dmxapi.cn/v1 |
| openrouter | [Click to Obtain](https://openrouter.ai/settings/keys) | https://openrouter.ai/api/v1 |
| openai | [Click to Obtain](https://platform.openai.com/api-keys) | https://api.openai.com/v1/ |
| gemini | [Click to Obtain](https://aistudio.google.com/u/0/apikey) | https://generativelanguage.googleapis.com/v1beta/openai/ |
| deepseek | [Click to Obtain](https://platform.deepseek.com/api_keys) | https://api.deepseek.com/v1 |
| 智譜ai | [Click to Obtain](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 |
| 騰訊混元 | [Click to Obtain](https://console.cloud.tencent.com/hunyuan/api-key) | https://api.hunyuan.cloud.tencent.com/v1 |
| 阿里云百煉 | [Click to Obtain](https://bailian.console.aliyun.com/?tab=model#/api-key) | https://dashscope.aliyuncs.com/compatible-mode/v1 |
| 火山引擎 | [Click to Obtain](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | https://ark.cn-beijing.volces.com/api/v3 |
| 硅基流動 | [Click to Obtain](https://cloud.siliconflow.cn/account/ak) | https://api.siliconflow.cn/v1 |
| DMXAPI | [Click to Obtain](https://www.dmxapi.cn/token) | https://www.dmxapi.cn/v1 |
### 2. Obtaining minerU Tokens (Online Parsing)
### 2. Obtaining minerU Token (Online Parsing)
When selecting `mineru` as the document parsing engine (`convert_engine="mineru"`), you need to apply for a free token.
If you select `mineru` as the document parsing engine (`convert_engine="mineru"`), you need to apply for a free Token.
1. Visit the [minerU official website](https://mineru.net/apiManage/docs), register, and apply for the API.
2. Create a new API token in the [API Token Management page](https://mineru.net/apiManage/token).
2. Create a new API Token on the [API Token management page](https://mineru.net/apiManage/token).
> **Note**: minerU tokens are valid for 14 days. If expired, recreate them.
> **Note**: The minerU Token is valid for 14 days. If it expires, please recreate it.
### 3. Configuring the docling Engine (Local Parsing)
When selecting `docling` as the document parsing engine (`convert_engine="docling"`), the required models will be
downloaded from Hugging Face upon first use.
If you select `docling` as the document parsing engine (`convert_engine="docling"`), the required models will be downloaded from Hugging Face during the first use.
**Solutions for Network Issues:**
1. **Setting Up Hugging Face Mirror (Recommended)**:
1. **Setting up a Hugging Face Mirror (Recommended)**:
* **Method A (Environment Variable)**: Set the system environment variable `HF_ENDPOINT` and restart your IDE or terminal.
* **Method A (Environment Variable)**: Set the system environment variable `HF_ENDPOINT` and restart the IDE or
terminal.
```
HF_ENDPOINT=https://hf-mirror.com
```
* **Method B (In-Code Configuration)**: Add the following code at the beginning of your Python script.
* **Method B (Setting in Code)**: Add the following code at the beginning of your Python script.
```python
import os
@@ -453,12 +462,16 @@ import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
```
2. **Offline Usage (Pre-Downloading Model Packages)**:
2. **Offline Use (Download Model Packages in Advance)**:
* Download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases).
* Extract and place it in the project directory.
* Extract it to your project directory.
* Specify the model path in the configuration:
```python
from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig
@@ -471,32 +484,26 @@ converter_config = ConverterDoclingConfig(
## FAQ
**Q: What should I do if port 8010 is already in use?**
**Q: What should I do if port 8010 is occupied?**
A: Specify a new port using the `-p` parameter or set the `DOCUTRANSLATE_PORT` environment variable.
**Q: Is scanned document translation supported?**
A: Yes, it is supported. Use the `mineru` parsing engine, which features powerful OCR capabilities.
**Q: Is translation of scanned documents supported?**
A: Yes, it is supported. Please use the `mineru` parsing engine, which is equipped with powerful OCR capabilities.
**Q: Why is it slow during the first use?**
A: When using the `docling` engine, the model needs to be downloaded from Hugging Face during the first run. Refer to
the "Network Issue Solutions" section above to speed up this process.
**Q: Why is it slow on first use?**
A: When using the `docling` engine, the model needs to be downloaded from Hugging Face during the first run. To speed up this process, refer to the "Solutions for Network Issues" section above.
**Q: How can I use it in an intranet (offline) environment?**
A: It is entirely possible. You need to meet the following two conditions:
**Q: How can it be used in an intranet (offline) environment?**
A: It is completely possible. The following two conditions need to be met:
1. **Local Parsing Engine**: Use the `docling` engine and follow the "Offline Usage" steps above to download the model
package in advance.
2. **Local LLM**: Deploy a local language model using tools like [Ollama](https://ollama.com/)
or [LM Studio](https://lmstudio.ai/), then input the local model's `base_url` in `TranslatorConfig`.
1. **Local Parsing Engine**: Use the `docling` engine and download the model package in advance according to the "Offline Use" guide above.
2. **Local LLM**: Deploy a language model locally using tools such as [Ollama](https://ollama.com/) or [LM Studio](https://lmstudio.ai/), and enter the `base_url` of the local model in `TranslatorConfig`.
**Q: How does the caching mechanism work?**
A: `MarkdownBasedWorkflow` automatically caches the results of document parsing (conversion from files to Markdown),
saving time and resources. By default, the cache is stored in memory, recording the last 10 parsing operations. You can
adjust the cache size using the `DOCUTRANSLATE_CACHE_NUM` environment variable.
A: `MarkdownBasedWorkflow` automatically caches the results of document parsing (conversion from files to Markdown) to avoid wasting time and resources on repeated parsing. The cache is stored in memory by default and records the most recent 10 parsing operations. The number of cached items can be changed via the `DOCUTRANSLATE_CACHE_NUM` environment variable.
**Q: How can I use the software via a proxy?**
A: The software does not use a proxy by default. You can enable proxy usage by setting the `DOCUTRANSLATE_USE_PROXY`
environment variable to `true`.
A: The software does not use a proxy by default. Set the `DOCUTRANSLATE_USE_PROXY` environment variable to `true` to enable communication via a proxy.
## Star History

View File

@@ -12,69 +12,72 @@
[**简体中文**](/README_ZH.md) / [**English**](/README.md) / [**日本語**](/README_JP.md)
**DocuTranslate** は、先進的なドキュメント解析エンジン([docling](https://github.com/docling-project/docling)
や[minerU](https://mineru.net/)などと大規模言語モデルLLMを組み合わせたファイル翻訳ツールで、多様なフォーマットのドキュメントを高精度に翻訳します。
**DocuTranslate** は、高度なドキュメント解析エンジン([docling](https://github.com/docling-project/docling) や [minerU](https://mineru.net/) などと大規模言語モデルLLMを組み合わせたファイル翻訳ツールです。多種多様な形式のドキュメントを高精度に翻訳することができます。
新バージョンでは、**ワークフロー(Workflow)**を中核としたアーキテクチャを採用し、様々なタイプの翻訳タスクに対して高度に設定可能拡張性の高いソリューションを提供します。
しいバージョンのアーキテクチャでは **ワークフローWorkflow** を中核として採用し、さまざまなタイプの翻訳タスクに対して高度に設定可能かつ拡張性のあるソリューションを提供しています。
-**多様なフォーマット対応**: `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, `epub`, `srt` など様々なファイル形式の翻訳可能
-**表数式コード認識**: `docling``mineru` を活用し、学術論文で頻出する表、数式、コードの認識と翻訳を実現
-**json翻訳**: json内の翻訳対象値をjsonpath-ng構文で指定可能
-**Word/Excel高忠実度翻訳**: `docx``xlsx`ファイル(`doc``xls`は非対応)のフォーマットを保持し翻訳
-**複数AIプラットフォーム対応**: 主要なAIプラットフォームを網羅し、カスタムプロンプトを用いた高並列AI翻訳を実現
-**非同期サポート**: 高性能シナリオ向けに設計され、完全な非同期サポートマルチタスク並処理APIを提供
-**対話型Webインターフェース**: すぐに使るWeb UIとRESTful APIを装備
-**多種多様なフォーマットをサポート**`pdf``docx``xlsx``md``txt``json``epub``srt` などファイル翻訳可能です。
-**表数式コード認識**`docling``mineru` を活用し、学術論文によく出現する表、数式、コードの認識と翻訳を実現します。
-**json翻訳**jsonパス(`jsonpath-ng`構文規範を通じてjson内で翻訳が必要な値を指定することをサポートします。
-**Word/Excel高忠実度翻訳**`docx``xlsx`ファイル(`doc``xls`ファイルは現在サポートしていません)の翻訳をサポートし、元のフォーマットを保持し翻訳します。
-**複数AIプラットフォームのサポート**:ほとんどのAIプラットフォームをサポートし、カスタムプロンプトによる並行高性能AI翻訳を実現できます。
-**非同期サポート**高性能シナリオ向けに設計され、完全な非同期サポートを提供し、マルチタスク並処理が可能なサービスインターフェースを実現しています。
-**インタラクティブWebインターフェース**すぐに使用できるWeb UIとRESTful APIを提供し、統合と使用が容易です。
> `pdf`翻訳時はmarkdownに変換されるため、**元のレイアウトが失われます**。レイアウト保持を重視される方はご注意ください
> `pdf`翻訳する場合、最初にマークダウンに変換されるため、元の排版が**失われます**。排版に要件があるユーザーは注意してください
> QQ交流グループ: 1047781902
> QQ交流グループ1047781902
**UIインターフェース**:
**UIインターフェース**
![翻译效果](/images/UI界面.png)
**論文翻訳**:
**論文翻訳**
![翻译效果](/images/论文翻译.png)
**小説翻訳**:
**小説翻訳**
![翻译效果](/images/小说翻译.png)
## バンドル版
## 統合パッケージ
すぐに使い始めたい方向けに、[GitHub Releases](https://github.com/xunbu/docutranslate/releases)
でバンドル版を提供しています。ダウンロードして解凍し、AIプラットフォームのAPIキーを入力するだけで利用可能です。
すぐに始めたいユーザーのために、[GitHub Releases](https://github.com/xunbu/docutranslate/releases) で統合パッケージを提供しています。ダウンロードして解凍し、AIプラットフォームのAPIキーを入力するだけで使用を開始できます。
- **DocuTranslate**: 標準版、オンラインの`minerU`エンジンを使用
- **DocuTranslate_full**: 完全版、ローカル`docling`解析エンジンを内蔵オフライン環境やデータプライバシー重視の場面に最適
- **DocuTranslate**標準版、オンラインの `minerU` エンジンを使用してドキュメントを解析します。ほとんどのユーザーに推奨されます。
- **DocuTranslate_full**完全版`docling` ローカル解析エンジンを内蔵しています。オフラインまたはデータプライバシーにより高い要件があるシナリオに適しています。
## インストール
### pipを使用
### pipを使用する場合
```bash
# 基本インストール
pip install docutranslate
# doclingローカル解析エンジンを使用する場合
# docling ローカル解析エンジンを使用する場合
pip install docutranslate[docling]
```
### uvを使用
### uvを使用する場合
```bash
# 環境初期化
# 環境初期化
uv init
# 基本インストール
uv add docutranslate
# docling拡張インストール
# docling 拡張機能をインストール
uv add docutranslate[docling]
```
### gitを使用
### gitを使用する場合
```bash
# 環境初期化
# 環境初期化
git clone https://github.com/xunbu/docutranslate.git
cd docutranslate
@@ -85,45 +88,42 @@ uv sync
## コアコンセプト:ワークフロー (Workflow)
新バージョンのDocuTranslateの中核は**ワークフロー (Workflow)**
です。各ワークフローは、特定のファイルタイプ向けに設計された完全なエンドツーエンドの翻訳パイプラインです。巨大なクラスとやり取りする代わりに、ファイルタイプに応じて適切なワークフローを選択・設定します。
新バージョンの DocuTranslate のコアは **ワークフロー (Workflow)** です。各ワークフローは特定のファイルタイプ向けに設計された完全なエンドツーエンドの翻訳パイプラインです。これまでのように大きなクラスとやり取りするのではなく、ファイルタイプに応じて適切なワークフローを選択して設定することになります。
**基本的な使用手順は以下の通りです:**
1. **ワークフローの選択**:入力ファイルタイプPDF/WordまたはTXTに基づ`MarkdownBasedWorkflow``TXTWorkflow`
などのワークフローを選択します。
2. **設定の構築**:選択したワークフローに対応する設定オブジェクト(例:`MarkdownBasedWorkflowConfig`
)を作成します。この設定オブジェクトには、以下のようなすべての必要なサブ設定が含まれます
* **コンバーター設定 (Converter Config)**: 元のファイルPDFなどをMarkdownに変換する方法を定義します。
* **トランスレーター設定 (Translator Config)**: 使用するLLM、APIキー、ターゲット言語などを定義します。
* **エクスポーター設定 (Exporter Config)**: 出力形式HTMLなどの特定のオプションを定義します。
1. **ワークフローの選択**入力ファイルタイプPDF/Word または TXTに基づいてワークフローを選択します。例えば`MarkdownBasedWorkflow` または `TXTWorkflow` などです。
2. **設定の構築**:選択したワークフローに対応する設定オブジェクト(`MarkdownBasedWorkflowConfig` など)を作成します。この設定オブジェクトには、以下のような必要なすべてのサブ設定が含まれています:
* **コンバーター設定 (Converter Config)**PDF などの元ファイルを Markdown に変換する方法を定義します。
* **翻訳者設定 (Translator Config)**:使用する LLM、API-Key、対象言語などを定義します
* **エクスポーター設定 (Exporter Config)**HTML などの出力形式の特定オプションを定義します。
3. **ワークフローのインスタンス化**:設定オブジェクトを使用してワークフローのインスタンスを作成します。
4. **翻訳の実行**:ワークフローの`.read_*()`および`.translate()` / `.translate_async()`メソッドを呼び出します。
5. **結果のエクスポート/保存**`.export_to_*()`または`.save_as_*()`メソッドを呼び出して翻訳結果を取得または保存します。
4. **翻訳の実行**:ワークフローの `.read_*()` メソッドと `.translate()` / `.translate_async()` メソッドを呼び出します。
5. **結果のエクスポート/保存**`.export_to_*()` メソッドまたは `.save_as_*()` メソッドを呼び出して翻訳結果を取得または保存します。
## 用可能なワークフロー
## 使用可能なワークフロー
| ワークフロー | 適用シナリオ | 入力形式 | 出力形式 | コア設定クラス |
|:----------------------------|:-------------------------------------------------------------------|:-----------------------------------------|:-----------------------|:------------------------------|
| **`MarkdownBasedWorkflow`** | PDF、Word、画像などのリッチテキストドキュメントを処理。「ファイル Markdown 翻訳 エクスポート」の流れ。 | `.pdf`, `.docx`, `.md`, `.png`, `.jpg` | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | プレーンテキストドキュメントを処理。「txt 翻訳 エクスポート」の流れ。 | `.txt` およびその他のプレーンテキスト形式 | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | jsonファイルを処理。「json 翻訳 エクスポート」の流れ。 | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | docxファイルを処理。「docx 翻訳 エクスポート」の流れ。 | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | xlsxファイルを処理。「xlsx 翻訳 エクスポート」の流れ。 | `.xlsx` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | srtファイルを処理。「srt 翻訳 エクスポート」の流れ。 | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | epubファイルを処理。「epub 翻訳 エクスポート」の流れ。 | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | htmlファイルを処理。「html 翻訳 エクスポート」の流れ。 | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
| ワークフロー | 適用シーン | 入力フォーマット | 出力フォーマット | コア設定クラス |
|:--------------------------|:--------------------------------------------------------------------|:------------------------------------------|:-----------------------|:-----------------------------|
| **`MarkdownBasedWorkflow`** | PDF、Word、画像などのリッチテキスト文書を処理する。フロー:`ファイル -> Markdown -> 翻訳 -> エクスポート`。 | `.pdf`, `.docx`, `.md`, `.png`, `.jpg` など | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | プレーンテキスト文書を処理する。フロー:`txt -> 翻訳 -> エクスポート` | `.txt` およびその他のプレーンテキストフォーマット | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | jsonファイルを処理する。フロー:`json -> 翻訳 -> エクスポート` | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | docxファイルを処理する。フロー:`docx -> 翻訳 -> エクスポート` | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | xlsxファイルを処理する。フロー:`xlsx -> 翻訳 -> エクスポート` | `.xlsx` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | srtファイルを処理する。フロー:`srt -> 翻訳 -> エクスポート` | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | epubファイルを処理する。フロー:`epub -> 翻訳 -> エクスポート` | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | htmlファイルを処理する。フロー:`html -> 翻訳 -> エクスポート` | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
> インタラクティブインターフェースではPDF形式でエクスポート可能
> インタラクティブインターフェースではpdf形式でエクスポートできます
## Web UIAPIサービスの起動
## Web UIAPI サービスの起動
利便性のため、DocuTranslateは機能豊富なWebインターフェースとRESTful APIを提供しています。
使いやすさを考慮して、DocuTranslateは機能豊富なWebインターフェースとRESTful APIを提供しています。
**サービスの起動:**
```bash
# サービスを起動デフォルトポート: 8010
# サービスを起動し、デフォルトポート8010を監視
docutranslate -i
# ポートを指定して起動
@@ -134,14 +134,15 @@ export DOCUTRANSLATE_PORT=8011
docutranslate -i
```
- **インタラクティブインターフェース**: サービス起動後、ブラウザで `http://127.0.0.1:8010`(または指定したポート)にアクセスしてください。
- **APIドキュメント**: 完全なAPIドキュメントSwagger UI`http://127.0.0.1:8010/docs` で利用可能です。
- **インタラクティブインターフェース**: サービス起動した後、ブラウザで `http://127.0.0.1:8010`(または指定したポート)にアクセスしてください。
- **APIドキュメント**: 完全なAPIドキュメントSwagger UI`http://127.0.0.1:8010/docs` にあります。
## 使用方法
### 例1: PDFファイルの翻訳`MarkdownBasedWorkflow`を使用
### 例 1: PDFファイルの翻訳 (`MarkdownBasedWorkflow` を使用)
これは最も一般的なユースケースです。`minerU` エンジンを使用して PDF を Markdown に変換し、LLM で翻訳を行います。ここでは非同期方式を例に挙げます。
これは最も一般的なユースケースです。`minerU`エンジンを使用してPDFをMarkdownに変換し、その後LLMで翻訳を行います。ここでは非同期方式を例示します。
```python
import asyncio
@@ -152,34 +153,34 @@ from docutranslate.exporter.md.md2html_exporter import MD2HTMLExporterConfig
async def main():
# 1. 翻訳機設定構築
# 1. 翻訳機設定構築
translator_config = MDTranslatorConfig(
base_url="https://open.bigmodel.cn/api/paas/v4", # AIプラットフォームのBase URL
api_key="YOUR_ZHIPU_API_KEY", # AIプラットフォームのAPI Key
model_id="glm-4-air", # モデルID
to_lang="English", # ターゲット言語
chunk_size=3000, # テキストチャンクサイズ
concurrent=10 # 並列処理
base_url="https://open.bigmodel.cn/api/paas/v4", # AI プラットフォームの Base URL
api_key="YOUR_ZHIPU_API_KEY", # AI プラットフォームの API Key
model_id="glm-4-air", # モデル ID
to_lang="English", # 目標言語
chunk_size=3000, # テキストチャンクサイズ
concurrent=10 # 同時実行
)
# 2. コンバーター設定構築minerUを使用
# 2. コンバーター設定構築 (minerU を使用)
converter_config = ConverterMineruConfig(
mineru_token="YOUR_MINERU_TOKEN", # minerUトークン
formula_ocr=True # 数式認識を有効
mineru_token="YOUR_MINERU_TOKEN", # あなたの minerU Token
formula_ocr=True # 数式認識を有効にする
)
# 3. メインワークフロー設定構築
# 3. メインワークフロー設定構築
workflow_config = MarkdownBasedWorkflowConfig(
convert_engine="mineru", # 解析エンジン指定
converter_config=converter_config, # コンバーター設定の適用
translator_config=translator_config, # 翻訳機設定の適用
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTMLエクスポート設定
convert_engine="mineru", # 解析エンジン指定
converter_config=converter_config, # コンバーター設定を渡す
translator_config=translator_config, # 翻訳機設定を渡す
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML エクスポート設定
)
# 4. ワークフローインスタンス化
# 4. ワークフローインスタンス化
workflow = MarkdownBasedWorkflow(config=workflow_config)
# 5. ファイル読み込み翻訳実行
# 5. ファイル読み込み翻訳実行
print("ファイルの読み込みと翻訳を開始します...")
workflow.read_path("path/to/your/document.pdf")
await workflow.translate_async()
@@ -187,13 +188,13 @@ async def main():
# workflow.translate()
print("翻訳が完了しました!")
# 6. 結果保存
# 6. 結果保存
workflow.save_as_html(name="translated_document.html")
workflow.save_as_markdown_zip(name="translated_document.zip")
workflow.save_as_markdown(name="translated_document.md") # 画像埋め込みMarkdown
print("ファイル ./output フォルダに保存されました。")
workflow.save_as_markdown(name="translated_document.md") # 画像埋め込んだ markdown
print("ファイル ./output フォルダに保存されました。")
# または直接コンテンツ文字列を取得
# または直接内容文字列を取得
html_content = workflow.export_to_html()
html_content = workflow.export_to_markdown()
# print(html_content)
@@ -203,9 +204,10 @@ if __name__ == "__main__":
asyncio.run(main())
```
### 例2: TXTファイルの翻訳`TXTWorkflow`を使用)
プレーンテキストファイルの場合、ドキュメント解析(変換)ステップが不要なため、プロセスがよりシンプルになります。ここでは非同期方式を例示します。
### 例 2: TXTファイルの翻訳 (`TXTWorkflow` を使用)
純粋なテキストファイルの場合、ドキュメントの解析(変換)ステップが不要なため、プロセスがより簡単です。ここでは非同期方式を例に挙げます。
```python
import asyncio
@@ -215,34 +217,34 @@ from docutranslate.exporter.txt.txt2html_exporter import TXT2HTMLExporterConfig
async def main():
# 1. 翻訳機の設定を構築
# 1. 翻訳設定を構築する
translator_config = TXTTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="日本語",
to_lang="中文",
)
# 2. メインワークフロー設定を構築
# 2. メインワークフロー設定を構築する
workflow_config = TXTWorkflowConfig(
translator_config=translator_config,
html_exporter_config=TXT2HTMLExporterConfig(cdn=True)
)
# 3. ワークフローをインスタンス化
# 3. ワークフローをインスタンス化する
workflow = TXTWorkflow(config=workflow_config)
# 4. ファイルを読み込み、翻訳を実行
# 4. ファイルを読み取り、翻訳を実行する
workflow.read_path("path/to/your/notes.txt")
await workflow.translate_async()
# または同期メソッドを使用
# または同期メソッドを使用する
# workflow.translate()
# 5. 結果を保存
# 5. 結果を保存する
workflow.save_as_txt(name="translated_notes.txt")
print("TXTファイルが保存されました。")
print("TXT ファイルが保存されました。")
# 翻訳後のプレーンテキストをエクスポートすることも可能
# 翻訳されたプレーンテキストをエクスポートすることもできます
text = workflow.export_to_txt()
@@ -250,10 +252,12 @@ if __name__ == "__main__":
asyncio.run(main())
```
### 例3: JSONファイルを翻訳する`JsonWorkflow`を使用)
ここでは非同期方式を例とします。JsonTranslatorConfigのjson_paths項目は、翻訳するJSONパスjsonpath-ng構文に準拠を指定する必要があり、
JSONパスに一致する値のみが翻訳されます。
### 例 3: json ファイルを翻訳する (`JsonWorkflow` を使用)
ここでは非同期方式を例として示します。JsonTranslatorConfig の json_paths 項目では、翻訳する json パスを指定する必要がありますjsonpath-ng 構文規則に準拠)。
json パスに一致する値のみが翻訳されます。
```python
import asyncio
@@ -264,35 +268,35 @@ from docutranslate.workflow.json_workflow import JsonWorkflowConfig, JsonWorkflo
async def main():
# 1. 翻訳機の設定を構築
# 1. 翻訳設定を構築する
translator_config = JsonTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="日本語",
json_paths=["$.*", "$.name"] # jsonpath-ngパス構文を満たし、一致するパスの値が翻訳されます
to_lang="中文",
json_paths=["$.*", "$.name"] # jsonpath-ngパス構文に準拠し、パスに一致する値がすべて翻訳されます
)
# 2. メインワークフロー設定を構築
# 2. メインワークフロー設定を構築する
workflow_config = JsonWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Json2HTMLExporterConfig(cdn=True)
)
# 3. ワークフローをインスタンス化
# 3. ワークフローをインスタンス化する
workflow = JsonWorkflow(config=workflow_config)
# 4. ファイルを読み込み、翻訳を実行
# 4. ファイルを読み取り、翻訳を実行する
workflow.read_path("path/to/your/notes.json")
await workflow.translate_async()
# または同期メソッドを使用
# または同期メソッドを使用する
# workflow.translate()
# 5. 結果を保存
# 5. 結果を保存する
workflow.save_as_json(name="translated_notes.json")
print("jsonファイルが保存されました。")
# 翻訳後のjsonテキストをエクスポートすることも可能
# 翻訳されたjsonテキストをエクスポートすることもできます
text = workflow.export_to_json()
@@ -300,9 +304,10 @@ if __name__ == "__main__":
asyncio.run(main())
```
### 例4: docxファイルを翻訳する`DocxWorkflow`を使用)
ここでは非同期方式を例とします。
### 例 4: docx ファイルを翻訳する (`DocxWorkflow` を使用)
ここでは非同期方式を例として示します。
```python
import asyncio
@@ -313,36 +318,36 @@ from docutranslate.workflow.docx_workflow import DocxWorkflowConfig, DocxWorkflo
async def main():
# 1. 翻訳機の設定を構築
# 1. 翻訳設定を構築する
translator_config = DocxTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="日本語",
insert_mode="replace", # オプション "replace", "append", "prepend"
separator="\n", # "append", "prepend"モードで使用るセパレータ
insert_mode="replace", # オプション: "replace", "append", "prepend"
separator="\n", # "append", "prepend"モードで使用されるセパレータ
)
# 2. メインワークフロー設定を構築
# 2. メインワークフロー設定を構築する
workflow_config = DocxWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Docx2HTMLExporterConfig(cdn=True)
)
# 3. ワークフローをインスタンス化
# 3. ワークフローをインスタンス化する
workflow = DocxWorkflow(config=workflow_config)
# 4. ファイルを読み込み、翻訳を実行
# 4. ファイルを読み込み、翻訳を実行する
workflow.read_path("path/to/your/notes.docx")
await workflow.translate_async()
# または同期メソッドを使用
# または同期メソッドを使用する
# workflow.translate()
# 5. 結果を保存
# 5. 結果を保存する
workflow.save_as_docx(name="translated_notes.docx")
print("docxファイルが保存されました。")
# 翻訳後のdocxバイナリエクスポートすることも可能
# 翻訳されたdocxバイナリエクスポートすることもできる
text_bytes = workflow.export_to_docx()
@@ -350,9 +355,11 @@ if __name__ == "__main__":
asyncio.run(main())
```
### 例5: xlsxファイルを翻訳する`XlsxWorkflow`を使用)
ここでは非同期方式を例とします。
### 例 5: xlsxファイルを翻訳する (`XlsxWorkflow` を使用)
ここでは非同期方式を例に挙げます。
```python
import asyncio
@@ -363,36 +370,36 @@ from docutranslate.workflow.xlsx_workflow import XlsxWorkflowConfig, XlsxWorkflo
async def main():
# 1. 翻訳機の設定を構築
# 1. 翻訳設定を構築する
translator_config = XlsxTranslatorConfig(
base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o",
to_lang="日本語",
insert_mode="replace", # オプション "replace", "append", "prepend"
separator="\n", # "append", "prepend"モードで使用るセパレータ
insert_mode="replace", # オプション: "replace", "append", "prepend"
separator="\n", # "append", "prepend"モードで使用されるセパレータ
)
# 2. メインワークフロー設定を構築
# 2. メインワークフロー設定を構築する
workflow_config = XlsxWorkflowConfig(
translator_config=translator_config,
html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True)
)
# 3. ワークフローをインスタンス化
# 3. ワークフローをインスタンス化する
workflow = XlsxWorkflow(config=workflow_config)
# 4. ファイルを読み込み、翻訳を実行
# 4. ファイルを読み込み、翻訳を実行する
workflow.read_path("path/to/your/notes.xlsx")
await workflow.translate_async()
# または同期メソッドを使用
# または同期メソッドを使用する
# workflow.translate()
# 5. 結果を保存
# 5. 結果を保存する
workflow.save_as_xlsx(name="translated_notes.xlsx")
print("xlsxファイルが保存されました。")
# 翻訳後のxlsxバイナリエクスポートすることも可能
# 翻訳されたxlsxバイナリエクスポートすることもできる
text_bytes = workflow.export_to_xlsx()
@@ -400,55 +407,55 @@ if __name__ == "__main__":
asyncio.run(main())
```
## 前提条件と設定の詳細説明
### 1. 大規模言語モデルAPIキーの取得
翻訳機能は大規模言語モデルに依存しており、対応するAIプラットフォームから`base_url``api_key``model_id`を取得する必要があります。
> 推奨モデル:火山引擎の`doubao-seed-1-6-250615`、`doubao-seed-1-6-flash-250715`、智譜の`glm-4-flash`、阿里雲の`qwen-plus`、
> `qwen-turbo`、deepseekの`deepseek-chat`など。
> 推奨モデル:火山引擎の`doubao-seed-1-6-250615`、`doubao-seed-1-6-flash-250715`、智譜の`glm-4-flash`、アリババクラウドの`qwen-plus`、`qwen-turbo`、deepseekの`deepseek-chat`など。
| プラットフォーム名 | APIキー取得方法 | baseurl |
|------------|-------------------------------------------------------------------------------------------|----------------------------------------------------------|
| プラットフォーム名 | APIキー取得方法 | baseurl |
|------------|-----------------------------------------------------------------------------------|----------------------------------------------------------|
| ollama | | http://127.0.0.1:11434/v1 |
| lm studio | | http://127.0.0.1:1234/v1 |
| openrouter | [クリックして取得](https://openrouter.ai/settings/keys) | https://openrouter.ai/api/v1 |
| openai | [クリックして取得](https://platform.openai.com/api-keys) | https://api.openai.com/v1/ |
| gemini | [クリックして取得](https://aistudio.google.com/u/0/apikey) | https://generativelanguage.googleapis.com/v1beta/openai/ |
| deepseek | [クリックして取得](https://platform.deepseek.com/api_keys) | https://api.deepseek.com/v1 |
| 智譜AI | [クリックして取得](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 |
| テンセント混元 | [クリックして取得](https://console.cloud.tencent.com/hunyuan/api-key) | https://api.hunyuan.cloud.tencent.com/v1 |
| 阿里百煉 | [クリックして取得](https://bailian.console.aliyun.com/?tab=model#/api-key) | https://dashscope.aliyuncs.com/compatible-mode/v1 |
| 智譜ai | [クリックして取得](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 |
| 騰訊混元 | [クリックして取得](https://console.cloud.tencent.com/hunyuan/api-key) | https://api.hunyuan.cloud.tencent.com/v1 |
| 阿里百煉 | [クリックして取得](https://bailian.console.aliyun.com/?tab=model#/api-key) | https://dashscope.aliyuncs.com/compatible-mode/v1 |
| 火山引擎 | [クリックして取得](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | https://ark.cn-beijing.volces.com/api/v3 |
| 硅基流動 | [クリックして取得](https://cloud.siliconflow.cn/account/ak) | https://api.siliconflow.cn/v1 |
| DMXAPI | [クリックして取得](https://www.dmxapi.cn/token) | https://www.dmxapi.cn/v1 |
### 2. minerUトークンの取得(オンライン解析)
### 2. minerU Token の取得(オンライン解析)
`mineru`ドキュメント解析エンジンとして選択する場合(`convert_engine="mineru"`)、無料のトークンを申請する必要があります。
ドキュメント解析エンジンとして `mineru` を選択した場合(`convert_engine="mineru"`)、無料の Token を申請する必要があります。
1. [minerU公式サイト](https://mineru.net/apiManage/docs)にアクセスし、登録してAPIを申請します。
2. [APIトークン管理画面](https://mineru.net/apiManage/token)で新しいAPIトークンを作成します。
1. [minerU 公式サイト](https://mineru.net/apiManage/docs) にアクセスし、登録して API を申請します。
2. [API Token 管理画面](https://mineru.net/apiManage/token) で新しい API Token を作成します。
> **注意**: minerUトークンは14日間有効で、期限切れの場合は再作成してください。
> **注意**: minerU Token の有効期限は14日です。期限切れの場合は再作成してください。
### 3. doclingエンジンの設定ローカル解析
### 3. docling エンジンの設定(ローカル解析)
`docling`ドキュメント解析エンジンとして選択する場合(`convert_engine="docling"`)、初回使用時にHugging
Faceから必要なモデルがダウンロードされます。
ドキュメント解析エンジンとして `docling` を選択した場合(`convert_engine="docling"`)、初回使用時に必要なモデルが Hugging Face からダウンロードされます。
**ネットワーク問題の解決策:**
1. **Hugging Faceミラーの設定推奨**:
1. **Hugging Face ミラーの設定(推奨)**:
* **方法A環境変数**: システム環境変数`HF_ENDPOINT`を設定し、IDEまたはターミナルを再起動します。
* **方法 A環境変数**: システム環境変数 `HF_ENDPOINT` を設定し、IDE またはターミナルを再起動します。
```
HF_ENDPOINT=https://hf-mirror.com
```
* **方法Bコード内設定**: Pythonスクリプトの先頭に以下のコードを追加します。
* **方法 Bコード内設定)**: Python スクリプトの先頭に以下のコードを追加します。
```python
import os
@@ -456,12 +463,14 @@ import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
```
2. **オフライン使用(モデルパッケージの事前ダウンロード)**:
* [GitHub Releases](https://github.com/xunbu/docutranslate/releases)から`docling_artifact.zip`をダウンロードします。
* 解凍してプロジェクトディレクトリに配置します。
2. **オフライン使用(事前にモデルパッケージをダウンロード)**:
* [GitHub Releases](https://github.com/xunbu/docutranslate/releases) から `docling_artifact.zip` をダウンロードします。
* プロジェクトディレクトリに解凍します。
* 設定でモデルパスを指定します:
```python
from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig
@@ -472,31 +481,29 @@ converter_config = ConverterDoclingConfig(
)
```
## FAQ
**Q: 8010ポートが使用中の場合どうすればよいですか?**
A: `-p`パラメータで新しいポートを指定するか、`DOCUTRANSLATE_PORT`環境変数を設定してください。
**Q: 8010ポートが占有されている場合どうしますか?**
A: `-p` パラメータで新しいポートを指定するか、`DOCUTRANSLATE_PORT` 環境変数を設定してください。
**Q: スキャンした文書の翻訳はサポートされていますか?**
A: サポートされています。強力なOCR機能を備えた`mineru`解析エンジンを使用してください。
**Q: スキャン文書の翻訳はサポートされていますか?**
A: サポートされています。強力なOCR機能を備えた `mineru` 解析エンジンを使用してください。
**Q: 初回使用時になぜ遅いのですか?**
A: `docling`エンジンを使用する場合、初回実行時にHugging Faceからモデルをダウンロードする必要があります。上記の「ネットワーク問題の解決策」を参照してこのプロセスを高速化してください。
**Q: 初回使用時に遅いのはなぜですか?**
A: `docling` エンジンを使用する場合、初回実行時に Hugging Face からモデルをダウンロードする必要があります。このプロセスを加速するには、上記の「ネットワーク問題の解決策」を参照してください。
**Q: イントラネット(オフライン)環境で使用するにはどうすればよいですか?**
**Q: イントラネット(オフライン)環境でどのように使用できますか?**
A: 完全に可能です。以下の2つの条件を満たす必要があります
1. **ローカル解析エンジン**: `docling`エンジンを使用し、上記の「オフライン使用」の手順に従ってモデルパッケージを事前にダウンロードします。
2. **ローカルLLM**: [Ollama](https://ollama.com/)[LM Studio](https://lmstudio.ai/)などのツールを使用してローカルに言語モデルをデプロイし、
`TranslatorConfig`にローカルモデルの`base_url`を入力します。
1. **ローカル解析エンジン**: `docling` エンジンを使用し、上記の「オフライン使用」のガイドに従って事前にモデルパッケージをダウンロードします。
2. **ローカル LLM**: [Ollama](https://ollama.com/)[LM Studio](https://lmstudio.ai/) などのツールを使用してローカルに言語モデルをデプロイし、`TranslatorConfig` でローカルモデルの `base_url` を入力します。
**Q: キャッシュメカニズムはどのように機能しますか?**
A: `MarkdownBasedWorkflow`
は、ドキュメント解析ファイルからMarkdownへの変換の結果を自動的にキャッシュし、時間とリソースを節約します。キャッシュはデフォルトでメモリに保存され、直近の10回の解析が記録されます。
`DOCUTRANSLATE_CACHE_NUM`環境変数でキャッシュ数を変更できます。
A: `MarkdownBasedWorkflow` はドキュメント解析ファイルからMarkdownへの変換の結果を自動的にキャッシュし、繰り返し解析による時間とリソースの浪費を回避します。キャッシュはデフォルトでメモリに保存され、直近の10回の解析が記録されます。環境変数 `DOCUTRANSLATE_CACHE_NUM` を通じてキャッシュ数を変更することができます。
**Q: ソフトウェアをプロキシ経由で使用するにはどうすればよいですか**
A: ソフトウェアはデフォルトでプロキシを使用しません。環境変数`DOCUTRANSLATE_USE_PROXY``true`に設定することでプロキシ経由で使用できます。
**Q: ソフトウェアをプロキシ経由で使用するにはどうすればよいですか**
A: ソフトウェアはデフォルトでプロキシを使用しません。環境変数 `DOCUTRANSLATE_USE_PROXY``true` に設定することで、ソフトウェアがプロキシ経由で通信するようになります。
## スター履歴
@@ -504,6 +511,6 @@ A: ソフトウェアはデフォルトでプロキシを使用しません。
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=xunbu/docutranslate&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=xunbu/docutranslate&type=Date" />
<img alt="スター履歴チャート" src="https://api.star-history.com/svg?repos=xunbu/docutranslate&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=xunbu/docutranslate&type=Date" />
</picture>
</a>