This commit is contained in:
xunbu
2025-12-04 20:31:17 +08:00
parent 3b72f2ae95
commit 0d80eaac3c
7 changed files with 984 additions and 758 deletions

398
README.md
View File

@@ -1,5 +1,5 @@
<p align="center"> <p align="center">
<img src="./DocuTranslate.png" alt="Project Logo" style="width: 150px"> <img src="./DocuTranslate.png" alt="Project Logo" style="width: 150px">
</p> </p>
<h1 align="center">DocuTranslate</h1> <h1 align="center">DocuTranslate</h1>
@@ -17,51 +17,40 @@
</p> </p>
<p align="center"> <p align="center">
A lightweight local file translation tool based on Large Language Models A lightweight local file translation tool based on Large Language Models.
</p> </p>
-**Multiple Format Support**: Translates various files including `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, `epub`, -**Support Multiple Formats**: Translates `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, `epub`, `srt`, `ass`, and more.
`srt`, `ass`, and more. -**Auto-Generate Glossary**: Supports automatic glossary generation to ensure term alignment.
-**Automatic Glossary Generation**: Supports automatic generation of glossaries for term alignment. -**PDF Table, Formula, Code Recognition**: Leverages `docling` and `mineru` PDF parsing engines to recognize and translate tables, formulas, and code often found in academic papers.
-**PDF Table, Formula, and Code Recognition**: Recognizes and translates tables, formulas, and code often found in -**JSON Translation**: Supports specifying values to translate within JSON using paths (`jsonpath-ng` syntax).
academic papers, powered by `docling` and `mineru` PDF parsing engines. -**Word/Excel Format Preservation**: Supports `docx` and `xlsx` files (currently does not support `doc` or `xls`) while maintaining original formatting.
-**JSON Translation**: Supports specifying values to be translated in JSON using JSON paths (following `jsonpath-ng` -**Multi-AI Platform Support**: Supports most AI platforms, allowing for high-performance concurrent AI translation with custom prompts.
syntax). -**Async Support**: Designed for high-performance scenarios, providing full asynchronous support and interfaces for parallel multi-tasking.
-**Word/Excel Format Preservation**: Translates `docx` and `xlsx` files while preserving their original formatting ( -**LAN & Multi-user Support**: Supports simultaneous use by multiple users within a local area network (LAN).
does not yet support `doc` or `xls` files). -**Interactive Web Interface**: Provides an out-of-the-box Web UI and RESTful API for easy integration and usage.
-**Multi-AI Platform Support**: Compatible with most AI platforms, enabling high-performance, concurrent AI -**Compact, Portable Packages**: Windows and Mac portable packages under 40MB (versions that do not use `docling` for local PDF parsing).
translation with custom prompts.
-**Asynchronous Support**: Designed for high-performance scenarios with full asynchronous support, offering service
interfaces for parallel tasks.
-**LAN and Multi-user Support**: Can be used by multiple people simultaneously on a local area network.
-**Interactive Web Interface**: Provides an out-of-the-box Web UI and RESTful API for easy integration and use.
-**Small, Multi-platform Standalone Packages**: Windows and Mac standalone packages under 40MB (for versions not
using the `docling` local PDF parser).
> When translating `pdf` files, they are first converted to Markdown, which will **cause the original layout to be lost > When translating `pdf`, it is first converted to markdown. This will **lose** the original layout. Users with strict layout requirements should take note.
**. Users with strict layout requirements should take note.
> QQ Discussion Group: 1047781902 > QQ Community Group: 1047781902
**UI Interface**: **UI Interface**:
![Translation Effect](/images/UI界面.png) ![UI Interface](/images/UI界面.png)
**Academic Paper Translation**: **Paper Translation**:
![Translation Effect](/images/论文翻译.png) ![Paper Translation](/images/论文翻译.png)
**Novel Translation**: **Novel Translation**:
![Translation Effect](/images/小说翻译.png) ![Novel Translation](/images/小说翻译.png)
## All-in-One Packages ## Integration Packages
For users who want to get started quickly, we provide all-in-one packages For users who want to get started quickly, we provide integration packages on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). simply download, unzip, and enter your AI platform API-Key to start using it.
on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). Simply download, unzip, and enter your AI
platform API Key to begin.
- **DocuTranslate**: Standard version, uses the online `minerU` engine to parse PDF documents. Choose this version if - **DocuTranslate**: Standard version. Uses the online `minerU` engine to parse PDF documents. Choose this version if you do not need local PDF parsing (Recommended).
you don't need local PDF parsing (recommended). - **DocuTranslate_full**: Full version. Includes the built-in `docling` local PDF parsing engine. Choose this version if you need to parse PDFs locally.
- **DocuTranslate_full**: Full version, includes the built-in `docling` local PDF parsing engine. Choose this version if > Version 1.5.1 and later support calling a locally deployed mineru service.
you need local PDF parsing.
## Installation ## Installation
@@ -71,7 +60,7 @@ platform API Key to begin.
# Basic installation # Basic installation
pip install docutranslate pip install docutranslate
# To use docling for local PDF parsing # If you need to use docling for local PDF parsing
pip install docutranslate[docling] pip install docutranslate[docling]
``` ```
@@ -102,69 +91,64 @@ uv sync
## Core Concept: Workflow ## Core Concept: Workflow
The core of the new DocuTranslate is the **Workflow**. Each workflow is a complete, end-to-end translation pipeline The core of the new DocuTranslate is the **Workflow**. Each workflow is a complete end-to-end translation pipeline designed for a specific file type. Instead of interacting with a massive class, you select and configure a suitable workflow based on your file type.
designed for a specific file type. Instead of interacting with a single large class, you select and configure a workflow
based on your file type.
**The basic usage flow is as follows:** **The basic usage flow is as follows:**
1. **Select a Workflow**: Choose a workflow based on your input file type (e.g., PDF/Word or TXT), such as 1. **Select Workflow**: Choose a workflow based on your input file type (e.g., PDF/Word or TXT), such as `MarkdownBasedWorkflow` or `TXTWorkflow`.
`MarkdownBasedWorkflow` or `TXTWorkflow`. 2. **Build Configuration**: Create the corresponding configuration object for the selected workflow (e.g., `MarkdownBasedWorkflowConfig`). This configuration object contains all necessary sub-configurations, such as:
2. **Build Configuration**: Create the corresponding configuration object for the selected workflow (e.g., * **Converter Config**: Defines how to convert the original file (e.g., PDF) to Markdown.
`MarkdownBasedWorkflowConfig`). This object contains all necessary sub-configurations, such as: * **Translator Config**: Defines which LLM, API-Key, target language, etc., to use.
* **Converter Config**: Defines how to convert the original file (like a PDF) to Markdown. * **Exporter Config**: Defines specific options for the output format (e.g., HTML).
* **Translator Config**: Defines which LLM, API-Key, target language, etc., to use. 3. **Instantiate Workflow**: Create a workflow instance using the configuration object.
* **Exporter Config**: Defines specific options for the output format (like HTML). 4. **Execute Translation**: Call the workflow's `.read_*()` and `.translate()` / `.translate_async()` methods.
3. **Instantiate the Workflow**: Create an instance of the workflow using the configuration object. 5. **Export/Save Results**: Call `.export_to_*()` or `.save_as_*()` methods to get or save the translation results.
4. **Execute Translation**: Call the workflow's `.read_*()` and `.translate()` / `.translate_async()` methods.
5. **Export/Save Results**: Call the `.export_to_*()` or `.save_as_*()` methods to get or save the translation results.
## Available Workflows ## Available Workflows
| Workflow | Use Case | Input Formats | Output Formats | Core Config Class | | Workflow | Applicable Scenarios | Input Formats | Output Formats | Core Configuration Class |
|:----------------------------|:-------------------------------------------------------------------------------------------------------|:---------------------------------------------|:-----------------------|:------------------------------| |:---|:---|:---|:---|:---|
| **`MarkdownBasedWorkflow`** | Processes rich text documents like PDF, Word, images. Flow: `File -> Markdown -> Translate -> Export`. | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` | | **`MarkdownBasedWorkflow`** | Handles rich text documents like PDF, Word, images, etc. Flow: `File -> Markdown -> Translate -> Export`. | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | Processes plain text documents. Flow: `txt -> Translate -> Export`. | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` | | **`TXTWorkflow`** | Handles plain text documents. Flow: `txt -> Translate -> Export`. | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | Processes JSON files. Flow: `json -> Translate -> Export`. | `.json` | `.json`, `.html` | `JsonWorkflowConfig` | | **`JsonWorkflow`** | Handles JSON files. Flow: `json -> Translate -> Export`. | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | Processes docx files. Flow: `docx -> Translate -> Export`. | `.docx` | `.docx`, `.html` | `DocxWorkflowConfig` | | **`DocxWorkflow`** | Handles docx files. Flow: `docx -> Translate -> Export`. | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | Processes xlsx files. Flow: `xlsx -> Translate -> Export`. | `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` | | **`XlsxWorkflow`** | Handles xlsx files. Flow: `xlsx -> Translate -> Export`. | `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | Processes srt files. Flow: `srt -> Translate -> Export`. | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` | | **`SrtWorkflow`** | Handles srt files. Flow: `srt -> Translate -> Export`. | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | Processes epub files. Flow: `epub -> Translate -> Export`. | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` | | **`EpubWorkflow`** | Handles epub files. Flow: `epub -> Translate -> Export`. | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | Processes html files. Flow: `html -> Translate -> Export`. | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` | | **`HtmlWorkflow`** | Handles html files. Flow: `html -> Translate -> Export`. | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
> You can export to PDF format in the interactive interface. > In the interactive interface, you can also export to PDF format.
## Launch Web UI and API Service ## Start Web UI and API Service
For ease of use, DocuTranslate provides a full-featured Web interface and RESTful API. For ease of use, DocuTranslate provides a fully functional Web Interface and RESTful API.
**Start the service:** **Start the Service:**
```bash ```bash
# Start the service, listening on port 8010 by default # Start service, defaults to listening on port 8010
docutranslate -i docutranslate -i
# Start on a specific port # Start on a specific port
docutranslate -i -p 8011 docutranslate -i -p 8011
# Allow Cross-Origin Requests # Allow CORS requests
docutranslate -i --cors docutranslate -i --cors
# You can also specify the port via an environment variable
# You can also specify the port via environment variable
export DOCUTRANSLATE_PORT=8011 export DOCUTRANSLATE_PORT=8011
docutranslate -i docutranslate -i
``` ```
- **Interactive Interface**: After starting the service, visit `http://127.0.0.1:8010` (or your specified port) in your - **Interactive Interface**: After starting the service, please visit `http://127.0.0.1:8010` (or your specified port) in your browser.
browser. - **API Documentation**: Full API documentation (Swagger UI) is located at `http://127.0.0.1:8010/docs`.
- **API Documentation**: The complete API documentation (Swagger UI) is available at `http://127.0.0.1:8010/docs`.
## Usage ## Usage Examples
### Example 1: Translate a PDF file (using `MarkdownBasedWorkflow`) ### Example 1: Translate a PDF File (Using `MarkdownBasedWorkflow`)
This is the most common use case. We will use the `minerU` engine to convert the PDF to Markdown and then use an LLM for This is the most common use case. We will use the `minerU` engine to convert the PDF to Markdown, and then translate it using an LLM. This example uses asynchronous execution.
translation. This example uses the asynchronous method.
```python ```python
import asyncio import asyncio
@@ -175,51 +159,67 @@ from docutranslate.exporter.md.md2html_exporter import MD2HTMLExporterConfig
async def main(): async def main():
# 1. Build translator configuration # 1. Build Translator Configuration
translator_config = MDTranslatorConfig( translator_config = MDTranslatorConfig(
base_url="https://open.bigmodel.cn/api/paas/v4", # AI Platform Base URL base_url="https://open.bigmodel.cn/api/paas/v4", # AI Platform Base URL
api_key="YOUR_ZHIPU_API_KEY", # AI Platform API Key api_key="YOUR_ZHIPU_API_KEY", # AI Platform API Key
model_id="glm-4-air", # Model ID model_id="glm-4-air", # Model ID
to_lang="English", # Target language to_lang="English", # Target Language
chunk_size=3000, # Text chunk size chunk_size=3000, # Text chunk size
concurrent=10, # Concurrency level concurrent=10, # Concurrency level
# glossary_generate_enable=True, # Enable automatic glossary generation # glossary_generate_enable=True, # Enable auto-glossary generation
# glossary_dict={"Jobs":"乔布斯"}, # Pass in a glossary # glossary_dict={"Jobs":"Steve Jobs"}, # Pass in a glossary dictionary
# system_proxy_enable=True, # Enable system proxy # system_proxy_enable=True, # Enable system proxy
) )
# 2. Build converter configuration (using minerU) # 2. Build Converter Configuration (Using minerU)
converter_config = ConverterMineruConfig( converter_config = ConverterMineruConfig(
mineru_token="YOUR_MINERU_TOKEN", # Your minerU Token mineru_token="YOUR_MINERU_TOKEN", # Your minerU Token
formula_ocr=True # Enable formula recognition formula_ocr=True # Enable formula recognition
) )
# 3. Build main workflow configuration # 3. Build Main Workflow Configuration
workflow_config = MarkdownBasedWorkflowConfig( workflow_config = MarkdownBasedWorkflowConfig(
convert_engine="mineru", # Specify the parsing engine convert_engine="mineru", # Specify parsing engine
converter_config=converter_config, # Pass the converter config converter_config=converter_config, # Pass converter config
translator_config=translator_config, # Pass the translator config translator_config=translator_config, # Pass translator config
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export configuration html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export config
) )
# 4. Instantiate the workflow # Using locally deployed mineru service
# from docutranslate.converter.x2md.converter_mineru_deploy import ConverterMineruDeployConfig
# converter_config = ConverterMineruDeployConfig(
# base_url = "http://127.0.0.1:8000",
# output_dir= "./output", # Due to mineru limitations, parsed files are saved to output_dir and need periodic cleaning
# backend= "pipeline",
# start_page_id = 0,
# end_page_id = 99999,
# )
# workflow_config = MarkdownBasedWorkflowConfig(
# convert_engine="mineru_deploy", # Specify parsing engine
# converter_config=converter_config, # Pass converter config
# translator_config=translator_config, # Pass translator config
# html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export config
# )
# 4. Instantiate Workflow
workflow = MarkdownBasedWorkflow(config=workflow_config) workflow = MarkdownBasedWorkflow(config=workflow_config)
# 5. Read the file and execute translation # 5. Read file and execute translation
print("Reading and translating the file...") print("Starting to read and translate file...")
workflow.read_path("path/to/your/document.pdf") workflow.read_path("path/to/your/document.pdf")
await workflow.translate_async() await workflow.translate_async()
# Or use the synchronous method # Or use synchronous method
# workflow.translate() # workflow.translate()
print("Translation complete!") print("Translation complete!")
# 6. Save the results # 6. Save results
workflow.save_as_html(name="translated_document.html") workflow.save_as_html(name="translated_document.html")
workflow.save_as_markdown_zip(name="translated_document.zip") workflow.save_as_markdown_zip(name="translated_document.zip")
workflow.save_as_markdown(name="translated_document.md") # Markdown with embedded images workflow.save_as_markdown(name="translated_document.md") # Markdown with embedded images
print("Files saved to the ./output folder.") print("Files saved to ./output folder.")
# Or get the content strings directly # Or get content strings directly
html_content = workflow.export_to_html() html_content = workflow.export_to_html()
html_content = workflow.export_to_markdown() html_content = workflow.export_to_markdown()
# print(html_content) # print(html_content)
@@ -229,10 +229,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 2: Translate a TXT file (using `TXTWorkflow`) ### Example 2: Translate a TXT File (Using `TXTWorkflow`)
For plain text files, the process is simpler as it doesn't require a document parsing (conversion) step. This example For plain text files, the process is simpler as it doesn't require a document parsing (conversion) step. This example uses asynchronous execution.
uses the asynchronous method.
```python ```python
import asyncio import asyncio
@@ -242,7 +241,7 @@ from docutranslate.exporter.txt.txt2html_exporter import TXT2HTMLExporterConfig
async def main(): async def main():
# 1. Build translator configuration # 1. Build Translator Configuration
translator_config = TXTTranslatorConfig( translator_config = TXTTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
@@ -250,22 +249,22 @@ async def main():
to_lang="Chinese", to_lang="Chinese",
) )
# 2. Build main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = TXTWorkflowConfig( workflow_config = TXTWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=TXT2HTMLExporterConfig(cdn=True) html_exporter_config=TXT2HTMLExporterConfig(cdn=True)
) )
# 3. Instantiate the workflow # 3. Instantiate Workflow
workflow = TXTWorkflow(config=workflow_config) workflow = TXTWorkflow(config=workflow_config)
# 4. Read the file and execute translation # 4. Read file and execute translation
workflow.read_path("path/to/your/notes.txt") workflow.read_path("path/to/your/notes.txt")
await workflow.translate_async() await workflow.translate_async()
# Or use the synchronous method # Or use synchronous method
# workflow.translate() # workflow.translate()
# 5. Save the result # 5. Save results
workflow.save_as_txt(name="translated_notes.txt") workflow.save_as_txt(name="translated_notes.txt")
print("TXT file saved.") print("TXT file saved.")
@@ -277,10 +276,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 3: Translate a JSON file (using `JsonWorkflow`) ### Example 3: Translate a JSON File (Using `JsonWorkflow`)
This example uses the asynchronous method. The `json_paths` item in `JsonTranslatorConfig` needs to specify the JSON This example uses asynchronous execution. In `JsonTranslatorConfig`, the `json_paths` item needs to specify the JSON paths to be translated (following `jsonpath-ng` syntax specifications); only values matching the JSON paths will be translated.
paths to be translated (conforming to the `jsonpath-ng` syntax). Only values matching these paths will be translated.
```python ```python
import asyncio import asyncio
@@ -291,31 +289,31 @@ from docutranslate.workflow.json_workflow import JsonWorkflowConfig, JsonWorkflo
async def main(): async def main():
# 1. Build translator configuration # 1. Build Translator Configuration
translator_config = JsonTranslatorConfig( translator_config = JsonTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="Chinese", to_lang="Chinese",
json_paths=["$.*", "$.name"] # Conforms to jsonpath-ng syntax, values at matching paths will be translated json_paths=["$.*", "$.name"] # Satisfies jsonpath-ng syntax, values at matching paths will be translated
) )
# 2. Build main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = JsonWorkflowConfig( workflow_config = JsonWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Json2HTMLExporterConfig(cdn=True) html_exporter_config=Json2HTMLExporterConfig(cdn=True)
) )
# 3. Instantiate the workflow # 3. Instantiate Workflow
workflow = JsonWorkflow(config=workflow_config) workflow = JsonWorkflow(config=workflow_config)
# 4. Read the file and execute translation # 4. Read file and execute translation
workflow.read_path("path/to/your/notes.json") workflow.read_path("path/to/your/notes.json")
await workflow.translate_async() await workflow.translate_async()
# Or use the synchronous method # Or use synchronous method
# workflow.translate() # workflow.translate()
# 5. Save the result # 5. Save results
workflow.save_as_json(name="translated_notes.json") workflow.save_as_json(name="translated_notes.json")
print("JSON file saved.") print("JSON file saved.")
@@ -327,9 +325,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 4: Translate a DOCX file (using `DocxWorkflow`) ### Example 4: Translate a Docx File (Using `DocxWorkflow`)
This example uses the asynchronous method. This example uses asynchronous execution.
```python ```python
import asyncio import asyncio
@@ -340,36 +338,36 @@ from docutranslate.workflow.docx_workflow import DocxWorkflowConfig, DocxWorkflo
async def main(): async def main():
# 1. Build translator configuration # 1. Build Translator Configuration
translator_config = DocxTranslatorConfig( translator_config = DocxTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="Chinese", to_lang="Chinese",
insert_mode="replace", # Options: "replace", "append", "prepend" insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used in "append" and "prepend" modes separator="\n", # Separator used for "append", "prepend" modes
) )
# 2. Build main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = DocxWorkflowConfig( workflow_config = DocxWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Docx2HTMLExporterConfig(cdn=True) html_exporter_config=Docx2HTMLExporterConfig(cdn=True)
) )
# 3. Instantiate the workflow # 3. Instantiate Workflow
workflow = DocxWorkflow(config=workflow_config) workflow = DocxWorkflow(config=workflow_config)
# 4. Read the file and execute translation # 4. Read file and execute translation
workflow.read_path("path/to/your/notes.docx") workflow.read_path("path/to/your/notes.docx")
await workflow.translate_async() await workflow.translate_async()
# Or use the synchronous method # Or use synchronous method
# workflow.translate() # workflow.translate()
# 5. Save the result # 5. Save results
workflow.save_as_docx(name="translated_notes.docx") workflow.save_as_docx(name="translated_notes.docx")
print("DOCX file saved.") print("docx file saved.")
# You can also export the translated DOCX as bytes # You can also export the translated docx bytes
text_bytes = workflow.export_to_docx() text_bytes = workflow.export_to_docx()
@@ -377,9 +375,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 5: Translate an XLSX file (using `XlsxWorkflow`) ### Example 5: Translate an Xlsx File (Using `XlsxWorkflow`)
This example uses the asynchronous method. This example uses asynchronous execution.
```python ```python
import asyncio import asyncio
@@ -390,36 +388,36 @@ from docutranslate.workflow.xlsx_workflow import XlsxWorkflowConfig, XlsxWorkflo
async def main(): async def main():
# 1. Build translator configuration # 1. Build Translator Configuration
translator_config = XlsxTranslatorConfig( translator_config = XlsxTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="Chinese", to_lang="Chinese",
insert_mode="replace", # Options: "replace", "append", "prepend" insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used in "append" and "prepend" modes separator="\n", # Separator used for "append", "prepend" modes
) )
# 2. Build main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = XlsxWorkflowConfig( workflow_config = XlsxWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True) html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True)
) )
# 3. Instantiate the workflow # 3. Instantiate Workflow
workflow = XlsxWorkflow(config=workflow_config) workflow = XlsxWorkflow(config=workflow_config)
# 4. Read the file and execute translation # 4. Read file and execute translation
workflow.read_path("path/to/your/notes.xlsx") workflow.read_path("path/to/your/notes.xlsx")
await workflow.translate_async() await workflow.translate_async()
# Or use the synchronous method # Or use synchronous method
# workflow.translate() # workflow.translate()
# 5. Save the result # 5. Save results
workflow.save_as_xlsx(name="translated_notes.xlsx") workflow.save_as_xlsx(name="translated_notes.xlsx")
print("XLSX file saved.") print("xlsx file saved.")
# You can also export the translated XLSX as bytes # You can also export the translated xlsx bytes
text_bytes = workflow.export_to_xlsx() text_bytes = workflow.export_to_xlsx()
@@ -427,9 +425,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 5: Configuration Items for Other Workflows (Using `HtmlWorkflow`, `EpubWorkflow`) ### Example 6: Config Options for Other Workflows (Using `HtmlWorkflow`, `EpubWorkflow`)
Here is an example using asynchronous mode. This example uses asynchronous execution.
```python ```python
# HtmlWorkflow # HtmlWorkflow
@@ -438,17 +436,17 @@ from docutranslate.workflow.html_workflow import HtmlWorkflowConfig, HtmlWorkflo
async def html(): async def html():
# 1. Create translator configuration # 1. Build Translator Configuration
translator_config = HtmlTranslatorConfig( translator_config = HtmlTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="Chinese", to_lang="Chinese",
insert_mode="replace", # Options: "replace", "append", "prepend" insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used for "append" and "prepend" modes separator="\n", # Separator used for "append", "prepend" modes
) )
# 2. Create main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = HtmlWorkflowConfig( workflow_config = HtmlWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
) )
@@ -462,17 +460,17 @@ from docutranslate.workflow.epub_workflow import EpubWorkflowConfig, EpubWorkflo
async def epub(): async def epub():
# 1. Create translator configuration # 1. Build Translator Configuration
translator_config = EpubTranslatorConfig( translator_config = EpubTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="Chinese", to_lang="Chinese",
insert_mode="replace", # Options: "replace", "append", "prepend" insert_mode="replace", # Options: "replace", "append", "prepend"
separator="\n", # Separator used for "append" and "prepend" modes separator="\n", # Separator used for "append", "prepend" modes
) )
# 2. Create main workflow configuration # 2. Build Main Workflow Configuration
workflow_config = EpubWorkflowConfig( workflow_config = EpubWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Epub2HTMLExporterConfig(cdn=True), html_exporter_config=Epub2HTMLExporterConfig(cdn=True),
@@ -480,64 +478,59 @@ async def epub():
workflow_epub = EpubWorkflow(config=workflow_config) workflow_epub = EpubWorkflow(config=workflow_config)
``` ```
## Prerequisites and Configuration Details ## Prerequisites and Detailed Configuration
### 1. Get a Large Model API Key ### 1. Get Large Model API Key
The translation feature relies on large language models. You need to obtain a `base_url`, `api_key`, and `model_id` from Translation functionality relies on Large Language Models. You need to obtain a `base_url`, `api_key`, and `model_id` from the corresponding AI platform.
the respective AI platform.
> Recommended models: Volcengine's `doubao-seed-1-6-flash` and `doubao-seed-1-6` series, Zhipu's `glm-4-flash`, Alibaba > Recommended Models: Volcengine's `doubao-seed-1-6-flash`, `doubao-seed-1-6` series, Zhipu's `glm-4-flash`, Alibaba Cloud's `qwen-plus`, `qwen-flash`, Deepseek's `deepseek-chat`, etc.
> Cloud's `qwen-plus` and `qwen-flash`, Deepseek's `deepseek-chat`, etc.
> [302.AI](https://share.302.ai/BgRLAe)👈 Register through this link to enjoy a $1 free credit > [302.AI](https://share.302.ai/BgRLAe) 👈 Register via this link to get $1 free credit.
| Platform Name | Get API Key | Base URL | | Platform Name | Get API Key | Base URL |
|:------------------------------|:----------------------------------------------------------------------------------------------|:-----------------------------------------------------------| |:---|:---|:---|
| ollama | | `http://127.0.0.1:11434/v1` | | ollama | | http://127.0.0.1:11434/v1 |
| lm studio | | `http://127.0.0.1:1234/v1` | | lm studio | | http://127.0.0.1:1234/v1 |
| 302.AI | [Click to get](https://share.302.ai/BgRLAe) | `https://api.302.ai/v1` | | 302.AI | [Click to Get](https://share.302.ai/BgRLAe) | https://api.302.ai/v1 |
| openrouter | [Click to get](https://openrouter.ai/settings/keys) | `https://openrouter.ai/api/v1` | | openrouter | [Click to Get](https://openrouter.ai/settings/keys) | https://openrouter.ai/api/v1 |
| openai | [Click to get](https://platform.openai.com/api-keys) | `https://api.openai.com/v1/` | | openai | [Click to Get](https://platform.openai.com/api-keys) | https://api.openai.com/v1/ |
| gemini | [Click to get](https://aistudio.google.com/u/0/apikey) | `https://generativelanguage.googleapis.com/v1beta/openai/` | | gemini | [Click to Get](https://aistudio.google.com/u/0/apikey) | https://generativelanguage.googleapis.com/v1beta/openai/ |
| deepseek | [Click to get](https://platform.deepseek.com/api_keys) | `https://api.deepseek.com/v1` | | deepseek | [Click to Get](https://platform.deepseek.com/api_keys) | https://api.deepseek.com/v1 |
| Zhipu AI (智谱ai) | [Click to get](https://open.bigmodel.cn/usercenter/apikeys) | `https://open.bigmodel.cn/api/paas/v4` | | Zhipu AI | [Click to Get](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 |
| Tencent Hunyuan (腾讯混元) | [Click to get](https://console.cloud.tencent.com/hunyuan/api-key) | `https://api.hunyuan.cloud.tencent.com/v1` | | Tencent Hunyuan | [Click to Get](https://console.cloud.tencent.com/hunyuan/api-key) | https://api.hunyuan.cloud.tencent.com/v1 |
| Alibaba Cloud Bailian (阿里云百炼) | [Click to get](https://bailian.console.aliyun.com/?tab=model#/api-key) | `https://dashscope.aliyuncs.com/compatible-mode/v1` | | Alibaba Bailian | [Click to Get](https://bailian.console.aliyun.com/?tab=model#/api-key) | https://dashscope.aliyuncs.com/compatible-mode/v1 |
| Volcengine (火山引擎) | [Click to get](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | `https://ark.cn-beijing.volces.com/api/v3` | | Volcengine | [Click to Get](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | https://ark.cn-beijing.volces.com/api/v3 |
| SiliconFlow (硅基流动) | [Click to get](https://cloud.siliconflow.cn/account/ak) | `https://api.siliconflow.cn/v1` | | SiliconFlow | [Click to Get](https://cloud.siliconflow.cn/account/ak) | https://api.siliconflow.cn/v1 |
| DMXAPI | [Click to get](https://www.dmxapi.cn/token) | `https://www.dmxapi.cn/v1` | | DMXAPI | [Click to Get](https://www.dmxapi.cn/token) | https://www.dmxapi.cn/v1 |
| Juguang AI (聚光AI) | [Click to get](https://ai.juguang.chat/console/token) | `https://ai.juguang.chat/v1` | | Juguang AI | [Click to Get](https://ai.juguang.chat/console/token) | https://ai.juguang.chat/v1 |
### 2. PDF Parsing Engine (ignore if not translating PDFs) ### 2. PDF Parsing Engine (Skip if you don't need to translate PDFs)
#### 2.1 Get a minerU Token (Online PDF parsing, free, recommended) ### 2.1 Get minerU Token (Online PDF Parsing, Free, Recommended)
If you choose `mineru` as your document parsing engine (`convert_engine="mineru"`), you need to apply for a free token. If you choose `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) to register and apply for an API. 1. Visit [minerU Website](https://mineru.net/apiManage/docs) to register and apply for the API.
2. Create a new API Token in the [API Token Management interface](https://mineru.net/apiManage/token). 2. Create a new API Token in the [API Token Management Interface](https://mineru.net/apiManage/token).
> **Note**: minerU Tokens are valid for 14 days. Please create a new one after expiration. > **Note**: The minerU Token is valid for 14 days. Please recreate it after expiration.
#### 2.2. docling Engine Configuration (Local PDF parsing) ### 2.2. docling Engine Configuration (Local PDF Parsing)
If you choose `docling` as your document parsing engine (`convert_engine="docling"`), it will download the required If you choose `docling` as the document parsing engine (`convert_engine="docling"`), it will download the required models from Hugging Face upon first use.
models from Hugging Face upon first use.
> A better option is to download `docling_artifact.zip` > A better option is to download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases) and unzip it into your working directory.
> from [GitHub Releases](https://github.com/xunbu/docutranslate/releases) and extract it to your working directory.
**Solutions for network issues when downloading `docling` models:** **Solutions for `docling` Model Download Network Issues:**
1. **Set a Hugging Face mirror (Recommended)**: 1. **Set Hugging Face Mirror (Recommended)**:
* **Method A (Environment Variable)**: Set the system environment variable `HF_ENDPOINT` and restart your IDE or
terminal.
```
HF_ENDPOINT=https://hf-mirror.com
```
* **Method B (Set in code)**: Add the following code at the beginning of your Python script. * **Method A (Environment Variable)**: Set the system environment variable `HF_ENDPOINT` and restart your IDE or terminal.
```
HF_ENDPOINT=https://hf-mirror.com
```
* **Method B (In Code)**: Add the following code at the beginning of your Python script.
```python ```python
import os import os
@@ -545,17 +538,17 @@ import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
``` ```
2. **Offline Usage (Download the model package in advance)**: 2. **Offline Use (Pre-download Model Package)**:
* Download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases).
* Extract it into your project directory.
* Specify the model path in your configuration (if the model is not in the same directory as the script): * Download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases).
* Unzip it into your project directory.
* Specify the model path in the configuration (if the model is not in the same directory as the script):
```python ```python
from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig
converter_config = ConverterDoclingConfig( converter_config = ConverterDoclingConfig(
artifact="./docling_artifact", # Path to the extracted folder artifact="./docling_artifact", # Point to the unzipped folder
code_ocr=True, code_ocr=True,
formula_ocr=True formula_ocr=True
) )
@@ -563,36 +556,29 @@ converter_config = ConverterDoclingConfig(
## FAQ ## FAQ
**Q: Why is the translated text still in the original language?** **Q: Why is the output still in the original language?**
A: Check the logs for errors. It's usually due to an overdue payment on the AI platform or network issues (check if you A: Check the logs for errors. It is usually due to the AI platform running out of credits or network issues (check if system proxy needs to be enabled).
need to enable the system proxy).
**Q: Port 8010 is already in use. What should I do?** **Q: Port 8010 is occupied, what should I do?**
A: Use the `-p` parameter to specify a new port, or set the `DOCUTRANSLATE_PORT` environment variable. A: Use the `-p` parameter to specify a new port, or set the `DOCUTRANSLATE_PORT` environment variable.
**Q: Does it support translating scanned PDFs?** **Q: Are scanned PDFs supported?**
A: Yes. Please use the `mineru` parsing engine, which has powerful OCR capabilities. A: Yes. Please use the `mineru` parsing engine, which has powerful OCR capabilities.
**Q: Why is the first PDF translation very slow?** **Q: Why is the first PDF translation very slow?**
A: If you are using the `docling` engine, it needs to download models from Hugging Face on its first run. Please refer A: If you are using the `docling` engine, it needs to download models from Hugging Face on the first run. Please refer to the "Network Issues Solutions" section above to speed up this process.
to the "Network Issues Solutions" section above to speed up this process.
**Q: How can I use it in an intranet (offline) environment?** **Q: How can I use it in an Intranet (Offline) environment?**
A: Absolutely. You need to meet the following conditions: A: Absolutely. You need to meet the following conditions:
1. **Local LLM**: Deploy a language model locally using tools like [Ollama](https://ollama.com/) 1. **Local LLM**: Use tools like [Ollama](https://ollama.com/) or [LM Studio](https://lmstudio.ai/) to deploy the language model locally, and enter the local model's `base_url` in `TranslatorConfig`.
or [LM Studio](https://lmstudio.ai/), and fill in the local model's `base_url` in `TranslatorConfig`. 2. **Local PDF Parsing Engine** (Only needed for PDF parsing): Use the `docling` engine and follow the "Offline Use" instructions above to pre-download the model package.
2. **Local PDF Parsing Engine** (only for parsing PDFs): Use the `docling` engine and download the model package in
advance as described in the "Offline Usage" section above.
**Q: How does the PDF parsing cache mechanism work?** **Q: How does the PDF parsing cache mechanism work?**
A: `MarkdownBasedWorkflow` automatically caches the results of document parsing (file-to-Markdown conversion) to avoid A: `MarkdownBasedWorkflow` automatically caches the results of document parsing (file-to-Markdown conversion) to avoid repeated parsing consuming time and resources. The cache is stored in memory by default and records the last 10 parses. You can modify the cache size via the `DOCUTRANSLATE_CACHE_NUM` environment variable.
repetitive, time-consuming parsing. The cache is stored in memory by default and records the last 10 parses. You can
change the cache size using the `DOCUTRANSLATE_CACHE_NUM` environment variable.
**Q: How can I make the software use a proxy?** **Q: How to enable proxy support for the software?**
A: By default, the software does not use the system proxy. You can enable it by setting `system_proxy_enable=True` in A: The software does not use the system proxy by default. You can enable it by setting `system_proxy_enable=True` in `TranslatorConfig`.
`TranslatorConfig`.
## Star History ## Star History
@@ -604,10 +590,10 @@ A: By default, the software does not use the system proxy. You can enable it by
</picture> </picture>
</a> </a>
## Sponsorship ## Donation Support
Your support is welcome! Please mention the reason for your donation in the memo. Welcome to support the author. Please specify the reason for the donation in the comments!
<p align="center"> <p align="center">
<img src="./images/赞赏码.jpg" alt="Sponsorship QR Code" style="width: 250px;"> <img src="./images/赞赏码.jpg" alt="Donation Code" style="width: 250px;">
</p> </p>

View File

@@ -1,5 +1,5 @@
<p align="center"> <p align="center">
<img src="./DocuTranslate.png" alt="プロジェクトロゴ" style="width: 150px"> <img src="./DocuTranslate.png" alt="プロジェクトロゴ" style="width: 150px">
</p> </p>
<h1 align="center">DocuTranslate</h1> <h1 align="center">DocuTranslate</h1>
@@ -17,69 +17,67 @@
</p> </p>
<p align="center"> <p align="center">
大規模言語モデルをベースにした軽量なローカルファイル翻訳ツール 大規模言語モデルLLMに基づいた軽量なローカルファイル翻訳ツール
</p> </p>
-**多様なフォーマットをサポート**`pdf``docx``xlsx``md``txt``json``epub``srt``ass`など、さまざまなファイル翻訳できます -**多形式対応**`pdf``docx``xlsx``md``txt``json``epub``srt``ass`など、多様なファイル翻訳に対応
-**用語集自動生成**:用語の整合性を保つための用語集自動生成をサポートします -**用語集自動生成**:用語のアライメント(統一)を実現するための用語集自動生成をサポート。
-**PDFの表数式コード認識**`docling``mineru` PDF解析エンジンにより、学術論文によく見られる表、数式、コード認識翻訳します -**PDFの表数式コード認識**`docling``mineru`といったPDF解析エンジンにより、学術論文によくる表、数式、コード認識翻訳を実現
-**JSON翻訳**JSONパス`jsonpath-ng`構文仕様を使用して、JSON内で翻訳が必要な値を指定できます -**JSON翻訳**JSONパス`jsonpath-ng`構文)による翻訳対象値の指定をサポート
-**Word/Excelのフォーマットを維持した翻訳**`docx``xlsx`ファイルの元のフォーマットを維持したまま翻訳をサポートします(現在 -**Word/Excelの書式保持翻訳**`docx``xlsx`ファイル`doc``xls`は未対応)の書式を保持したまま翻訳可能。
`doc``xls`ファイルは未対応) -**マルチAIプラットフォーム対応**ほぼ全てのAIプラットフォームに対応し、カスタムプロンプトによる高性能な並行AI翻訳を実現
-**複数のAIプラットフォームをサポート**ほとんどのAIプラットフォームに対応しており、カスタムプロンプトによる並行高性能なAI翻訳が可能です -**非同期サポート**:高性能なシナリオ向けに設計され、完全な非同期サポートを提供し、マルチタスク並列処理可能なサービスインターフェースを実装
-**非同期サポート**:高性能なシーン向けに設計され、完全な非同期サポートを提供し、複数のタスクを並行実行できるサービスインターフェースを実現します -**LAN・複数人利用対応**LAN内での複数人同時利用をサポート
-**LAN、複数人での使用をサポート**:ローカルエリアネットワーク内で複数人が同時に使用できます -**インタラクティブなWeb画面**すぐに使えるWeb UIとRESTful APIを提供し、統合と使用が容易
-**インタラクティブなWebインターフェース**すぐに使えるWeb UIとRESTful APIを提供し、統合と使用が容易です -**軽量・マルチプラットフォーム対応のポータブルパッケージ**40MB未満のWindows/Mac用ポータブルパッケージ`docling`ローカル解析を含まないバージョン)を提供
-**小型でマルチプラットフォーム対応の統合パッケージ**40MB未満のWindows、Mac用統合パッケージ`docling`
ローカルPDF解析を使用しないバージョン
> `pdf`を翻訳する際、まずMarkdownに変換されるため、元のレイアウトが**失われます**。レイアウトにこだわりがあるユーザーはご注意ください。 > `pdf`を翻訳する際、まずMarkdownに変換されるため、元のレイアウトが**失われます**。レイアウトを重視するユーザーはご注意ください。
> QQ交流グループ1047781902 > QQ交流グループ1047781902
**UI画面** **UI画面**
![翻訳効果](/images/UI界面.png) ![UI画面](/images/UI界面.png)
**論文翻訳** **論文翻訳**
![翻訳効果](/images/文翻.png) ![論文翻訳](/images/文翻.png)
**小説翻訳** **小説翻訳**
![翻訳効果](/images/小说翻译.png) ![小説翻訳](/images/小说翻译.png)
## 統合パッケージ ## 統合パッケージ
すぐに始めたいユーザーのために、[GitHub Releases](https://github.com/xunbu/docutranslate/releases) すぐに使い始めたいユーザー向けに、[GitHub Releases](https://github.com/xunbu/docutranslate/releases) で統合パッケージを提供しています。ダウンロードして解凍し、AIプラットフォームのAPIキーを入力するだけで使用を開始できます。
で統合パッケージを提供しています。ダウンロードして解凍し、AIプラットフォームのAPIキーを入力するだけで使用を開始できます。
- **DocuTranslate**: 標準版。オンラインの`minerU`エンジンを使用してPDFドキュメントを解析します。ローカルでのPDF解析が不要な場合はこのバージョンを選択してください(推奨)。 - **DocuTranslate**: 標準版。オンラインの `minerU` エンジンを使用してPDFドキュメントを解析します。ローカルでのPDF解析が不要な場合はこちらを選択してください(推奨)。
- **DocuTranslate_full**: 完全版。`docling`ローカルPDF解析エンジンを内蔵しています。ローカルでPDF解析が必要な場合はこのバージョンを選択してください。 - **DocuTranslate_full**: 完全版。`docling` ローカルPDF解析エンジンを内蔵しています。ローカルでPDF解析する必要がある場合はこちらを選択してください。
> バージョン1.5.1以降、ローカルにデプロイされたmineruサービスの呼び出しをサポートしています。
## インストール ## インストール
### pipを使用 ### pipを使用する場合
```bash ```bash
# 基本的なインストール # 基本インストール
pip install docutranslate pip install docutranslate
# doclingを使用してローカルPDF解析する場合 # doclingローカルPDF解析を行う場合
pip install docutranslate[docling] pip install docutranslate[docling]
``` ```
### uvを使用 ### uvを使用する場合
```bash ```bash
# 環境の初期化 # 環境の初期化
uv init uv init
# 基本的なインストール # 基本インストール
uv add docutranslate uv add docutranslate
# docling拡張機能のインストール # docling拡張のインストール
uv add docutranslate[docling] uv add docutranslate[docling]
``` ```
### gitを使用 ### gitを使用する場合
```bash ```bash
# 環境の初期化 # 環境の初期化
@@ -93,66 +91,64 @@ uv sync
## コアコンセプト:ワークフロー (Workflow) ## コアコンセプト:ワークフロー (Workflow)
新しいDocuTranslateの中核は**ワークフロー (Workflow)** 新しい DocuTranslate の核となるのは **ワークフロー (Workflow)** です。各ワークフローは、特定の種類のファイル用に設計された、完全なエンドツーエンドの翻訳パイプラインです。巨大なクラスとやり取りするのではなく、ファイルの種類に基づいて適切なワークフローを選択し、設定します。
です。各ワークフローは、特定のファイルタイプ専用に設計された、完全なエンドツーエンドの翻訳パイプラインです。巨大な単一クラスと対話する代わりに、ファイルタイプに応じて適切なワークフローを選択し、設定します。
**基本的な使用手順は以下の通りです:** **基本的な使用手順は以下の通りです:**
1. **ワークフローの選択**:入力ファイルタイプPDF/WordまたはTXT応じて、`MarkdownBasedWorkflow``TXTWorkflow` 1. **ワークフローの選択**:入力ファイルの種類PDF/Word または TXT基づいて、`MarkdownBasedWorkflow``TXTWorkflow` などのワークフローを選択します。
などのワークフローを選択します。 2. **設定の構築**:選択したワークフローに対応する設定オブジェクト(例:`MarkdownBasedWorkflowConfig`)を作成します。この設定オブジェクトには、必要なすべてのサブ設定が含まれます:
2. **設定の構築**:選択したワークフローに対応する設定オブジェクト(例:`MarkdownBasedWorkflowConfig` * **コンバータ設定 (Converter Config)**: 元のファイルPDFをMarkdownに変換する方法を定義します。
)を作成します。この設定オブジェクトには、以下のような必要なすべてのサブ設定が含まれます:
* **コンバーター設定 (Converter Config)**: 元のファイルPDFなどをMarkdownに変換する方法を定義します。
* **翻訳機設定 (Translator Config)**: 使用するLLM、APIキー、ターゲット言語などを定義します。 * **翻訳機設定 (Translator Config)**: 使用するLLM、APIキー、ターゲット言語などを定義します。
* **エクスポータ設定 (Exporter Config)**: 出力フォーマット(HTMLなど)の特定のオプションを定義します。 * **エクスポータ設定 (Exporter Config)**: 出力形式(例:HTMLの特定のオプションを定義します。
3. **ワークフローのインスタンス化**:設定オブジェクトを使用してワークフローのインスタンスを作成します。 3. **ワークフローのインスタンス化**:設定オブジェクトを使用してワークフローのインスタンスを作成します。
4. **翻訳の実行**:ワークフローの`.read_*()`および`.translate()` / `.translate_async()`メソッドを呼び出します。 4. **翻訳の実行**:ワークフローの `.read_*()` および `.translate()` / `.translate_async()` メソッドを呼び出します。
5. **結果のエクスポート/保存**`.export_to_*()`または`.save_as_*()`メソッドを呼び出して翻訳結果を取得または保存します。 5. **結果のエクスポート/保存**`.export_to_*()` または `.save_as_*()` メソッドを呼び出して翻訳結果を取得または保存します。
## 利用可能なワークフロー ## 利用可能なワークフロー
| ワークフロー | 適用シーン | 入力フォーマット | 出力フォーマット | コア設定クラス | | ワークフロー | 適用シナリオ | 入力形式 | 出力形式 | コア設定クラス |
|:----------------------------|:-----------------------------------------------------------------------|:------------------------------------------|:-----------------------|:------------------------------| |:---|:---|:---|:---|:---|
| **`MarkdownBasedWorkflow`** | PDF、Word、画像などのリッチテキストドキュメントを処理。フロー`ファイル -> Markdown -> 翻訳 -> エクスポート`。 | `.pdf`, `.docx`, `.md`, `.png`, `.jpg` など | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` | | **`MarkdownBasedWorkflow`** | PDF、Word、画像などのリッチテキストドキュメントを処理。フロー`ファイル -> Markdown -> 翻訳 -> エクスポート`。 | `.pdf`, `.docx`, `.md`, `.png`, `.jpg` | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | プレーンテキストドキュメントを処理。フロー:`txt -> 翻訳 -> エクスポート` | `.txt` およびその他のプレーンテキスト形式 | `.txt`, `.html` | `TXTWorkflowConfig` | | **`TXTWorkflow`** | プレーンテキストドキュメントを処理。フロー:`txt -> 翻訳 -> エクスポート`。 | `.txt` およびその他のテキスト形式 | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | JSONファイルを処理。フロー`json -> 翻訳 -> エクスポート` | `.json` | `.json`, `.html` | `JsonWorkflowConfig` | | **`JsonWorkflow`** | JSONファイルを処理。フロー`json -> 翻訳 -> エクスポート`| `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | docxファイルを処理。フロー`docx -> 翻訳 -> エクスポート` | `.docx` | `.docx`, `.html` | `DocxWorkflowConfig` | | **`DocxWorkflow`** | docxファイルを処理。フロー`docx -> 翻訳 -> エクスポート`| `.docx` | `.docx`, `.html` | `docxWorkflowConfig` |
| **`XlsxWorkflow`** | xlsxファイルを処理。フロー`xlsx -> 翻訳 -> エクスポート` | `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` | | **`XlsxWorkflow`** | xlsxファイルを処理。フロー`xlsx -> 翻訳 -> エクスポート`| `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | srtファイルを処理。フロー`srt -> 翻訳 -> エクスポート` | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` | | **`SrtWorkflow`** | srtファイルを処理。フロー`srt -> 翻訳 -> エクスポート`| `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | epubファイルを処理。フロー`epub -> 翻訳 -> エクスポート` | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` | | **`EpubWorkflow`** | epubファイルを処理。フロー`epub -> 翻訳 -> エクスポート`| `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | htmlファイルを処理。フロー`html -> 翻訳 -> エクスポート` | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` | | **`HtmlWorkflow`** | htmlファイルを処理。フロー`html -> 翻訳 -> エクスポート`| `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
> インタラクティブインターフェースではPDF形式でエクスポートできます。 > インタラクティブ画面ではPDF形式でエクスポートも可能です。
## Web UIAPIサービスの起動 ## Web UIAPI サービスの起動
利便性のために、DocuTranslateは機能豊富なWebインターフェースとRESTful APIを提供しています。 使いやすくするために、DocuTranslate は機能豊富な Web インターフェースと RESTful API を提供しています。
**サービスの起動:** **サービスの起動:**
```bash ```bash
# サービス起動し、デフォルトで8010ポートをリッスンします # サービス起動デフォルトでポート8010をリッスン
docutranslate -i docutranslate -i
# ポートを指定して起動 # ポートを指定して起動
docutranslate -i -p 8011 docutranslate -i -p 8011
# クロスオリジンリクエストを許可する # CORSリクエストを許可
docutranslate -i --cors docutranslate -i --cors
# 環境変数でポートを指定することもできます
# 環境変数でポートを指定することも可能
export DOCUTRANSLATE_PORT=8011 export DOCUTRANSLATE_PORT=8011
docutranslate -i docutranslate -i
``` ```
- **インタラクティブインターフェース**: サービス起動後、ブラウザで`http://127.0.0.1:8010`または指定したポートにアクセスしてください。 - **インタラクティブ画面**: サービス起動後、ブラウザで `http://127.0.0.1:8010` (または指定したポート) にアクセスしてください。
- **APIドキュメント**: 完全なAPIドキュメントSwagger UI)は`http://127.0.0.1:8010/docs`にあります。 - **API ドキュメント**: 完全な API ドキュメント (Swagger UI) は `http://127.0.0.1:8010/docs` にあります。
## 使用方法 ## 使用方法
### 例1PDFファイルの翻訳 (`MarkdownBasedWorkflow`を使用) ### 例 1: PDFファイルの翻訳 (`MarkdownBasedWorkflow` を使用)
これ最も一般的な使用例です。`minerU`エンジンを使用してPDFMarkdownに変換し、LLMで翻訳します。ここでは非同期方式を例にとります。 これ最も一般的なユースケースです。`minerU` エンジンを使用して PDFMarkdown に変換し、その後 LLM を使用して翻訳します。ここでは非同期方式を例にます。
```python ```python
import asyncio import asyncio
@@ -163,51 +159,67 @@ from docutranslate.exporter.md.md2html_exporter import MD2HTMLExporterConfig
async def main(): async def main():
# 1. 翻訳機設定構築 # 1. 翻訳機設定構築
translator_config = MDTranslatorConfig( translator_config = MDTranslatorConfig(
base_url="https://open.bigmodel.cn/api/paas/v4", # AIプラットフォームBase URL base_url="https://open.bigmodel.cn/api/paas/v4", # AIプラットフォーム Base URL
api_key="YOUR_ZHIPU_API_KEY", # AIプラットフォームAPIキー api_key="YOUR_ZHIPU_API_KEY", # AIプラットフォーム API Key
model_id="glm-4-air", # モデルID model_id="glm-4-air", # モデル ID
to_lang="English", # ターゲット言語 to_lang="English", # ターゲット言語
chunk_size=3000, # テキストのチャンクサイズ chunk_size=3000, # テキスト分割サイズ
concurrent=10, # 並列 concurrent=10, # 同時並行
# glossary_generate_enable=True, # 用語集自動生成を有効にする # glossary_generate_enable=True, # 用語集自動生成を有効
# glossary_dict={"Jobs":"ジョブズ"}, # 用語集を渡す # glossary_dict={"Jobs":"ジョブズ"}, # 用語集を渡す
# system_proxy_enable=True,# システムプロキシを有効にする # system_proxy_enable=True,# システムプロキシを有効
) )
# 2. コンバーターの設定構築 (minerUを使用) # 2. コンバータ設定構築 (minerUを使用)
converter_config = ConverterMineruConfig( converter_config = ConverterMineruConfig(
mineru_token="YOUR_MINERU_TOKEN", # あなたのminerUトークン mineru_token="YOUR_MINERU_TOKEN", # あなたの minerU Token
formula_ocr=True # 数式認識を有効にする formula_ocr=True # 数式認識を有効
) )
# 3. メインワークフロー設定構築 # 3. メインワークフロー設定構築
workflow_config = MarkdownBasedWorkflowConfig( workflow_config = MarkdownBasedWorkflowConfig(
convert_engine="mineru", # 解析エンジンを指定 convert_engine="mineru", # 解析エンジンを指定
converter_config=converter_config, # コンバータ設定を渡す converter_config=converter_config, # コンバータ設定を渡す
translator_config=translator_config, # 翻訳機設定を渡す translator_config=translator_config, # 翻訳機設定を渡す
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTMLエクスポート設定 html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTMLエクスポート設定
) )
# 4. ワークフローをインスタンス化 # ローカルデプロイされたmineruサービスを使用する場合
# from docutranslate.converter.x2md.converter_mineru_deploy import ConverterMineruDeployConfig
# converter_config = ConverterMineruDeployConfig(
# base_url = "http://127.0.0.1:8000",
# output_dir= "./output",# mineruの制限により、解析後のファイルはoutput_dir下に保存されるため、定期的なクリーニングが必要です
# backend= "pipeline",
# start_page_id = 0,
# end_page_id = 99999,
# )
# workflow_config = MarkdownBasedWorkflowConfig(
# convert_engine="mineru_deploy", # 解析エンジンを指定
# converter_config=converter_config, # コンバータ設定を渡す
# translator_config=translator_config, # 翻訳機設定を渡す
# html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTMLエクスポート設定
# )
# 4. ワークフローのインスタンス化
workflow = MarkdownBasedWorkflow(config=workflow_config) workflow = MarkdownBasedWorkflow(config=workflow_config)
# 5. ファイル読み込んで翻訳実行 # 5. ファイル読み込みと翻訳実行
print("ファイルの読み込みと翻訳を開始します...") print("ファイルの読み込みと翻訳を開始します...")
workflow.read_path("path/to/your/document.pdf") workflow.read_path("path/to/your/document.pdf")
await workflow.translate_async() await workflow.translate_async()
# または同期方式を使用 # または同期方式を使用
# workflow.translate() # workflow.translate()
print("翻訳完了しました") print("翻訳完了!")
# 6. 結果保存 # 6. 結果保存
workflow.save_as_html(name="translated_document.html") workflow.save_as_html(name="translated_document.html")
workflow.save_as_markdown_zip(name="translated_document.zip") workflow.save_as_markdown_zip(name="translated_document.zip")
workflow.save_as_markdown(name="translated_document.md") # 画像埋め込まれたMarkdown workflow.save_as_markdown(name="translated_document.md") # 画像埋め込Markdown
print("ファイルは ./output フォルダに保存されました。") print("ファイルは ./output フォルダに保存されました。")
# または直接コンテンツ文字列を取得 # またはコンテンツ文字列を直接取得
html_content = workflow.export_to_html() html_content = workflow.export_to_html()
html_content = workflow.export_to_markdown() html_content = workflow.export_to_markdown()
# print(html_content) # print(html_content)
@@ -217,9 +229,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例2TXTファイルの翻訳 (`TXTWorkflow`を使用) ### 例 2: TXTファイルの翻訳 (`TXTWorkflow` を使用)
プレーンテキストファイルの場合、ドキュメント解析(変換)ステップが不要なため、プロセスはより簡単です。ここでは非同期方式を例にとります。 プレーンテキストファイルの場合、ドキュメント解析(変換)ステップが不要なため、プロセスはより簡単です。ここでは非同期方式を例にます。
```python ```python
import asyncio import asyncio
@@ -229,34 +241,34 @@ from docutranslate.exporter.txt.txt2html_exporter import TXT2HTMLExporterConfig
async def main(): async def main():
# 1. 翻訳機設定構築 # 1. 翻訳機設定構築
translator_config = TXTTranslatorConfig( translator_config = TXTTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="日本語", to_lang="中文",
) )
# 2. メインワークフロー設定構築 # 2. メインワークフロー設定構築
workflow_config = TXTWorkflowConfig( workflow_config = TXTWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=TXT2HTMLExporterConfig(cdn=True) html_exporter_config=TXT2HTMLExporterConfig(cdn=True)
) )
# 3. ワークフローインスタンス化 # 3. ワークフローインスタンス化
workflow = TXTWorkflow(config=workflow_config) workflow = TXTWorkflow(config=workflow_config)
# 4. ファイル読み込んで翻訳実行 # 4. ファイル読み込みと翻訳実行
workflow.read_path("path/to/your/notes.txt") workflow.read_path("path/to/your/notes.txt")
await workflow.translate_async() await workflow.translate_async()
# または同期方式を使用 # または同期メソッドを使用
# workflow.translate() # workflow.translate()
# 5. 結果保存 # 5. 結果保存
workflow.save_as_txt(name="translated_notes.txt") workflow.save_as_txt(name="translated_notes.txt")
print("TXTファイルが保存されました。") print("TXTファイルが保存されました。")
# 翻訳後のプレーンテキストをエクスポートすることもできます # 翻訳後のテキストをエクスポートすることも可能
text = workflow.export_to_txt() text = workflow.export_to_txt()
@@ -264,10 +276,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例3JSONファイルの翻訳 (`JsonWorkflow`を使用) ### 例 3: JSONファイルの翻訳 (`JsonWorkflow` を使用)
ここでは非同期方式を例にとります。`JsonTranslatorConfig``json_paths`項目で、翻訳したいJSONパス`jsonpath-ng` ここでは非同期方式を例にます。`JsonTranslatorConfig``json_paths` 項目で、翻訳対象のJSONパスjsonpath-ng構文に準拠)を指定する必要があります。パスに一致する値のみが翻訳されます。
構文仕様に準拠を指定する必要があります。JSONパスに一致する値のみが翻訳されます。
```python ```python
import asyncio import asyncio
@@ -278,35 +289,35 @@ from docutranslate.workflow.json_workflow import JsonWorkflowConfig, JsonWorkflo
async def main(): async def main():
# 1. 翻訳機設定構築 # 1. 翻訳機設定構築
translator_config = JsonTranslatorConfig( translator_config = JsonTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="日本語", to_lang="中文",
json_paths=["$.*", "$.name"] # jsonpath-ng構文に準拠、一致するパスの値が翻訳されます json_paths=["$.*", "$.name"] # jsonpath-ngパス構文に準拠、一致するパスの値が翻訳されます
) )
# 2. メインワークフロー設定構築 # 2. メインワークフロー設定構築
workflow_config = JsonWorkflowConfig( workflow_config = JsonWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Json2HTMLExporterConfig(cdn=True) html_exporter_config=Json2HTMLExporterConfig(cdn=True)
) )
# 3. ワークフローインスタンス化 # 3. ワークフローインスタンス化
workflow = JsonWorkflow(config=workflow_config) workflow = JsonWorkflow(config=workflow_config)
# 4. ファイル読み込んで翻訳実行 # 4. ファイル読み込みと翻訳実行
workflow.read_path("path/to/your/notes.json") workflow.read_path("path/to/your/notes.json")
await workflow.translate_async() await workflow.translate_async()
# または同期方式を使用 # または同期メソッドを使用
# workflow.translate() # workflow.translate()
# 5. 結果保存 # 5. 結果保存
workflow.save_as_json(name="translated_notes.json") workflow.save_as_json(name="translated_notes.json")
print("JSONファイルが保存されました。") print("jsonファイルが保存されました。")
# 翻訳後のJSONテキストをエクスポートすることもできます # 翻訳後のjsonテキストをエクスポートすることも可能
text = workflow.export_to_json() text = workflow.export_to_json()
@@ -314,9 +325,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例4DOCXファイルの翻訳 (`DocxWorkflow`を使用) ### 例 4: docxファイルの翻訳 (`DocxWorkflow` を使用)
ここでは非同期方式を例にとります。 ここでは非同期方式を例にます。
```python ```python
import asyncio import asyncio
@@ -327,36 +338,36 @@ from docutranslate.workflow.docx_workflow import DocxWorkflowConfig, DocxWorkflo
async def main(): async def main():
# 1. 翻訳機設定構築 # 1. 翻訳機設定構築
translator_config = DocxTranslatorConfig( translator_config = DocxTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="日本語", to_lang="中文",
insert_mode="replace", # 選択肢: "replace", "append", "prepend" insert_mode="replace", # 選択肢 "replace" (置換), "append" (追記), "prepend" (前置)
separator="\n", # "append", "prepend"モードで使用する区切り文字 separator="\n", # "append", "prepend" モード時の区切り文字
) )
# 2. メインワークフロー設定構築 # 2. メインワークフロー設定構築
workflow_config = DocxWorkflowConfig( workflow_config = DocxWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Docx2HTMLExporterConfig(cdn=True) html_exporter_config=Docx2HTMLExporterConfig(cdn=True)
) )
# 3. ワークフローインスタンス化 # 3. ワークフローインスタンス化
workflow = DocxWorkflow(config=workflow_config) workflow = DocxWorkflow(config=workflow_config)
# 4. ファイル読み込んで翻訳実行 # 4. ファイル読み込みと翻訳実行
workflow.read_path("path/to/your/notes.docx") workflow.read_path("path/to/your/notes.docx")
await workflow.translate_async() await workflow.translate_async()
# または同期方式を使用 # または同期メソッドを使用
# workflow.translate() # workflow.translate()
# 5. 結果保存 # 5. 結果保存
workflow.save_as_docx(name="translated_notes.docx") workflow.save_as_docx(name="translated_notes.docx")
print("docxファイルが保存されました。") print("docxファイルが保存されました。")
# 翻訳後のdocxバイナリデータをエクスポートすることもできます # 翻訳後のdocxバイナリをエクスポートすることも可能
text_bytes = workflow.export_to_docx() text_bytes = workflow.export_to_docx()
@@ -364,9 +375,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例5XLSXファイルの翻訳 (`XlsxWorkflow`を使用) ### 例 5: xlsxファイルの翻訳 (`XlsxWorkflow` を使用)
ここでは非同期方式を例にとります。 ここでは非同期方式を例にます。
```python ```python
import asyncio import asyncio
@@ -377,36 +388,36 @@ from docutranslate.workflow.xlsx_workflow import XlsxWorkflowConfig, XlsxWorkflo
async def main(): async def main():
# 1. 翻訳機設定構築 # 1. 翻訳機設定構築
translator_config = XlsxTranslatorConfig( translator_config = XlsxTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="日本語", to_lang="中文",
insert_mode="replace", # 選択肢: "replace", "append", "prepend" insert_mode="replace", # 選択肢 "replace", "append", "prepend"
separator="\n", # "append", "prepend"モードで使用する区切り文字 separator="\n", # "append", "prepend" モード時の区切り文字
) )
# 2. メインワークフロー設定構築 # 2. メインワークフロー設定構築
workflow_config = XlsxWorkflowConfig( workflow_config = XlsxWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True) html_exporter_config=Xlsx2HTMLExporterConfig(cdn=True)
) )
# 3. ワークフローインスタンス化 # 3. ワークフローインスタンス化
workflow = XlsxWorkflow(config=workflow_config) workflow = XlsxWorkflow(config=workflow_config)
# 4. ファイル読み込んで翻訳実行 # 4. ファイル読み込みと翻訳実行
workflow.read_path("path/to/your/notes.xlsx") workflow.read_path("path/to/your/notes.xlsx")
await workflow.translate_async() await workflow.translate_async()
# または同期方式を使用 # または同期メソッドを使用
# workflow.translate() # workflow.translate()
# 5. 結果保存 # 5. 結果保存
workflow.save_as_xlsx(name="translated_notes.xlsx") workflow.save_as_xlsx(name="translated_notes.xlsx")
print("xlsxファイルが保存されました。") print("xlsxファイルが保存されました。")
# 翻訳後のxlsxバイナリデータをエクスポートすることもできます # 翻訳後のxlsxバイナリをエクスポートすることも可能
text_bytes = workflow.export_to_xlsx() text_bytes = workflow.export_to_xlsx()
@@ -414,9 +425,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例 5: その他のワークフロー設定項目 (`HtmlWorkflow`、`EpubWorkflow` 使用) ### 例 6: その他のワークフロー設定 (`HtmlWorkflow`、`EpubWorkflow` 使用)
以下は非同期モードの使用例です。 ここでは非同期方式を例にします。
```python ```python
# HtmlWorkflow # HtmlWorkflow
@@ -425,17 +436,17 @@ from docutranslate.workflow.html_workflow import HtmlWorkflowConfig, HtmlWorkflo
async def html(): async def html():
# 1. 翻訳機設定を作成 # 1. 翻訳機設定の構築
translator_config = HtmlTranslatorConfig( translator_config = HtmlTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="国語", to_lang="",
insert_mode="replace", # 選択肢: "replace", "append", "prepend" insert_mode="replace", # 選択肢 "replace", "append", "prepend"
separator="\n", # "append", "prepend" モードで使用される区切り文字 separator="\n", # "append", "prepend" モード時の区切り文字
) )
# 2. メインワークフロー設定を作成 # 2. メインワークフロー設定の構築
workflow_config = HtmlWorkflowConfig( workflow_config = HtmlWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
) )
@@ -449,17 +460,17 @@ from docutranslate.workflow.epub_workflow import EpubWorkflowConfig, EpubWorkflo
async def epub(): async def epub():
# 1. 翻訳機設定を作成 # 1. 翻訳機設定の構築
translator_config = EpubTranslatorConfig( translator_config = EpubTranslatorConfig(
base_url="https://api.openai.com/v1/", base_url="https://api.openai.com/v1/",
api_key="YOUR_OPENAI_API_KEY", api_key="YOUR_OPENAI_API_KEY",
model_id="gpt-4o", model_id="gpt-4o",
to_lang="国語", to_lang="",
insert_mode="replace", # 選択肢: "replace", "append", "prepend" insert_mode="replace", # 選択肢 "replace", "append", "prepend"
separator="\n", # "append", "prepend" モードで使用される区切り文字 separator="\n", # "append", "prepend" モード時の区切り文字
) )
# 2. メインワークフロー設定を作成 # 2. メインワークフロー設定の構築
workflow_config = EpubWorkflowConfig( workflow_config = EpubWorkflowConfig(
translator_config=translator_config, translator_config=translator_config,
html_exporter_config=Epub2HTMLExporterConfig(cdn=True), html_exporter_config=Epub2HTMLExporterConfig(cdn=True),
@@ -469,60 +480,57 @@ async def epub():
## 前提条件と設定詳細 ## 前提条件と設定詳細
### 1. 大規模モデルAPIキーの取得 ### 1. 大規模モデル API Key の取得
翻訳機能は大規模言語モデルに依存しているため、対応するAIプラットフォームから`base_url``api_key``model_id`を取得する必要があります。 翻訳機能は大規模言語モデルLLMに依存しており、対応するAIプラットフォームから `base_url``api_key``model_id` を取得する必要があります。
> 推奨モデル:火山引擎の`doubao-seed-1-6-flash`、`doubao-seed-1-6`シリーズ、智譜の`glm-4-flash`、阿里雲の`qwen-plus`、 > 推奨モデル:Volcengineの `doubao-seed-1-6-flash`、`doubao-seed-1-6` シリーズ、Zhipuの `glm-4-flash`、Alibaba Cloudの `qwen-plus`、`qwen-flash`、DeepSeekの `deepseek-chat` など。
`qwen-flash`、deepseekの`deepseek-chat`など。
> [302.AI](https://share.302.ai/BgRLAe)👈 このリンクから登録1ドルの無料クレジットを提供 > [302.AI](https://share.302.ai/BgRLAe)👈このリンクから登録すると、1ドルの無料クレジットがもらえます。
| プラットフォーム名 | APIキー取得 | baseurl | | プラットフォーム名 | API Keyの取得 | baseurl |
|:-----------|:---------------------------------------------------------------------------------------------|:-----------------------------------------------------------| |:---|:---|:---|
| ollama | | `http://127.0.0.1:11434/v1` | | ollama | | http://127.0.0.1:11434/v1 |
| lm studio | | `http://127.0.0.1:1234/v1` | | lm studio | | http://127.0.0.1:1234/v1 |
| 302.AI | [ここをクリックして取得](https://share.302.ai/BgRLAe) | `https://api.302.ai/v1` | | 302.AI | [取得はこちら](https://share.302.ai/BgRLAe) | https://api.302.ai/v1 |
| openrouter | [ここをクリックして取得](https://openrouter.ai/settings/keys) | `https://openrouter.ai/api/v1` | | openrouter | [取得はこちら](https://openrouter.ai/settings/keys) | https://openrouter.ai/api/v1 |
| openai | [ここをクリックして取得](https://platform.openai.com/api-keys) | `https://api.openai.com/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/` | | 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` | | 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` | | 智譜ai (Zhipu) | [取得はこちら](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://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://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` | | 火山引擎 (Volcengine) | [取得はこちら](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` | | SiliconFlow | [取得はこちら](https://cloud.siliconflow.cn/account/ak) | https://api.siliconflow.cn/v1 |
| DMXAPI | [ここをクリックして取得](https://www.dmxapi.cn/token) | `https://www.dmxapi.cn/v1` | | DMXAPI | [取得はこちら](https://www.dmxapi.cn/token) | https://www.dmxapi.cn/v1 |
| 聚光AI | [ここをクリックして取得](https://ai.juguang.chat/console/token) | `https://ai.juguang.chat/v1` | | 聚光AI | [取得はこちら](https://ai.juguang.chat/console/token) | https://ai.juguang.chat/v1 |
### 2. PDF解析エンジンPDF翻訳が不要な場合は無視してください ### 2. PDF解析エンジンPDF翻訳が不要な場合は無視して構いません
#### 2.1 minerUトークンの取得オンラインPDF解析、無料、推奨 ### 2.1 minerU Token の取得 (オンラインPDF解析、無料、推奨)
ドキュメント解析エンジンとして`mineru`を選択した場合(`convert_engine="mineru"`)、無料のトークンを申請する必要があります。 ドキュメント解析エンジンとして `mineru` を選択する場合(`convert_engine="mineru"`)、無料の Token を申請する必要があります。
1. [minerU公式サイト](https://mineru.net/apiManage/docs)にアクセスし登録しAPIを申請します。 1. [minerU 公式サイト](https://mineru.net/apiManage/docs) にアクセスし登録しAPI を申請します。
2. [APIトークン管理画面](https://mineru.net/apiManage/token)で新しいAPIトークンを作成します。 2. [API Token 管理画面](https://mineru.net/apiManage/token) で新しい API Token を作成します。
> **注意**: minerUトークンの有効期は14日間です。期限切れたら再作成してください。 > **注意**: minerU Token の有効期は14日間です。期限切れ後は再作成してください。
#### 2.2. doclingエンジン設定ローカルPDF解析 ### 2.2. docling エンジン設定 (ローカルPDF解析)
ドキュメント解析エンジンとして`docling`を選択した場合(`convert_engine="docling"`、初回使用時にHugging ドキュメント解析エンジンとして `docling` を選択する場合(`convert_engine="docling"`)、初回使用時に Hugging Face から必要なモデルをダウンロードします。
Faceから必要なモデルがダウンロードされます。
> より良い選択肢は、[GitHub Releases](https://github.com/xunbu/docutranslate/releases)から`docling_artifact.zip` > [Github Releases](https://github.com/xunbu/docutranslate/releases) から `docling_artifact.zip` をダウンロードし、作業ディレクトリに解凍することをお勧めします。
> をダウンロードし、作業ディレクトリに解凍することです。
**`docling`モデルダウンロード時のネットワーク問題解決策:** **`docling` モデルダウンロード時のネットワーク問題解決策:**
1. **Hugging Faceミラーの設定推奨**: 1. **Hugging Face ミラーの設定 (推奨)**:
* **方法A環境変数**: システム環境変数`HF_ENDPOINT`を設定し、IDEまたはターミナルを再起動します。
```
HF_ENDPOINT=https://hf-mirror.com
```
* **方法Bコード内で設定**: Pythonスクリプトの冒頭に以下のコードを追加します。 * **方法 A (環境変数)**: システム環境変数 `HF_ENDPOINT` を設定し、IDEまたはターミナルを再起動します。
```
HF_ENDPOINT=https://hf-mirror.com
```
* **方法 B (コード内で設定)**: Pythonスクリプトの冒頭に以下のコードを追加します。
```python ```python
import os import os
@@ -530,17 +538,17 @@ import os
os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
``` ```
2. **オフラインでの使用(モデルパッケージを事前にダウンロード**: 2. **オフライン使用 (事前にモデルパッケージをダウンロード)**:
* [GitHub Releases](https://github.com/xunbu/docutranslate/releases)から`docling_artifact.zip`をダウンロードします。
* プロジェクトディレクトリに解凍します。
* 設定でモデルのパスを指定します(モデルがスクリプトと同じディレクトリにない場合): * [GitHub Releases](https://github.com/xunbu/docutranslate/releases) から `docling_artifact.zip` をダウンロードします。
* プロジェクトディレクトリに解凍します。
* 設定でモデルパスを指定します(モデルがスクリプトと同階層にない場合):
```python ```python
from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig from docutranslate.converter.x2md.converter_docling import ConverterDoclingConfig
converter_config = ConverterDoclingConfig( converter_config = ConverterDoclingConfig(
artifact="./docling_artifact", # 解凍したフォルダへのパス artifact="./docling_artifact", # 解凍後のフォルダを指定
code_ocr=True, code_ocr=True,
formula_ocr=True formula_ocr=True
) )
@@ -549,32 +557,28 @@ converter_config = ConverterDoclingConfig(
## FAQ ## FAQ
**Q: なぜ翻訳結果が原文のままなのですか?** **Q: なぜ翻訳結果が原文のままなのですか?**
A: ログにどのようなエラーが出ているか確認してください。通常AIプラットフォームの料金未払いやネットワークの問題(システムプロキシを有効にする必要があるか確認)が原因です。 A: ログを確認し、エラー内容をチェックしてください。通常AIプラットフォームの残高不足か、ネットワークの問題(システムプロキシを有効にする必要があるか確認)です。
**Q: 8010ポートが使用中です。どうすればいいですか?** **Q: 8010ポートが使用されていますが、どうすればいいですか?**
A: `-p`パラメータ新しいポートを指定するか、`DOCUTRANSLATE_PORT`環境変数を設定してください。 A: `-p` パラメータを使用して新しいポートを指定するか、`DOCUTRANSLATE_PORT` 環境変数を設定してください。
**Q: スキャンされたPDFの翻訳はサポートていますか?** **Q: スキャンされたPDFの翻訳はサポートされていますか?**
A: はい、サポートています。強力なOCR機能を持つ`mineru`解析エンジンを使用してください。 A: はい、サポートされています。強力なOCR機能を備えた `mineru` 解析エンジンを使用してください。
**Q: なぜ最初のPDF翻訳がとても遅いのですか?** **Q: 最初のPDF翻訳が非常に遅いのはなぜですか?**
A: `docling`エンジンを使用している場合、初回実行時にHugging A: `docling` エンジンを使用している場合、初回実行時に Hugging Face からモデルをダウンロードする必要があるためです。上記の「ネットワーク問題解決策」を参照して、このプロセスを高速化してください。
Faceからモデルをダウンロードする必要があります。このプロセスを高速化するには、上記の「ネットワーク問題解決策」を参照してください。
**Q: イントラネット(オフライン)環境で使用するにはどうすればいいですか** **Q: イントラネット(オフライン)環境で使用する方法は**
A: 完全に可能です。以下の条件を満たす必要があります: A: 可能です。以下の条件を満たす必要があります:
1. **ローカルLLM**: [Ollama](https://ollama.com/)[LM Studio](https://lmstudio.ai/)などのツールを使用してローカルに言語モデルをデプロイし、 1. **ローカルLLM**: [Ollama](https://ollama.com/)[LM Studio](https://lmstudio.ai/) などのツールを使用してローカルに言語モデルをデプロイし、`TranslatorConfig` にローカルモデルの `base_url` を入力します。
`TranslatorConfig`にローカルモデルの`base_url`を記入します 2. **ローカルPDF解析エンジン**PDF解析が必要な場合のみ: `docling` エンジンを使用し、上記の「オフライン使用」の指示に従って事前にモデルパッケージをダウンロードしてください
2. **ローカルPDF解析エンジン**PDF解析にのみ必要: `docling`エンジンを使用し、上記の「オフラインでの使用」の指示に従って事前にモデルパッケージをダウンロードします。
**Q: PDF解析のキャッシュメカニズムはどのように機能しますか** **Q: PDF解析のキャッシュメカニズムはどのように機能しますか**
A: `MarkdownBasedWorkflow` A: `MarkdownBasedWorkflow` は、ドキュメント解析ファイルからMarkdownへの変換の結果を自動的にキャッシュし、時間とリソースを消費する重複解析を回避します。キャッシュはデフォルトでメモリに保存され、最近の10件の解析を記録します。`DOCUTRANSLATE_CACHE_NUM` 環境変数でキャッシュ数を変更できます。
は、ドキュメント解析ファイルからMarkdownへの変換の結果を自動的にキャッシュし、時間とリソースの重複消費を防ぎます。キャッシュはデフォルトでメモリに保存され、直近10回の解析が記録されます。
`DOCUTRANSLATE_CACHE_NUM`環境変数でキャッシュ数を変更できます。
**Q: ソフトウェアプロキシを経由するようにするにはどうすればいいですか?** **Q: ソフトウェアプロキシを使用するにはどうすればいいですか?**
A: デフォルトではシステムプロキシを使用しません。`TranslatorConfig``system_proxy_enable=True`設定することで有効にできます。 A: ソフトウェアはデフォルトではシステムプロキシを使用しません。`TranslatorConfig``system_proxy_enable=True`設定することで、システムプロキシを有効にできます。
## Star History ## Star History
@@ -586,10 +590,10 @@ A: デフォルトではシステムプロキシを使用しません。`Transla
</picture> </picture>
</a> </a>
## ご支援について ## 寄付・サポート
作者へのご支援を歓迎します。備考欄に支援の理由を記載していただけるといです。 著者をサポートしてくださる方は、備考欄に理由を書いていただけると嬉しいです。
<p align="center"> <p align="center">
<img src="./images/赞赏码.jpg" alt="支援用QRコード" style="width: 250px;"> <img src="./images/赞赏码.jpg" alt="寄付コード" style="width: 250px;">
</p> </p>

View File

@@ -1,5 +1,5 @@
<p align="center"> <p align="center">
<img src="./DocuTranslate.png" alt="项目Logo" style="width: 150px"> <img src="./DocuTranslate.png" alt="项目Logo" style="width: 150px">
</p> </p>
<h1 align="center">DocuTranslate</h1> <h1 align="center">DocuTranslate</h1>
@@ -51,6 +51,7 @@ AI 平台 API-Key 即可开始使用。
- **DocuTranslate**: 标准版,使用在线的 `minerU` 引擎解析PDF文档如果不需要本地解析pdf选这个版本推荐 - **DocuTranslate**: 标准版,使用在线的 `minerU` 引擎解析PDF文档如果不需要本地解析pdf选这个版本推荐
- **DocuTranslate_full**: 完整版,内置 `docling` 本地PDF解析引擎需要本地解析pdf选这个版本。 - **DocuTranslate_full**: 完整版,内置 `docling` 本地PDF解析引擎需要本地解析pdf选这个版本。
> 1.5.1版本以后支持调用本地部署的mineru服务
## 安装 ## 安装
@@ -186,6 +187,22 @@ async def main():
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML 导出配置 html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML 导出配置
) )
# 使用本地部署mineru服务
# from docutranslate.converter.x2md.converter_mineru_deploy import ConverterMineruDeployConfig
# converter_config = ConverterMineruDeployConfig(
# base_url = "http://127.0.0.1:8000",
# output_dir= "./output",#受mineru限制解析后的文件会保存到output_dir下需要定期清理
# backend= "pipeline",
# start_page_id = 0,
# end_page_id = 99999,
# )
# workflow_config = MarkdownBasedWorkflowConfig(
# convert_engine="mineru_deploy", # 指定解析引擎
# converter_config=converter_config, # 传入转换器配置
# translator_config=translator_config, # 传入翻译器配置
# html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML 导出配置
# )
# 4. 实例化工作流 # 4. 实例化工作流
workflow = MarkdownBasedWorkflow(config=workflow_config) workflow = MarkdownBasedWorkflow(config=workflow_config)

View File

@@ -1,3 +1,3 @@
# SPDX-FileCopyrightText: 2025 QinHan # SPDX-FileCopyrightText: 2025 QinHan
# SPDX-License-Identifier: MPL-2.0 # SPDX-License-Identifier: MPL-2.0
__version__="1.5.3a1" __version__="1.5.3"

View File

@@ -1,13 +1,15 @@
# SPDX-FileCopyrightText: 2025 QinHan # SPDX-FileCopyrightText: 2025 QinHan
# SPDX-License-Identifier: MPL-2.0 # SPDX-License-Identifier: MPL-2.0
# from docling.pipeline.standard_pdf_pipeline import StandardPdfPipeline # from docling.pipeline.standard_pdf_pipeline import StandardPdfPipeline
import pathlib
import docling.utils.model_downloader import docling.utils.model_downloader
def get_docling_artifacts(): def get_docling_artifacts(output_dir=None):
# path = StandardPdfPipeline.download_models_hf() # path = StandardPdfPipeline.download_models_hf()
path=docling.utils.model_downloader.download_models() path=docling.utils.model_downloader.download_models(output_dir)
print(f"docling模型包已经下载到{path.resolve()}") print(f"docling模型包已经下载到{path.resolve()}")
return path return path
# #
if __name__ == '__main__': if __name__ == '__main__':
get_docling_artifacts() get_docling_artifacts(output_dir=pathlib.Path(r"C:\Users\jxgm\Desktop\translate\docutranslate\dist\models"))

897
uv.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
更新日志 更新日志
---------------- ----------------
v1.5.3a1版 2025.11.29 v1.5.3版 2025.12.04
特性 特性
- 新增PPTX翻译 - 新增PPTX翻译
- 新的/service/translate/file接口可以直接上传表单文件 - 新的/service/translate/file接口可以直接上传表单文件