代码与文档翻译Code & Documentation Translation

智能识别代码与注释,仅翻译注释、文档字符串和 Markdown 文档,保持代码逻辑完全不变。支持 20+ 编程语言,精准解析各类注释语法和文档字符串格式,可按需控制字符串字面量是否翻译,适用于开源项目国际化、代码审查、技术文档本地化等场景。Intelligently separates code from comments — translates only comments, docstrings, and Markdown docs while preserving code logic. Supports 20+ programming languages with precise parsing of comment syntax and docstring formats. Optional string literal translation for open-source i18n, code review, and technical documentation localization.

快速概览

Quick Overview

属性Attribute说明Description
翻译端点EndpointPOST /v1/code/translate
认证AuthenticationBearer Token(Authorization 请求头)Bearer Token in Authorization header
请求体Request Bodyapplication/json(JSON 格式)application/json (JSON format)
代码上限Code Limit单次最多 50,000 字符Max 50,000 characters per request
支持语言Supported Languages20+ 编程语言(Python/JS/TS/Java/Go/C++/Rust 等)20+ programming languages (Python/JS/TS/Java/Go/C++/Rust etc.)
翻译范围Translation Scope注释 / 文档字符串 / 字符串字面量(可选)Comments / docstrings / string literals (optional)
代码安全Code Safety代码逻辑、变量名、函数名完全保持不变Code logic, variable names, function names fully preserved
响应方式Response同步返回翻译后的完整代码Synchronous return of translated code

请求端点

Endpoint

POST/v1/code/translate

认证

Authentication

所有 API 请求需在 HTTP Header 中携带 Access Token。

All API requests must include an Access Token in the HTTP Header.

Authorization: Bearer {access_token}

请求头

Request Headers

请求头Header必填Required说明Description
Authorizationrequired格式 Bearer {access_token},用于身份认证Format: Bearer {access_token}, used for authentication
Content-Typerequired固定为 application/jsonMust be application/json

请求参数

Request Parameters

参数Parameter类型Type必填Required说明Description
codestringrequired源代码文本,最大 50,000 字符。支持完整文件或代码片段Source code text, max 50,000 chars. Supports full files or snippets
langstringrequired编程语言:py/js/ts/java/go/cpp 等,详见支持语言Programming language: py/js/ts/java/go/cpp etc. See Supported Languages
target_langstringrequired目标自然语言代码,如 zhenjaTarget natural language code, e.g. zh, en, ja
source_langstringoptional源自然语言代码,默认 auto 自动检测注释语言Source natural language code; default auto for auto-detection
translate_onlystringoptional翻译范围:comments(仅注释)/ docstrings(仅文档字符串)/ all(注释+文档字符串),默认 allTranslation scope: comments / docstrings / all; default all
translate_stringsbooleanoptional是否翻译字符串字面量(如日志文本、提示信息),默认 false。注意:可能影响 i18n 逻辑Translate string literals (log text, messages); default false. Note: may affect i18n logic
preserve_formattingbooleanoptional是否保留注释原始缩进和格式对齐,默认 truePreserve original indentation and alignment of comments, default true

请求示例

Request Examples

curl -X POST https://api.itranslator.cc/v1/code/translate \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "# This function calculates the average\n# of a list of numbers\ndef calculate_average(numbers):\n    \"\"\"Return the mean.\"\"\"\n    if not numbers:\n        return 0\n    return sum(numbers) / len(numbers)",
    "lang": "py",
    "target_lang": "zh",
    "translate_only": "all"
  }' 

响应字段说明

Response Fields

字段Field类型Type说明Description
translated_codestring翻译后的完整代码(含已翻译的注释和文档字符串)Translated full code with translated comments and docstrings
original_langstring检测到的源注释语言Detected source comment language
target_langstring目标自然语言Target natural language
code_intactboolean代码逻辑是否完整保持不变(true 表示代码部分未被修改)Whether code logic is fully preserved (true means code was not modified)
comments_translatedinteger已翻译的注释数量Number of comments translated
docstrings_translatedinteger已翻译的文档字符串数量Number of docstrings translated
strings_translatedinteger已翻译的字符串字面量数量(仅 translate_strings=true 时返回)Number of string literals translated (only when translate_strings=true)
char_countinteger翻译字符数(计费依据)Translated character count (billing basis)

响应示例

Response Examples

示例 1:Python 代码翻译

Example 1: Python Code

{
  "translated_code": "# 该函数用于计算\n# 数字列表的平均值\ndef calculate_average(numbers):\n    \"\"\"返回输入列表的平均值。\"\"\"\n    if not numbers:\n        return 0\n    return sum(numbers) / len(numbers)",
  "original_lang": "en",
  "target_lang": "zh",
  "code_intact": true,
  "comments_translated": 2,
  "docstrings_translated": 1,
  "char_count": 85
}

示例 2:JavaScript 代码翻译

Example 2: JavaScript Code

{
  "translated_code": "/**\n * 用户登录处理\n * @param {string} username - 用户名\n * @param {string} password - 密码\n * @returns {Promise<Object>} 登录结果\n */\nasync function login(username, password) {\n  // 验证输入参数\n  if (!username || !password) {\n    throw new Error('用户名和密码不能为空');\n  }\n  // 发送登录请求\n  const res = await fetch('/api/login', {\n    method: 'POST',\n    body: JSON.stringify({ username, password })\n  });\n  return res.json();\n}",
  "original_lang": "en",
  "target_lang": "zh",
  "code_intact": true,
  "comments_translated": 2,
  "docstrings_translated": 1,
  "char_count": 120
}

支持的编程语言

Supported Languages

语言LanguageLang Code文件扩展名Extensions注释语法Comment Syntax文档字符串Docstring Format
Pythonpy.py#"""..."""
JavaScriptjs.js,.jsx// / /* *//** ... */
TypeScriptts.ts,.tsx// / /* *//** ... */
Javajava.java// / /* *//** ... */
Gogo.go// / /* */// Doc comment
C / C++c / cpp.c,.cpp,.h,.hpp// / /* *//** ... */
C#cs.cs// / /* *//// <summary>
Rustrust.rs// / /* *//// / //!
Swiftswift.swift// / /* *//** ... */
Kotlinkt.kt,.kts// / /* *//** ... */ / KDoc
Rubyrb.rb#=begin ... =end
PHPphp.php// / # / /* *//** ... */
Shell / BashShell / Bashsh.sh,.bash#
SQLsql.sql-- / /* */
HTMLhtml.html,.htm<!-- -->
CSScss.css/* */
💡 翻译范围说明
  • 注释(comments):行内注释 //# 和块注释 /* */ 中的文本内容
  • Comments: Text in inline comments (//, #) and block comments (/* */)
  • 文档字符串(docstrings):Python """..."""、JSDoc /** ... */、JavaDoc 等结构化文档注释
  • Docstrings: Python """...""", JSDoc /** ... */, JavaDoc and other structured doc comments
  • 字符串字面量(strings):默认不翻译,避免影响 i18n 框架和日志分析逻辑。如需翻译 UI 文案,设置 translate_strings=true
  • String literals: Not translated by default to avoid affecting i18n frameworks and log analysis. Set translate_strings=true for UI text

错误码

Error Codes

HTTP Code错误码Error Code说明Description
2000成功Success
4001001参数错误,请检查必填参数和参数格式Invalid parameter; check required fields and format
4001002不支持的语言代码Unsupported language code
4001014代码中存在语法错误,无法解析注释结构Syntax error in code; cannot parse comment structure
4001015translate_only 值无效,仅支持 comments/docstrings/allInvalid translate_only value; only comments/docstrings/all supported
4001016代码中未检测到可翻译的注释或文档字符串No translatable comments or docstrings detected in code
4012001认证失败,Token 无效或已过期Authentication failed; invalid or expired token
4032003无权限访问该资源Access denied; insufficient permissions
4133001请求文本超出长度限制(最大 50,000 字符)Text exceeds maximum length (50,000 chars)
4223014代码解析失败,可能包含不完整的多行注释或字符串Code parsing failed; may contain incomplete multi-line comments or strings
4294001请求频率超限,请稍后重试Rate limit exceeded; please retry later
4564002套餐配额已用尽,请升级或等待重置Plan quota exhausted; upgrade or wait for reset
5005001服务器内部错误,请重试或联系技术支持Internal server error; retry or contact support
5035002服务暂时不可用,建议稍后重试Service temporarily unavailable; retry later

最佳实践

Best Practices

  1. 合理选择翻译范围:仅需翻译注释时用 translate_only=comments,仅需文档字符串时用 docstrings,两者都需要用 all
  2. Choose Translation Scope: Use comments for comments only, docstrings for docstrings only, all for both.
  3. 谨慎翻译字符串translate_strings=true 会翻译字符串字面量,可能影响 i18n 框架(如 gettext)、日志解析和正则匹配,仅在确认安全时使用。
  4. Translate Strings Carefully: translate_strings=true translates string literals, which may affect i18n frameworks (e.g. gettext), log parsing, and regex matching. Use only when safe.
  5. 保留注释格式:默认开启 preserve_formatting=true,确保翻译后注释的缩进和对齐与原代码一致,便于代码审查。
  6. Preserve Comment Formatting: Keep preserve_formatting=true by default; ensures translated comments match original indentation and alignment for code review.
  7. 大文件分段处理:超过 50,000 字符的文件按函数或模块分段调用,避免单次请求超限。
  8. Chunk Large Files: For files over 50,000 chars, split by function or module to avoid exceeding the limit.
  9. CI/CD 集成:将代码翻译集成到 CI 流程,自动将多语言注释推送到不同分支,保持文档同步更新。
  10. CI/CD Integration: Integrate code translation into CI pipelines to auto-push multi-language comments to branches, keeping docs in sync.
  11. 指定源语言:混合语言注释时显式指定 source_lang,避免自动检测误判。
  12. Specify Source Language: Set source_lang explicitly for mixed-language comments to avoid auto-detection errors.

应用场景

Use Cases

场景Scenario推荐配置Recommended Config说明Notes
📦 开源项目国际化 📦 Open-Source i18n translate_only=all translate_only=all 将开源代码的英文注释翻译为多语言,方便全球开发者阅读理解 Translate English comments to multiple languages for global developers
📖 API 文档本地化 📖 API Doc Localization translate_only=docstrings translate_only=docstrings 翻译 JSDoc/JavaDoc/Python docstring,配合文档生成工具输出多语言 API 文档 Translate JSDoc/JavaDoc/docstrings; output multi-language API docs with doc generators
🔍 代码审查辅助 🔍 Code Review Aid translate_only=comments translate_only=comments 将外文注释翻译为母语,辅助理解和审查第三方代码 Translate foreign comments to native language to aid reviewing third-party code
🏫 教学示例翻译 🏫 Tutorial Translation translate_only=all + preserve_formatting translate_only=all + preserve_formatting 编程教学代码示例的多语言化,保留代码逻辑仅翻译讲解注释 Multi-language coding tutorials; preserve logic, translate explanatory comments
🌐 UI 文案提取翻译 🌐 UI Text Extraction translate_strings=true translate_strings=true 提取并翻译前端代码中的 UI 字符串文案,配合 i18n 框架使用 Extract and translate UI strings in frontend code; use with i18n frameworks
🔧 遗留代码维护 🔧 Legacy Code Maintenance translate_only=all translate_only=all 翻译遗留代码中的外文注释,便于团队接手和维护 Translate foreign comments in legacy code for team handover and maintenance
使用说明
  • 所有 API 请求均使用 HTTPS,建议开启 HTTP Keep-Alive 以提高性能。
  • All API requests use HTTPS; enable HTTP Keep-Alive for better performance.
  • 请勿在客户端代码中暴露 Access Token,建议通过后端代理调用。
  • Do not expose your Access Token in client-side code; use a backend proxy.
  • 推荐设置合理的超时时间(30 秒),并实现指数退避重试策略。
  • Set a reasonable timeout (30s) and implement exponential backoff for retries.