Back to skills
extension
Category: Productivity & OfficeNo API key required

translation_skill

Skill:一个具有三种模式的翻译技能:快速用于直接翻译,普通用于基于分析的翻译,精修用于完整的出版级工作流,包含审校与润色。 Skill②:一个能够评估译文的等效性,检查术语一致性,验证目标语言中的准确性,并衡量翻译质量指标的翻译技能。

personAuthor: ValenluhubModelScope

Three-Mode Translation Tool (Quick / Standard / Premium)

Full lifecycle skill: write code → install dependencies → configure LLM → auto-test → run inference. Cross-platform: macOS / Windows / Linux.

Architecture

Input text (any language)
  → Mode selection
  → Quick:    Single LLM call → Direct translation
  → Standard: Analysis → Context-aware translation
  → Premium:  Analysis → Translation → Review → Polish → Final output
  → Translated text + optional quality report

Three modes:

| Mode | LLM Calls | Pipeline | Use case | Output | |---|---|---|---|---| | Quick (--mode quick) | 1 | Direct translate | Fast drafts, gist reading, bulk processing | Translated text | | Standard (--mode standard) | 2 | Analyze → Translate | Professional use, business docs, technical content | Translated text + analysis notes | | Premium (--mode premium) | 4 | Analyze → Translate → Review → Polish | Publishing, legal, medical, literary | Translated text + full quality report |

Domain presets: general, legal, medical, technical, literary, business, academic, marketing, it, finance

LLM backend: OpenAI-compatible API (OpenAI / Azure / DeepSeek / Qwen / any OpenAI-compatible endpoint)


Phase 1: Create Project

Create the project directory <PROJECT_DIR> (user-specified, or default ./tri-mode-translate).

1.1 Create tri_mode_translate.py

Write the main tool script with the following structure:

# Key imports
import os
import sys
import json
import argparse
import time
from openai import OpenAI
from pathlib import Path

# Config: ~/.tri-mode-translate/config.json or env vars
# Default model: gpt-4o (or any OpenAI-compatible model)
# Default domain: general
# Default mode: standard

Critical implementation details:

  • LLM client: Use from openai import OpenAI. Supports any OpenAI-compatible endpoint via base_url and api_key. For Azure: use AzureOpenAI instead. For local models (Ollama / vLLM): set base_url="http://localhost:11434/v1".
  • Three modes pipeline:
    • Quick (--mode quick): Single LLM call. Prompt embeds domain glossary and style guide directly. Returns translation only.
    • Standard (--mode standard): Two sequential calls. Call 1 analyzes source text (terminology, structure, domain challenges). Call 2 translates using the analysis as context. Returns translation + analysis notes.
    • Premium (--mode premium): Four sequential calls. Call 1 analyzes source. Call 2 translates. Call 3 reviews translation against source (accuracy, terminology, fluency, cultural fit, domain compliance). Call 4 polishes to publishing grade using review feedback. Returns translation + full quality report.
  • Domain-specific handling: Each domain preset injects a system prompt with domain-specific instructions:
    • legal: precise legal terminology, preserve clause numbering, maintain defined terms, Latin phrases handling
    • medical: ICD/MeSH terminology, dosage format compliance, contraindication clarity, regulatory language
    • technical: consistent UI/tool names, API parameter naming, code snippet preservation, specification accuracy
    • literary: register and tone preservation, literary devices, rhythm and flow, cultural adaptation
    • business: corporate register, financial terminology, polite formality, metric/number formatting
    • academic: citation format preservation, field-specific jargon, passive voice conventions, hedging language
    • marketing: brand voice consistency, cultural localization, call-to-action effectiveness, slogan adaptation
    • it: consistent technical terms, placeholder preservation, error message tone, UI string length constraints
    • finance: financial reporting standards (IFRS/GAAP), currency formatting, fiscal terminology, regulatory compliance
  • Glossary support: Load custom glossary from JSON file via --glossary glossary.json. Format:
    {
      "source_term": "target_term",
      "blockchain": "区块链",
      "smart contract": "智能合约"
    }
    
    Glossary terms are injected into prompts as mandatory terminology constraints.
  • Style guide support: Load custom style rules from text file via --style-guide style.txt. Injected as additional system instructions.
  • Batch processing: --batch input_folder/ --mode premium --source-lang en --target-lang zh processes all .txt / .md / .docx files in directory.
  • Output formats: --output-format txt (plain text), --output-format json (structured with metadata), --output-format bilingual (side-by-side source + translation).
  • Token management: For long documents exceeding model context window, auto-split by paragraphs/sentences. Preserve split boundaries to maintain coherence across chunks. Use overlap of 1-2 sentences between chunks.
  • CLI args: --input, --source-lang, --target-lang, --mode, --domain, --glossary, --style-guide, --model, --api-key, --base-url, --batch, --output, --output-format, --temperature, --config, --ui

1.2 Create requirements.txt

openai>=1.30.0
python-dotenv>=1.0.0
tiktoken>=0.7.0

1.3 Create default config structure

<PROJECT_DIR>/
├── tri_mode_translate.py
├── requirements.txt
├── config.json
├── glossaries/
│   ├── legal.json
│   ├── medical.json
│   ├── technical.json
│   └── custom.json
├── style_guides/
│   ├── general.txt
│   └── custom.txt
├── output/
│   ├── translations/
│   └── reports/
└── venv/

1.4 Create default config.json

{
  "api_key": "",
  "base_url": "https://api.openai.com/v1",
  "model": "gpt-4o",
  "default_mode": "standard",
  "default_domain": "general",
  "default_source_lang": "auto",
  "default_target_lang": "zh",
  "temperature_quick": 0.3,
  "temperature_standard": 0.2,
  "temperature_premium": 0.1,
  "max_tokens": 4096,
  "glossary_dir": "glossaries",
  "style_guide_dir": "style_guides"
}

Phase 2: Platform-Adaptive Installation

Detect the current OS and adapt accordingly.

2.1 Detect platform

# macOS
[[ "$(uname)" == "Darwin" ]] && PLATFORM="macos"
# Linux
[[ "$(uname)" == "Linux" ]] && PLATFORM="linux"
# Windows (Git Bash / PowerShell)
uname -s | grep -q MINGW && PLATFORM="windows"
[[ "$OS" == "Windows_NT" ]] && PLATFORM="windows"

2.2 Create venv (platform-specific activate)

| Platform | Create | Activate | |---|---|---| | macOS / Linux | python3 -m venv venv | source venv/bin/activate | | Windows (cmd) | python -m venv venv | venv\Scripts\activate.bat | | Windows (PS) | python -m venv venv | venv\Scripts\Activate.ps1 |

When running commands via terminal tool, always use the venv Python directly:

# macOS/Linux
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py --config <PROJECT_DIR>/config.json

# Windows
<PROJECT_DIR>\venv\Scripts\python.exe <PROJECT_DIR>\tri_mode_translate.py --config <PROJECT_DIR>\config.json

2.3 Install dependencies

# Use venv pip directly (avoids activate issues)
<PROJECT_DIR>/venv/bin/pip install -r <PROJECT_DIR>/requirements.txt
# For Gradio UI (optional):
<PROJECT_DIR>/venv/bin/pip install gradio

2.4 Configure LLM API

Edit config.json to set API credentials, or use environment variables:

# OpenAI
export OPENAI_API_KEY="sk-xxxxxxxxxxxx"

# Or any OpenAI-compatible endpoint
export OPENAI_API_KEY="your-key"
export OPENAI_BASE_URL="https://api.deepseek.com/v1"

# Or local model (Ollama / vLLM)
export OPENAI_API_KEY="ollama"
export OPENAI_BASE_URL="http://localhost:11434/v1"

Verify connectivity:

<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py --test-connection

Skip if config is already set and connection test passes.


Phase 3: Auto-Test

After installation, run an automatic test using sample text for all three modes.

3.1 Test Quick mode

echo "The quick brown fox jumps over the lazy dog. This is a simple test sentence." > /tmp/test_input.txt

<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input /tmp/test_input.txt --source-lang en --target-lang zh --mode quick

Expected output:

  • Translation: "敏捷的棕色狐狸跳过了懒狗。这是一个简单的测试句子。"
  • No analysis notes, no quality report.

3.2 Test Standard mode

<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input /tmp/test_input.txt --source-lang en --target-lang zh --mode standard --domain general

Expected output:

  • Analysis notes: identification of sentence structure, terminology, and translation considerations
  • Translation: "敏捷的棕色狐狸跃过懒狗。这是一句简单的测试语句。"

3.3 Test Premium mode

<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input /tmp/test_input.txt --source-lang en --target-lang zh --mode premium --domain literary --output /tmp/test_output

Expected output:

  • Analysis notes: literary structure, idiom identification, cultural adaptation considerations
  • Translation: polished, publication-ready text
  • Quality report: accuracy score, terminology consistency check, fluency assessment, review notes, polish changes

If all three tests pass, report success to the user. If any fails, refer to Troubleshooting below.


Phase 4: Daily Usage

4.1 CLI

# Quick mode - fast direct translation
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input document.txt --source-lang en --target-lang zh --mode quick

# Standard mode - analysis-based translation
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input document.txt --source-lang en --target-lang zh --mode standard --domain technical

# Premium mode - full publishing-grade workflow
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --input document.txt --source-lang en --target-lang zh --mode premium --domain legal \
    --glossary glossaries/legal.json --output output/legal_doc --output-format bilingual

Optional flags:

  • --source-lang — source language; default auto (LLM auto-detects)
  • --target-lang — target language code (zh, ja, en, fr, de, ko, etc.)
  • --modequick / standard / premium; default standard
  • --domaingeneral / legal / medical / technical / literary / business / academic / marketing / it / finance; default general
  • --glossary — path to custom glossary JSON file
  • --style-guide — path to custom style guide text file
  • --model — override model name (e.g., gpt-4o, deepseek-chat, qwen-max)
  • --base-url — override API endpoint
  • --api-key — override API key
  • --temperature — override temperature (default: 0.3 quick / 0.2 standard / 0.1 premium)
  • --batch — batch process all files in a directory
  • --output — output file path or directory (for batch)
  • --output-formattxt / json / bilingual; default txt
  • --ui — launch Gradio web UI
  • --config — path to config file; default config.json

4.2 Gradio Web UI

<PROJECT_DIR>/venv/bin/pip install gradio
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py --ui --port 7860

Features:

  • Paste or upload text for translation
  • Select mode (Quick / Standard / Premium) and domain from dropdowns
  • View analysis notes and quality report (Standard / Premium modes)
  • Side-by-side bilingual output view
  • Download results as .txt or .json
  • Edit and re-run individual pipeline steps (Premium mode)

4.3 Batch processing

# Process all .txt and .md files in a folder
<PROJECT_DIR>/venv/bin/python <PROJECT_DIR>/tri_mode_translate.py \
    --batch input_folder/ --mode premium --domain technical \
    --source-lang en --target-lang zh --output output/

Batch features:

  • Processes .txt, .md files in the specified directory recursively
  • Generates per-file translations and a summary report
  • Skips already-processed files unless --force is passed
  • Summary report includes per-file mode, domain, timing, token usage, and quality scores

4.4 Supported languages

All languages supported by the configured LLM, including but not limited to: Chinese (Simplified), Chinese (Traditional), English, Japanese, Korean, French, German, Spanish, Italian, Portuguese, Russian, Arabic, Hindi, Turkish, Vietnamese, Thai, Indonesian, Malay, Filipino, Dutch, Polish, Czech, Swedish, Finnish, Danish, Norwegian, Greek, Hebrew, Persian, Ukrainian, Romanian, Hungarian, Bulgarian, and more.

4.5 Domain presets

| Domain | Key concerns | Glossary example | |---|---|---| | general | Natural fluency, accurate meaning | — | | legal | Clause numbering, defined terms, Latin phrases, jurisdiction | "force majeure": "不可抗力" | | medical | ICD/MeSH terms, dosage format, contraindications, regulatory language | "myocardial infarction": "心肌梗死" | | technical | UI names, API params, code preservation, spec accuracy | "blockchain": "区块链" | | literary | Register, tone, literary devices, rhythm, cultural adaptation | — | | business | Corporate register, financial terms, formality, number format | "EBITDA": "息税折旧摊销前利润" | | academic | Citation format, field jargon, passive voice, hedging | "peer review": "同行评审" | | marketing | Brand voice, cultural localization, CTA effectiveness, slogans | "call to action": "行动号召" | | it | Technical terms, placeholder preservation, error messages, UI strings | "endpoint": "端点" | | finance | IFRS/GAAP standards, currency format, fiscal terms, compliance | "balance sheet": "资产负债表" |


Troubleshooting

| Issue | Fix | |---|---| | AuthenticationError | Check API key in config.json or OPENAI_API_KEY env var | | RateLimitError | Add retry logic or reduce batch size; use --max-retries 3 | | ContextWindowExceeded | Tool auto-splits long text; if persisting, reduce --max-tokens | | ConnectionError (local model) | Ensure Ollama/vLLM is running: ollama serve or check base_url | | Translation quality poor (Quick mode) | Switch to --mode standard or --mode premium | | Terminology inconsistent | Create a glossary JSON file and pass via --glossary | | Style not matching expectations | Create a style guide text file and pass via --style-guide | | Premium mode too slow | Use --mode standard for non-critical content; reserve Premium for final output | | Output file not created | Check --output path is writable; use absolute paths | | Model not found | Check model name in config.json; use --model to override | | Batch processing skips files | Use --force to reprocess; or check file extensions are .txt / .md | | Windows venv activate fails | Use venv\Scripts\python.exe directly instead of activate | | json.decoder.JSONDecodeError (glossary) | Validate glossary JSON: each entry is "source": "target" string pairs |


本内容由 Coze AI 生成,请遵循相关法律法规及《人工智能生成合成内容标识办法》使用与传播。