Created
June 13, 2025 03:04
-
-
Save IUHHUI/515c1e89655a4edfa46595396d39a0dc to your computer and use it in GitHub Desktop.
使用qwen-mt翻译文章
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| from openai import OpenAI | |
| STR_CHINESE = "Chinese" | |
| STR_ENGLISH = "English" | |
| MODEL_QWEN_MT_TURBO = "qwen-mt-turbo" | |
| MODEL_QWEN_MT_PLUS = "qwen-mt-plus" | |
| def detect_language(text) -> str: | |
| # 去除空格和换行符 | |
| text = text.strip() | |
| if not text: | |
| # "Empty string" | |
| return STR_ENGLISH | |
| # 统计中英文字符数量 | |
| chinese_count = 0 | |
| english_count = 0 | |
| for char in text: | |
| if "\u4e00" <= char <= "\u9fff": | |
| chinese_count += 1 | |
| elif char.isalpha(): | |
| english_count += 1 | |
| # 判断主要语言 | |
| if chinese_count > 0 and chinese_count > english_count: | |
| return STR_CHINESE | |
| elif english_count > 0 and english_count > chinese_count: | |
| return STR_ENGLISH | |
| else: | |
| # "Mixed or Undetermined" | |
| return STR_ENGLISH | |
| def translate( | |
| dashscope_api_key: str, model: str, source_lang: str, target_lang: str, content: str | |
| ) -> str: | |
| """ | |
| 使用阿里云百炼翻译服务进行翻译 | |
| """ | |
| client = OpenAI( | |
| # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx", | |
| api_key=dashscope_api_key, | |
| base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", | |
| ) | |
| messages = [ | |
| { | |
| "role": "user", | |
| "content": content, | |
| } | |
| ] | |
| translation_options = {"source_lang": source_lang, "target_lang": target_lang} | |
| completion = client.chat.completions.create( | |
| model=model, | |
| messages=messages, | |
| extra_body={"translation_options": translation_options}, | |
| ) | |
| return completion.choices[0].message.content | |
| def main(dashscope_api_key: str, quality: int, content: str) -> dict: | |
| """ | |
| 翻译文本 | |
| :param dashscope_api_key: 阿里云百炼API Key | |
| :param quality: 翻译质量,1为高{QWEN_MT_PLUS},其它为速度优先{QWEN_MT_TURBO} | |
| :param content: 待翻译的文本 | |
| """ | |
| source_lang = detect_language(content) | |
| target_lang = STR_CHINESE if source_lang == STR_ENGLISH else STR_ENGLISH | |
| model = MODEL_QWEN_MT_PLUS if quality == 1 else MODEL_QWEN_MT_TURBO | |
| text = translate(dashscope_api_key, model, source_lang, target_lang, content) | |
| return {"text": text} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment