更新readme

This commit is contained in:
xunbu
2025-09-24 11:39:30 +08:00
parent c05f2dac58
commit cad7c47458
3 changed files with 298 additions and 344 deletions

298
README.md
View File

@@ -17,50 +17,39 @@
</p> </p>
<p align="center"> <p align="center">
A lightweight local file translation tool based on a large language model. A lightweight local file translation tool based on Large Language Models
</p> </p>
-**Supports Multiple Formats**: Can translate various files such as `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, -**Multiple Format Support**: Translates various files including `pdf`, `docx`, `xlsx`, `md`, `txt`, `json`, `epub`, `srt`, `ass`, and more.
`epub`, `srt`, and more. -**Automatic Glossary Generation**: Supports automatic generation of glossaries for term alignment.
-**Automatic Glossary Generation**: Supports automatic generation of glossaries to ensure term alignment. -**PDF Table, Formula, and Code Recognition**: Recognizes and translates tables, formulas, and code often found in academic papers, powered by `docling` and `mineru` PDF parsing engines.
-**PDF Table, Formula, and Code Recognition**: With the `docling` and `mineru` PDF parsing engines, it can recognize -**JSON Translation**: Supports specifying values to be translated in JSON using JSON paths (following `jsonpath-ng` syntax).
and translate tables, formulas, and code frequently found in academic papers. -**Word/Excel Format Preservation**: Translates `docx` and `xlsx` files while preserving their original formatting (does not yet support `doc` or `xls` files).
-**JSON Translation**: Supports specifying the values to be translated in JSON via JSON paths (using `jsonpath-ng` -**Multi-AI Platform Support**: Compatible with most AI platforms, enabling high-performance, concurrent AI translation with custom prompts.
syntax). -**Asynchronous Support**: Designed for high-performance scenarios with full asynchronous support, offering service interfaces for parallel tasks.
-**Word/Excel Format-Preserving Translation**: Supports translating `docx` and `xlsx` files (currently not `doc` or -**LAN and Multi-user Support**: Can be used by multiple people simultaneously on a local area network.
`xls` files) while preserving the original formatting.
-**Multi-AI Platform Support**: Supports most AI platforms, enabling high-performance, concurrent AI translation with
custom prompts.
-**Asynchronous Support**: Designed for high-performance scenarios, it offers complete asynchronous support,
providing service interfaces for parallel multitasking.
-**LAN and Multi-user Support**: Supports simultaneous use by multiple users on a local area network.
-**Interactive Web Interface**: Provides an out-of-the-box Web UI and RESTful API for easy integration and use. -**Interactive Web Interface**: Provides an out-of-the-box Web UI and RESTful API for easy integration and use.
-**Small-Footprint, Multi-Platform "Lazy" Packages**: Windows and Mac "lazy" packages under 40MB (for versions not -**Small, Multi-platform Standalone Packages**: Windows and Mac standalone packages under 40MB (for versions not using the `docling` local PDF parser).
using `docling` for local PDF parsing).
> When translating `pdf` files, they are first converted to Markdown, which will **lose** the original layout. Users > When translating `pdf` files, they are first converted to Markdown, which will **cause the original layout to be lost**. Users with strict layout requirements should take note.
> with layout requirements should take note.
> QQ Discussion Group: 1047781902 > QQ Discussion Group: 1047781902
**UI Interface**: **UI Interface**:
![Translation Effect](/images/UI界面.png) ![Translation Effect](/images/UI界面.png)
**Thesis Translation**: **Academic Paper Translation**:
![Translation Effect](/images/论文翻译.png) ![Translation Effect](/images/论文翻译.png)
**Novel Translation**:![Translation Effect](/images/小说翻译.png) **Novel Translation**:
![Translation Effect](/images/小说翻译.png)
## All-in-One Packages ## All-in-One 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 all-in-one packages on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). Simply download, unzip, and enter your AI platform API Key to begin.
on [GitHub Releases](https://github.com/xunbu/docutranslate/releases). Simply download, unzip, and enter your AI
platform API-Key to start using.
- **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 don't 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 local PDF parsing.
- **DocuTranslate_full**: Full version, includes the built-in `docling` local PDF parsing engine. Choose this version if
you need local PDF parsing.
## Installation ## Installation
@@ -96,48 +85,44 @@ git clone https://github.com/xunbu/docutranslate.git
cd docutranslate cd docutranslate
uv sync 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 single large class, you select and configure a workflow based on your file type.
designed specifically for a particular file type. You no longer interact with a monolithic class; instead, you select
and configure a suitable workflow based on your file type.
**The basic usage process 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 a 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 object contains all necessary sub-configurations, such as:
2. **Build the Configuration**: Create the corresponding configuration object for the selected workflow (e.g., * **Converter Config**: Defines how to convert the original file (like a PDF) to Markdown.
`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 which LLM, API-Key, target language, etc., to use. * **Translator Config**: Defines which LLM, API-Key, target language, etc., to use.
* **Exporter Config**: Defines specific options for the output format (e.g., HTML). * **Exporter Config**: Defines specific options for the output format (like HTML).
3. **Instantiate the Workflow**: Create a workflow instance using the configuration object. 3. **Instantiate the Workflow**: Create an instance of the workflow using the configuration object.
4. **Execute the Translation**: Call the workflow's `.read_*()` and `.translate()` / `.translate_async()` methods. 4. **Execute Translation**: Call the workflow's `.read_*()` and `.translate()` / `.translate_async()` methods.
5. **Export/Save the Result**: Call the `.export_to_*()` or `.save_as_*()` methods to get or save the translation 5. **Export/Save Results**: Call the `.export_to_*()` or `.save_as_*()` methods to get or save the translation results.
result.
## Available Workflows ## Available Workflows
| Workflow | Use Case | Input Formats | Output Formats | Core Config Class | | Workflow | Use Case | Input Formats | Output Formats | Core Config Class |
|:----------------------------|:----------------------------------------------------------------------------------------------------------------------|:---------------------------------------------|:-----------------------|:------------------------------| |:----------------------------|:----------------------------------------------------------------|:---------------------------------------------|:---------------------------|:------------------------------|
| **`MarkdownBasedWorkflow`** | Processes rich text documents like PDF, Word, images, etc. The process is: `File -> Markdown -> Translate -> Export`. | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` | | **`MarkdownBasedWorkflow`** | Processes rich text documents like PDF, Word, images. Flow: `File -> Markdown -> Translate -> Export`. | `.pdf`, `.docx`, `.md`, `.png`, `.jpg`, etc. | `.md`, `.zip`, `.html` | `MarkdownBasedWorkflowConfig` |
| **`TXTWorkflow`** | Processes plain text documents. The process is: `txt -> Translate -> Export`. | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` | | **`TXTWorkflow`** | Processes plain text documents. Flow: `txt -> Translate -> Export`. | `.txt` and other plain text formats | `.txt`, `.html` | `TXTWorkflowConfig` |
| **`JsonWorkflow`** | Processes JSON files. The process is: `json -> Translate -> Export`. | `.json` | `.json`, `.html` | `JsonWorkflowConfig` | | **`JsonWorkflow`** | Processes JSON files. Flow: `json -> Translate -> Export`. | `.json` | `.json`, `.html` | `JsonWorkflowConfig` |
| **`DocxWorkflow`** | Processes docx files. The process is: `docx -> Translate -> Export`. | `.docx` | `.docx`, `.html` | `docxWorkflowConfig` | | **`DocxWorkflow`** | Processes docx files. Flow: `docx -> Translate -> Export`. | `.docx` | `.docx`, `.html` | `DocxWorkflowConfig` |
| **`XlsxWorkflow`** | Processes xlsx files. The process is: `xlsx -> Translate -> Export`. | `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` | | **`XlsxWorkflow`** | Processes xlsx files. Flow: `xlsx -> Translate -> Export`. | `.xlsx`, `.csv` | `.xlsx`, `.html` | `XlsxWorkflowConfig` |
| **`SrtWorkflow`** | Processes srt files. The process is: `srt -> Translate -> Export`. | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` | | **`SrtWorkflow`** | Processes srt files. Flow: `srt -> Translate -> Export`. | `.srt` | `.srt`, `.html` | `SrtWorkflowConfig` |
| **`EpubWorkflow`** | Processes epub files. The process is: `epub -> Translate -> Export`. | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` | | **`EpubWorkflow`** | Processes epub files. Flow: `epub -> Translate -> Export`. | `.epub` | `.epub`, `.html` | `EpubWorkflowConfig` |
| **`HtmlWorkflow`** | Processes html files. The process is: `html -> Translate -> Export`. | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` | | **`HtmlWorkflow`** | Processes html files. Flow: `html -> Translate -> Export`. | `.html`, `.htm` | `.html` | `HtmlWorkflowConfig` |
> In the interactive interface, you can export to PDF format. > You can export to PDF format in the interactive interface.
## Starting the Web UI and API Service ## Launch 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 full-featured Web interface and RESTful API.
**Starting the Service:** **Start the service:**
```bash ```bash
# Start the service, listening on port 8010 by default # Start the service, listening on port 8010 by default
@@ -151,16 +136,14 @@ export DOCUTRANSLATE_PORT=8011
docutranslate -i docutranslate -i
``` ```
- **Interactive Interface**: After starting the service, please visit `http://127.0.0.1:8010` (or your specified port) - **Interactive Interface**: After starting the service, visit `http://127.0.0.1:8010` (or your specified port) in your browser.
in your browser.
- **API Documentation**: The complete API documentation (Swagger UI) is available 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
### Example 1: Translating 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 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 translation. This example uses the asynchronous method.
for translation. Here is an example using the asynchronous approach.
```python ```python
import asyncio import asyncio
@@ -171,37 +154,38 @@ from docutranslate.exporter.md.md2html_exporter import MD2HTMLExporterConfig
async def main(): async def main():
# 1. Build the 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 concurrent=10, # Concurrency level
# glossary_generate_enable=True, # Enable automatic glossary generation # glossary_generate_enable=True, # Enable automatic glossary generation
# glossary_dict={"Jobs":"乔布斯"} # Pass in a glossary # glossary_dict={"Jobs":"乔布斯"}, # Pass in a glossary
# system_proxy_enable=True, # Enable system proxy
) )
# 2. Build the 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 the 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 the parsing engine
converter_config=converter_config, # Pass in the converter configuration converter_config=converter_config, # Pass the converter config
translator_config=translator_config, # Pass in the translator configuration translator_config=translator_config, # Pass the translator config
html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export configuration html_exporter_config=MD2HTMLExporterConfig(cdn=True) # HTML export configuration
) )
# 4. Instantiate the workflow # 4. Instantiate the workflow
workflow = MarkdownBasedWorkflow(config=workflow_config) workflow = MarkdownBasedWorkflow(config=workflow_config)
# 5. Read the file and execute the translation # 5. Read the file and execute translation
print("Starting to read and translate the file...") print("Reading and translating the 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 the synchronous method
@@ -212,11 +196,11 @@ async def main():
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 have been saved to the ./output folder.") print("Files saved to the ./output folder.")
# Or get the content strings directly # Or get the content strings directly
html_content = workflow.export_to_html() html_content = workflow.export_to_html()
markdown_content = workflow.export_to_markdown() html_content = workflow.export_to_markdown()
# print(html_content) # print(html_content)
@@ -224,10 +208,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 2: Translating 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. Here is an For plain text files, the process is simpler as it doesn't require a document parsing (conversion) step. This example uses the asynchronous method.
example using the asynchronous approach.
```python ```python
import asyncio import asyncio
@@ -237,7 +220,7 @@ from docutranslate.exporter.txt.txt2html_exporter import TXT2HTMLExporterConfig
async def main(): async def main():
# 1. Build the 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",
@@ -245,7 +228,7 @@ async def main():
to_lang="Chinese", to_lang="Chinese",
) )
# 2. Build the 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)
@@ -254,7 +237,7 @@ async def main():
# 3. Instantiate the workflow # 3. Instantiate the workflow
workflow = TXTWorkflow(config=workflow_config) workflow = TXTWorkflow(config=workflow_config)
# 4. Read the file and execute the translation # 4. Read the 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 the synchronous method
@@ -262,7 +245,7 @@ async def main():
# 5. Save the result # 5. Save the result
workflow.save_as_txt(name="translated_notes.txt") workflow.save_as_txt(name="translated_notes.txt")
print("TXT file has been saved.") print("TXT file saved.")
# You can also export the translated plain text # You can also export the translated plain text
text = workflow.export_to_txt() text = workflow.export_to_txt()
@@ -272,11 +255,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 3: Translating a JSON File (using `JsonWorkflow`) ### Example 3: Translate a JSON file (using `JsonWorkflow`)
Here is an example using the asynchronous approach. The `json_paths` item in `JsonTranslatorConfig` needs to specify the This example uses the asynchronous method. The `json_paths` item in `JsonTranslatorConfig` needs to specify the JSON paths to be translated (conforming to the `jsonpath-ng` syntax). Only values matching these paths will be translated.
JSON paths to be translated (satisfying the `jsonpath-ng` syntax). Only values matching the JSON paths will be
translated.
```python ```python
import asyncio import asyncio
@@ -287,16 +268,16 @@ from docutranslate.workflow.json_workflow import JsonWorkflowConfig, JsonWorkflo
async def main(): async def main():
# 1. Build the 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"] # Satisfies jsonpath-ng syntax, values at matching paths will be translated json_paths=["$.*", "$.name"] # Conforms to jsonpath-ng syntax, values at matching paths will be translated
) )
# 2. Build the 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)
@@ -305,7 +286,7 @@ async def main():
# 3. Instantiate the workflow # 3. Instantiate the workflow
workflow = JsonWorkflow(config=workflow_config) workflow = JsonWorkflow(config=workflow_config)
# 4. Read the file and execute the translation # 4. Read the 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 the synchronous method
@@ -313,7 +294,7 @@ async def main():
# 5. Save the result # 5. Save the result
workflow.save_as_json(name="translated_notes.json") workflow.save_as_json(name="translated_notes.json")
print("JSON file has been saved.") print("JSON file saved.")
# You can also export the translated JSON text # You can also export the translated JSON text
text = workflow.export_to_json() text = workflow.export_to_json()
@@ -323,9 +304,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 4: Translating a docx File (using `DocxWorkflow`) ### Example 4: Translate a DOCX file (using `DocxWorkflow`)
Here is an example using the asynchronous approach. This example uses the asynchronous method.
```python ```python
import asyncio import asyncio
@@ -336,7 +317,7 @@ from docutranslate.workflow.docx_workflow import DocxWorkflowConfig, DocxWorkflo
async def main(): async def main():
# 1. Build the 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",
@@ -346,7 +327,7 @@ async def main():
separator="\n", # Separator used in "append" and "prepend" modes separator="\n", # Separator used in "append" and "prepend" modes
) )
# 2. Build the 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)
@@ -355,7 +336,7 @@ async def main():
# 3. Instantiate the workflow # 3. Instantiate the workflow
workflow = DocxWorkflow(config=workflow_config) workflow = DocxWorkflow(config=workflow_config)
# 4. Read the file and execute the translation # 4. Read the 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 the synchronous method
@@ -363,9 +344,9 @@ async def main():
# 5. Save the result # 5. Save the result
workflow.save_as_docx(name="translated_notes.docx") workflow.save_as_docx(name="translated_notes.docx")
print("docx file has been saved.") print("DOCX file saved.")
# You can also export the translated docx as binary # You can also export the translated DOCX as bytes
text_bytes = workflow.export_to_docx() text_bytes = workflow.export_to_docx()
@@ -373,9 +354,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### Example 5: Translating a xlsx File (using `XlsxWorkflow`) ### Example 5: Translate an XLSX file (using `XlsxWorkflow`)
Here is an example using the asynchronous approach. This example uses the asynchronous method.
```python ```python
import asyncio import asyncio
@@ -386,7 +367,7 @@ from docutranslate.workflow.xlsx_workflow import XlsxWorkflowConfig, XlsxWorkflo
async def main(): async def main():
# 1. Build the 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",
@@ -396,7 +377,7 @@ async def main():
separator="\n", # Separator used in "append" and "prepend" modes separator="\n", # Separator used in "append" and "prepend" modes
) )
# 2. Build the 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)
@@ -405,7 +386,7 @@ async def main():
# 3. Instantiate the workflow # 3. Instantiate the workflow
workflow = XlsxWorkflow(config=workflow_config) workflow = XlsxWorkflow(config=workflow_config)
# 4. Read the file and execute the translation # 4. Read the 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 the synchronous method
@@ -413,9 +394,9 @@ async def main():
# 5. Save the result # 5. Save the result
workflow.save_as_xlsx(name="translated_notes.xlsx") workflow.save_as_xlsx(name="translated_notes.xlsx")
print("xlsx file has been saved.") print("XLSX file saved.")
# You can also export the translated xlsx as binary # You can also export the translated XLSX as bytes
text_bytes = workflow.export_to_xlsx() text_bytes = workflow.export_to_xlsx()
@@ -425,76 +406,67 @@ if __name__ == "__main__":
## Prerequisites and Configuration Details ## Prerequisites and Configuration Details
### 1. Get a Large Language Model API Key ### 1. Get a Large Model API Key
The translation functionality relies on large language models. You need to obtain a `base_url`, `api_key`, and The translation feature relies on large language models. You need to obtain a `base_url`, `api_key`, and `model_id` from the respective AI platform.
`model_id` from the respective AI platform.
> Recommended models: Volcengine's `doubao-seed-1-6-250615`, `doubao-seed-1-6-flash-250715`, Zhipu's `glm-4-flash`, > Recommended models: Volcengine's `doubao-seed-1-6-flash` and `doubao-seed-1-6` series, Zhipu's `glm-4-flash`, Alibaba Cloud's `qwen-plus` and `qwen-flash`, Deepseek's `deepseek-chat`, etc.
> Alibaba Cloud's `qwen-plus`, `qwen-turbo`, Deepseek's `deepseek-chat`, etc.
| Platform Name | Get API Key | baseurl | | 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` |
| 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 | [Click to get](https://open.bigmodel.cn/usercenter/apikeys) | https://open.bigmodel.cn/api/paas/v4 | | Zhipu AI (智谱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 Cloud 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` |
### 2. PDF Parsing Engine (ignore if not translating PDFs) ### 2. PDF Parsing Engine (ignore if not translating PDFs)
### 2.1 Get a minerU Token (online PDF parsing, free, recommended) #### 2.1 Get a minerU Token (Online PDF parsing, free, recommended)
If you choose `mineru` as the document parsing engine (`convert_engine="mineru"`), you need to apply for a free token. If you choose `mineru` as your 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 the [minerU official website](https://mineru.net/apiManage/docs) to register and apply for an 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 have a 14-day validity period. Please re-create them after they expire. > **Note**: minerU Tokens are valid for 14 days. Please create a new one after expiration.
### 2.2. docling Engine Configuration (local PDF parsing) #### 2.2. docling Engine Configuration (Local PDF parsing)
If you choose `docling` as the document parsing engine (`convert_engine="docling"`), it will download the required If you choose `docling` as your document parsing engine (`convert_engine="docling"`), it will download the required models from Hugging Face upon first use.
models from Hugging Face on 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 extract it to your working directory.
> from [GitHub releases](https://github.com/xunbu/docutranslate/releases) and unzip it to your working directory.
**Solution for network issues when downloading `docling` models:** **Solutions for network issues when downloading `docling` models:**
1. **Set a Hugging Face mirror (recommended)**: 1. **Set 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 your IDE or
terminal.
``` ```
HF_ENDPOINT=https://hf-mirror.com HF_ENDPOINT=https://hf-mirror.com
``` ```
* **Method B (set in code)**: Add the following code at the beginning of your Python script. * **Method B (Set in code)**: Add the following code at the beginning of your Python script.
```python ```python
import os 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 (download the model package in advance)**:
* Download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases). * Download `docling_artifact.zip` from [GitHub Releases](https://github.com/xunbu/docutranslate/releases).
* Unzip it to your project directory. * Extract it into your project directory.
* Specify the model path in the configuration (if the model is not in the same directory as the script): * Specify the model path in your 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", # Point to the unzipped folder artifact="./docling_artifact", # Path to the extracted folder
code_ocr=True, code_ocr=True,
formula_ocr=True formula_ocr=True
) )
@@ -502,32 +474,28 @@ converter_config = ConverterDoclingConfig(
## FAQ ## FAQ
**Q: What if port 8010 is occupied?** **Q: Why is the translated text 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 need to enable the system proxy).
**Q: Port 8010 is already in use. 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 translation of scanned PDFs?** **Q: Does it support translating scanned PDFs?**
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 so 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 its first run. Please refer to the "Network Issues Solutions" section above to speed up this process.
to the "Network Issues Solution" above to speed up this process.
**Q: How to use it in an intranet (offline) environment?** **Q: How can I use it in an intranet (offline) environment?**
A: It is entirely possible. 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/) or [LM Studio](https://lmstudio.ai/), and fill in the local model's `base_url` in `TranslatorConfig`.
1. **Local LLM**: Use tools like [Ollama](https://ollama.com/) or [LM Studio](https://lmstudio.ai/) to deploy a language 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.
model locally, and fill in the `base_url` of the local model in `TranslatorConfig`.
2. **Local PDF parsing engine** (only needed for parsing PDFs): Use the `docling` engine and follow the "Offline use"
instructions above to download the model package in advance.
**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 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.
repeated parsing that consumes time and resources. The cache is stored in memory by default and records the last 10
parses. You can modify the cache size using the `DOCUTRANSLATE_CACHE_NUM` environment variable.
**Q: How to make the software go through a proxy?** **Q: How can I make the software use a proxy?**
A: The software does not use a proxy by default. You can enable it by setting the environment variable A: By default, the software does not use the system proxy. You can enable it by setting `system_proxy_enable=True` in `TranslatorConfig`.
`DOCUTRANSLATE_PROXY_ENABLED` to `true`.
## Star History ## Star History
@@ -539,10 +507,10 @@ A: The software does not use a proxy by default. You can enable it by setting th
</picture> </picture>
</a> </a>
## Support the Author ## Sponsorship
Welcome to support the author. Please kindly mention the reason for your appreciation in the notes. ❤ Your support is welcome! Please mention the reason for your donation in the memo.
<p align="center"> <p align="center">
<img src="./images/赞赏码.jpg" alt="赞赏码" style="width: 250px;"> <img src="./images/赞赏码.jpg" alt="Sponsorship QR Code" style="width: 250px;">
</p> </p>

View File

@@ -5,11 +5,11 @@
<h1 align="center">DocuTranslate</h1> <h1 align="center">DocuTranslate</h1>
<p align="center"> <p align="center">
<a href="https://github.com/xunbu/docutranslate/stargazers"><img src="https://img.shields.io/github/stars/xunbu/docutranslate?style=flat-square&logo=github&color=blue" alt="GitHubスター"></a> <a href="https://github.com/xunbu/docutranslate/stargazers"><img src="https://img.shields.io/github/stars/xunbu/docutranslate?style=flat-square&logo=github&color=blue" alt="GitHub stars"></a>
<a href="https://github.com/xunbu/docutranslate/releases"><img src="https://img.shields.io/github/downloads/xunbu/docutranslate/total?logo=github&style=flat-square" alt="GitHubダウンロード数"></a> <a href="https://github.com/xunbu/docutranslate/releases"><img src="https://img.shields.io/github/downloads/xunbu/docutranslate/total?logo=github&style=flat-square" alt="GitHub Downloads"></a>
<a href="https://pypi.org/project/docutranslate/"><img src="https://img.shields.io/pypi/v/docutranslate?style=flat-square" alt="PyPIバージョン"></a> <a href="https://pypi.org/project/docutranslate/"><img src="https://img.shields.io/pypi/v/docutranslate?style=flat-square" alt="PyPI version"></a>
<a href="https://www.python.org/"><img src="https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white&style=flat-square" alt="Pythonバージョン"></a> <a href="https://www.python.org/"><img src="https://img.shields.io/badge/Python-3.11+-3776AB?logo=python&logoColor=white&style=flat-square" alt="Python Version"></a>
<a href="./LICENSE"><img src="https://img.shields.io/github/license/xunbu/docutranslate?style=flat-square" alt="ライセンス"></a> <a href="./LICENSE"><img src="https://img.shields.io/github/license/xunbu/docutranslate?style=flat-square" alt="License"></a>
</p> </p>
<p align="center"> <p align="center">
@@ -17,23 +17,21 @@
</p> </p>
<p align="center"> <p align="center">
大規模言語モデルに基づく軽量なローカルファイル翻訳ツール 大規模言語モデルをベースにした軽量なローカルファイル翻訳ツール
</p> </p>
-**多様なフォーマットをサポート**`pdf``docx``xlsx``md``txt``json``epub``srt` など、さまざまなファイルを翻訳できます。 -**多様なフォーマットをサポート**`pdf``docx``xlsx``md``txt``json``epub``srt``ass`など、さまざまなファイルを翻訳できます。
-**用語集の自動生成**:用語集を自動生成し、専門用語の統一を実現します。 -**用語集の自動生成**:用語の整合性を保つための用語集の自動生成をサポートします。
-**PDFの表、数式、コード認識**`docling``mineru` PDF解析エンジンにより、学術論文によく見られる表、数式、コードを認識し翻訳します。 -**PDFの表、数式、コード認識**`docling``mineru` PDF解析エンジンにより、学術論文によく見られる表、数式、コードを認識し翻訳します。
-**JSON翻訳**JSON Path (`jsonpath-ng`構文仕様) を用いて、翻訳対象の値を指定できます。 -**JSON翻訳**JSONパス(`jsonpath-ng`構文仕様を使用して、JSON内で翻訳が必要な値を指定できます。
-**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 UI**すぐに使えるWeb UIとRESTful APIを提供し、統合や利用が容易です -**小型でマルチプラットフォーム対応の統合パッケージ**40MB未満のWindows、Mac用統合パッケージ`docling`ローカルPDF解析を使用しないバージョン
-**小容量・マルチプラットフォーム対応の簡単パッケージ**40MB未満のWindows、Mac用簡単パッケージ`docling`
によるローカルPDF解析を使用しないバージョン
> `pdf`を翻訳する際、一度Markdownに変換されるため、元のレイアウトが**失われます**。レイアウトを重視するユーザーはご注意ください。 > `pdf`を翻訳する際、まずMarkdownに変換されるため、元のレイアウトが**失われます**。レイアウトにこだわりがあるユーザーはご注意ください。
> QQ交流グループ1047781902 > QQ交流グループ1047781902
@@ -44,25 +42,24 @@
![翻訳効果](/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解析が必要な場合はこのバージョンを選択してください。
## インストール ## インストール
### pipを使用 ### pipを使用
```bash ```bash
# 基本インストール # 基本的なインストール
pip install docutranslate pip install docutranslate
# doclingローカルPDF解析を使用する場合 # doclingを使用してローカルPDF解析する場合
pip install docutranslate[docling] pip install docutranslate[docling]
``` ```
@@ -72,7 +69,7 @@ pip install docutranslate[docling]
# 環境の初期化 # 環境の初期化
uv init uv init
# 基本インストール # 基本的なインストール
uv add docutranslate uv add docutranslate
# docling拡張機能のインストール # docling拡張機能のインストール
@@ -91,63 +88,60 @@ 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` |
> インタラクティブUIではPDF形式でエクスポートが可能です > インタラクティブインターフェースではPDF形式でエクスポートできます。
## Web UIとAPIサービスの起動 ## Web UIとAPIサービスの起動
DocuTranslateは、使いやすさを考慮して、フル機能のWebインターフェースとRESTful APIを提供しています。 利便性のために、DocuTranslateは機能豊富なWebインターフェースとRESTful APIを提供しています。
**サービスの起動:** **サービスの起動:**
```bash ```bash
# サービスを起動、デフォルトはポート8010でリッスンします # サービスを起動、デフォルトで8010ポートをリッスンします
docutranslate -i docutranslate -i
# ポートを指定して起動 # ポートを指定して起動
docutranslate -i -p 8011 docutranslate -i -p 8011
# 環境変数でポートを指定することも可能です # 環境変数でポートを指定することもできま
export DOCUTRANSLATE_PORT=8011 export DOCUTRANSLATE_PORT=8011
docutranslate -i docutranslate -i
``` ```
- **インタラクティブUI**: サービス起動後、ブラウザで `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`にあります。
## 使用方法 ## 使用方法
### 例1: PDFファイルの翻訳 (`MarkdownBasedWorkflow`を使用) ### 例1PDFファイルの翻訳 (`MarkdownBasedWorkflow`を使用)
これは最も一般的な使用例です。`minerU`エンジンを使用してPDFをMarkdownに変換し、LLMで翻訳します。ここでは非同期方式を例にとります。 これは最も一般的な使用例です。`minerU`エンジンを使用してPDFをMarkdownに変換し、LLMで翻訳します。ここでは非同期方式を例にとります。
@@ -167,21 +161,22 @@ async def main():
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,# システムプロキシを有効にする
) )
# 2. コンバータの設定を構築 (minerUを使用) # 2. コンバータの設定を構築 (minerUを使用)
converter_config = ConverterMineruConfig( converter_config = ConverterMineruConfig(
mineru_token="YOUR_MINERU_TOKEN", # あなたのminerUトークン mineru_token="YOUR_MINERU_TOKEN", # あなたのminerUトークン
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エクスポート設定
) )
@@ -189,13 +184,13 @@ async def main():
# 4. ワークフローをインスタンス化 # 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")
@@ -213,9 +208,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例2: TXTファイルの翻訳 (`TXTWorkflow`を使用) ### 例2TXTファイルの翻訳 (`TXTWorkflow`を使用)
プレーンテキストファイルの場合、ドキュメント解析(変換)ステップが不要なため、プロセスはよりシンプルになります。ここでは非同期方式を例にとります。 プレーンテキストファイルの場合、ドキュメント解析(変換)ステップが不要なため、プロセスはより簡単です。ここでは非同期方式を例にとります。
```python ```python
import asyncio import asyncio
@@ -242,17 +237,17 @@ async def main():
# 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()
@@ -260,10 +255,9 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例3: JSONファイルの翻訳 (`JsonWorkflow`を使用) ### 例3JSONファイルの翻訳 (`JsonWorkflow`を使用)
ここでは非同期方式を例にとります。`JsonTranslatorConfig``json_paths`項目で翻訳対象のJSONパスを指定する必要があります( ここでは非同期方式を例にとります。`JsonTranslatorConfig``json_paths`項目で翻訳したいJSONパス`jsonpath-ng`構文仕様に準拠を指定する必要があります。JSONパスに一致する値のみが翻訳されます。
`jsonpath-ng`構文仕様に準拠。JSONパスにマッチした値のみが翻訳されます。
```python ```python
import asyncio import asyncio
@@ -280,7 +274,7 @@ async def main():
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. メインワークフローの設定を構築
@@ -292,17 +286,17 @@ async def main():
# 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()
@@ -310,7 +304,7 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例4: DOCXファイルの翻訳 (`DocxWorkflow`を使用) ### 例4DOCXファイルの翻訳 (`DocxWorkflow`を使用)
ここでは非同期方式を例にとります。 ここでは非同期方式を例にとります。
@@ -342,17 +336,17 @@ async def main():
# 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()
@@ -360,7 +354,7 @@ if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
``` ```
### 例5: XLSXファイルの翻訳 (`XlsxWorkflow`を使用) ### 例5XLSXファイルの翻訳 (`XlsxWorkflow`を使用)
ここでは非同期方式を例にとります。 ここでは非同期方式を例にとります。
@@ -392,17 +386,17 @@ async def main():
# 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()
@@ -412,75 +406,67 @@ if __name__ == "__main__":
## 前提条件と設定詳細 ## 前提条件と設定詳細
### 1. 大規模言語モデルAPIキー取得 ### 1. 大規模モデルAPIキー取得
翻訳機能は大規模言語モデルに依存しているため、対応するAIプラットフォームから`base_url``api_key``model_id`を取得する必要があります。 翻訳機能は大規模言語モデルに依存しているため、対応するAIプラットフォームから`base_url``api_key``model_id`を取得する必要があります。
> 推奨モデル:火山引擎の`doubao-seed-1-6-250615`、`doubao-seed-1-6-flash-250715`、智の`glm-4-flash`、阿里の`qwen-plus`、 > 推奨モデル:火山引擎の`doubao-seed-1-6-flash`、`doubao-seed-1-6`シリーズ、智の`glm-4-flash`、阿里の`qwen-plus`、`qwen-flash`、deepseekの`deepseek-chat`など。
`qwen-turbo`、deepseekの`
> deepseek-chat`など。
| プラットフォーム名 | APIキー取得 | baseurl | | プラットフォーム名 | APIキー取得 | 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` |
| 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 | [ここをクリックして取得](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 | | 火山引擎 | [ここをクリックして取得](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 | | 硅基流 | [ここをクリックして取得](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` |
### 2. PDF解析エンジンPDF翻訳が不要な場合は気にする必要はありません ### 2. PDF解析エンジンPDF翻訳が不要な場合は無視してください
### 2.1 minerUトークンの取得 (オンラインPDF解析、無料、推奨) #### 2.1 minerUトークンの取得オンラインPDF解析、無料、推奨
ドキュメント解析エンジンとして`mineru`を選択した場合(`convert_engine="mineru"`)、無料のトークンを申請する必要があります。 ドキュメント解析エンジンとして`mineru`を選択した場合(`convert_engine="mineru"`)、無料のトークンを申請する必要があります。
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トークン管理画面](https://mineru.net/apiManage/token)で新しいAPIトークンを作成します。
> **注意**: minerUトークンには14日間の有効期限があります。期限が切れた場合は再作成してください。 > **注意**: minerUトークンの有効期間は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またはターミナルを再起動します。
* **方法 A (環境変数)**: システム環境変数 `HF_ENDPOINT` を設定し、IDEまたはターミナルを再起動します。
``` ```
HF_ENDPOINT=https://hf-mirror.com HF_ENDPOINT=https://hf-mirror.com
``` ```
* **方法 B (コード内で設定)**: Pythonスクリプトの頭に以下のコードを追加します。 * **方法Bコード内で設定**: Pythonスクリプトの頭に以下のコードを追加します。
```python ```python
import os 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
) )
@@ -488,30 +474,28 @@ converter_config = ConverterDoclingConfig(
## FAQ ## FAQ
**Q: ポート8010が使用中の場合はどうすればよいですか?** **Q: なぜ翻訳結果が原文のままなのですか?**
A: `-p` パラメータを使用して新しいポートを指定するか、`DOCUTRANSLATE_PORT` 環境変数を設定してください A: ログにどのようなエラーが出ているか確認してください。通常はAIプラットフォームの料金未払いやネットワークの問題システムプロキシを有効にする必要があるか確認が原因です
**Q: 8010ポートが使用中です。どうすればいいですか**
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: LAN(オフライン)環境で使用するにはどうすればいですか?** **Q: イントラネット(オフライン)環境で使用するにはどうすればいですか?**
A: 完全に可能です。以下の条件を満たす必要があります: A: 完全に可能です。以下の条件を満たす必要があります:
1. **ローカルLLM**: [Ollama](https://ollama.com/)や[LM Studio](https://lmstudio.ai/)などのツールを使用してローカルに言語モデルをデプロイし、`TranslatorConfig`にローカルモデルの`base_url`を記入します。
1. **ローカルLLM**: [Ollama](https://ollama.com/) や [LM Studio](https://lmstudio.ai/) などのツールを使用して言語モデルをローカルにデプロイし、 2. **ローカルPDF解析エンジン**PDF解析にのみ必要: `docling`エンジンを使用し、上記の「オフラインでの使用」の指示に従って事前にモデルパッケージをダウンロードします。
`TranslatorConfig`にローカルモデルの`base_url`を記入します。
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: デフォルトではプロキシを使用しません。環境変数`DOCUTRANSLATE_PROXY_ENABLED``true`設定することで、プロキシ経由での通信が可能になります。 A: デフォルトではシステムプロキシを使用しません。`TranslatorConfig``system_proxy_enable=True`設定することで有効にできます。
## Star History ## Star History
@@ -523,10 +507,10 @@ A: デフォルトではプロキシを使用しません。環境変数`DOCUTRA
</picture> </picture>
</a> </a>
## 応援サポート ## ご支援について
作者へのサポートを歓迎します。備考欄に援の理由を記載していただけると幸いです。 作者へのご支援を歓迎します。備考欄に援の理由を記載していただけると幸いです。
<p align="center"> <p align="center">
<img src="./images/赞赏码.jpg" alt="赞赏码" style="width: 250px;"> <img src="./images/赞赏码.jpg" alt="支援用QRコード" style="width: 250px;">
</p> </p>

View File

@@ -20,7 +20,7 @@
一个基于大语言模型的轻量级本地文件翻译工具 一个基于大语言模型的轻量级本地文件翻译工具
</p> </p>
-**支持多种格式**:能翻译 `pdf``docx``xlsx``md``txt``json``epub``srt` 等多种文件。 -**支持多种格式**:能翻译 `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`语法规范)指定json中需要被翻译的值。
@@ -164,7 +164,8 @@ async def main():
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,# 启用系统代理
) )
# 2. 构建转换器配置 (使用 minerU) # 2. 构建转换器配置 (使用 minerU)
@@ -411,9 +412,7 @@ if __name__ == "__main__":
翻译功能依赖于大型语言模型,您需要从相应的 AI 平台获取 `base_url`, `api_key``model_id` 翻译功能依赖于大型语言模型,您需要从相应的 AI 平台获取 `base_url`, `api_key``model_id`
> 推荐模型:火山引擎的`doubao-seed-1-6-250615`、`doubao-seed-1-6-flash-250715`、智谱的`glm-4-flash`,阿里云的 `qwen-plus`、 > 推荐模型:火山引擎的`doubao-seed-1-6-flash`、`doubao-seed-1-6`系列、智谱的`glm-4-flash`,阿里云的 `qwen-plus`、`qwen-flash`deepseek的`deepseek-chat`等。
`qwen-turbo`deepseek的`
> deepseek-chat`等。
| 平台名称 | 获取APIkey | baseurl | | 平台名称 | 获取APIkey | baseurl |
|------------|---------------------------------------------------------------------------------------|----------------------------------------------------------| |------------|---------------------------------------------------------------------------------------|----------------------------------------------------------|
@@ -429,6 +428,7 @@ if __name__ == "__main__":
| 火山引擎 | [点击获取](https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D) | https://ark.cn-beijing.volces.com/api/v3 | | 火山引擎 | [点击获取](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 | | 硅基流动 | [点击获取](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 |
### 2. PDF解析引擎不需要翻译PDF的无需关心此处 ### 2. PDF解析引擎不需要翻译PDF的无需关心此处
@@ -480,6 +480,8 @@ converter_config = ConverterDoclingConfig(
``` ```
## FAQ ## FAQ
**Q: 为什么翻译出来的还是原文**
A: 查看一下日志报了什么错一般是AI平台欠费或网络有问题查看是否需要开启系统代理
**Q: 8010 端口被占用了怎么办?** **Q: 8010 端口被占用了怎么办?**
A: 使用 `-p` 参数指定一个新端口,或设置 `DOCUTRANSLATE_PORT` 环境变量。 A: 使用 `-p` 参数指定一个新端口,或设置 `DOCUTRANSLATE_PORT` 环境变量。
@@ -502,7 +504,7 @@ A: `MarkdownBasedWorkflow` 会自动缓存文档解析文件到Markdown的转
`DOCUTRANSLATE_CACHE_NUM` 环境变量来修改缓存数量。 `DOCUTRANSLATE_CACHE_NUM` 环境变量来修改缓存数量。
**Q: 如何让软件可以经过代理** **Q: 如何让软件可以经过代理**
A: 软件默认不使用代理,可以通过设置环境变量`DOCUTRANSLATE_PROXY_ENABLED`为`true`让软件通过代理 A: 软件默认不使用系统代理,可以在`TranslatorConfig中令system_proxy_enable=True` 启用系统代理
## Star History ## Star History