溫州專業(yè)手機網(wǎng)站制作哪家好天津網(wǎng)站seo設(shè)計
XunityAutoTranslator-Gemini-API
本項目是一個使用 Flask 框架和 Google Gemini GenAI 模型構(gòu)建的 Web API 服務(wù),用于將日文unity游戲文本翻譯成簡體中文。
日文游戲文本AI翻譯API (基于Google Gemini)
本項目是一個使用 Flask 框架和 Google Gemini GenAI 模型構(gòu)建的 Web API 服務(wù),用于將日文游戲文本翻譯成簡體中文。
功能特點
- AI 驅(qū)動翻譯: 使用 Google Gemini GenAI 模型
gemini-2.0-flash-001
進行高質(zhì)量的日文到簡體中文翻譯。 - 游戲文本優(yōu)化: 針對游戲文本特點進行了優(yōu)化,例如保留格式標(biāo)簽、處理特殊符號、保留原文風(fēng)格等。
- 質(zhì)量檢測與重試: 自動檢測譯文質(zhì)量,當(dāng)檢測到譯文包含日文或重復(fù)內(nèi)容時,會自動重試翻譯。
- 高并發(fā)處理: 使用 Flask 框架和 gevent WSGI 服務(wù)器,支持高并發(fā)請求處理。
- 異步請求處理: 使用隊列和線程池異步處理翻譯請求,避免阻塞主線程,提高服務(wù)器響應(yīng)速度。
- 簡單易用: 提供簡潔的 HTTP GET API 接口
/translate
,方便集成到各種游戲或工具中。
快速開始
1. 前置條件
- Python 3.6+
- 已安裝必要的 Python 庫 (見(###2-依賴庫))
- Google Gemini API 密鑰
2. 依賴庫
請確保已安裝以下 Python 庫:
import os
import re
import json
import time
from flask import Flask, request
from gevent.pywsgi import WSGIServer
from urllib.parse import unquote
from threading import Thread
from queue import Queue
import concurrent.futures
from google import genai # 導(dǎo)入 Google GenAI 庫
配置說明
API 配置
Model_Type = "gemini-2.0-flash-001" # 使用的模型類型, 請根據(jù)Google的文檔自行修改
client = genai.Client(api_key="YOUR_API_KEY") # 替換為你的 API 密鑰
3. 配置 API 密鑰
請修改代碼,打開 腳本文件名.py 文件,找到以下代碼行:
client = genai.Client(api_key=“YOUR_API_KEY”) # 使用 genai.Client 初始化客戶端,并配置 API 密鑰 請?zhí)鎿Q為您的 API 密鑰
將 “YOUR_API_KEY” 替換為您自己的 Google Gemini API 密鑰。 注意:請務(wù)必替換為您自己的 API 密鑰,否則API將無法正常工作。
4. 運行 API 服務(wù) 在代碼所在目錄下,打開終端并執(zhí)行以下命令:
python 腳本文件名.py
配置XUnity.AutoTranslator看我上一篇文章:
XUnity.AutoTranslator-deepseek——調(diào)用騰訊的DeepSeek V3 API,實現(xiàn)Unity游戲中日文文本的自動翻譯
代碼配置
以下參數(shù)在代碼中直接定義,您可以根據(jù)需要修改代碼進行調(diào)整:
- Model_Type: 使用的 Google Gemini GenAI 模型類型,默認為 “gemini-2.0-flash-001”。您可以根據(jù) Google GenAI API 的支持情況選擇其他模型。
- repeat_count: 重復(fù)內(nèi)容檢測閾值,默認為 5。用于檢測譯文中是否存在重復(fù)內(nèi)容,數(shù)值越大,對重復(fù)內(nèi)容檢測的容忍度越高。
- prompt: 基礎(chǔ)提示詞 (Prompt),用于指導(dǎo) AI 模型進行翻譯。您可以根據(jù)需要修改提示詞,以優(yōu)化翻譯效果。
- prompt_list: 提示詞列表,默認為包含單個基礎(chǔ)提示詞的列表。您可以配置多個提示詞,程序會在翻譯失敗時自動嘗試使用列表中的下一個提示詞進行重試翻譯。
- MAX_WORKERS: 線程池最大工作線程數(shù),默認為 2。您可以根據(jù)服務(wù)器性能和并發(fā)需求調(diào)整線程池大小。
代碼如下:
import os
import re
import json
import time
from flask import Flask, request
from gevent.pywsgi import WSGIServer
from urllib.parse import unquote
from threading import Thread
from queue import Queue
import concurrent.futures
from google import genai # 導(dǎo)入 Google GenAI 庫# 啟用虛擬終端序列,支持 ANSI 轉(zhuǎn)義代碼,允許在終端顯示彩色文本
os.system('')# dict_path='用戶替換字典.json' # 替換字典路徑。如果不需要使用替換字典,請將此變量留空(設(shè)為 None 或空字符串 "")
dict_path=None # 替換字典路徑。如果不需要使用替換字典,請將此變量留空(設(shè)為 None 或空字符串 "")
# API 配置參數(shù)
Model_Type = "gemini-2.0-flash-001" # 使用的模型類型,選擇 GenAI 支持的模型,例如 "gemini-2.0-flash"# 創(chuàng)建 Google GenAI 客戶端實例
# 使用 genai.Client 進行客戶端初始化,并配置 API 密鑰
# 注意:請將 "YOUR_API_KEY" 替換為您自己的 Google GenAI API 密鑰
client = genai.Client(api_key="YOUR_API_KEY") # 使用 genai.Client 初始化客戶端,并配置 API 密鑰 **請?zhí)鎿Q為您的 API 密鑰**# 譯文重復(fù)內(nèi)容檢測參數(shù)
repeat_count=5 # 重復(fù)內(nèi)容閾值。如果譯文中有任意單字或單詞連續(xù)重復(fù)出現(xiàn)次數(shù)大于等于 repeat_count,則認為譯文質(zhì)量不佳,會觸發(fā)重試翻譯邏輯# 提示詞 (Prompt) 配置
prompt= '''
你是資深本地化專家,負責(zé)將游戲日文文本譯為簡體中文。
**你的任務(wù)是精確翻譯日文文本,僅輸出譯文,請勿添加任何與原文無關(guān)的解釋、說明、補充信息或其他任何文字。** 接收文本后,請嚴格按照以下要求翻譯:
翻譯范圍:翻譯普通日文文本,保留原文敘述風(fēng)格。
保留格式:保留轉(zhuǎn)義字符、格式標(biāo)簽等非日文文本內(nèi)容。
翻譯原則:忠實準(zhǔn)確,確保語義無誤;對露骨性描寫,可直白粗俗表述,不刪減篡改;對雙關(guān)語等特殊表達,找目標(biāo)語言等效表達,保原作意圖風(fēng)格。
文本類型:游戲文本含角色對話、旁白、武器及物品名稱、技能描述、格式標(biāo)簽、特殊符號等。
以下是待翻譯的游戲文本:''' # 基礎(chǔ)提示詞,用于指導(dǎo)模型進行翻譯,定義了翻譯的角色、范圍、格式、原則和文本類型
prompt_list=[prompt] # 提示詞列表??梢耘渲枚鄠€提示詞,程序會依次嘗試使用列表中的提示詞進行翻譯,直到獲得滿意的結(jié)果
# l=len(prompt_list) # 獲取提示詞列表的長度 (此變量目前未被直接使用,移除)# 提示字典相關(guān)的提示詞配置
dprompt0='\n在翻譯中使用以下字典,字典的格式為{\'原文\':\'譯文\'}\n' # 提示模型在翻譯時使用提供的字典。字典格式為 JSON 格式的字符串,鍵為原文,值為譯文
dprompt1='\nDuring the translation, use a dictionary in {\'Japanese text \':\'translated text \'} format\n' # 英文版的字典提示詞,可能用于多語言支持或模型偏好
# dprompt_list 字典提示詞列表,與 prompt_list 提示詞列表一一對應(yīng)。當(dāng)使用 prompt_list 中的第 i 個提示詞時,會同時使用 dprompt_list 中的第 i 個字典提示詞
dprompt_list=[dprompt0,dprompt1,dprompt1]
MAX_WORKERS = 2 # 線程池最大工作線程數(shù) (直接在代碼中定義)app = Flask(__name__) # 創(chuàng)建 Flask 應(yīng)用實例# 讀取提示字典
prompt_dict= {} # 初始化提示字典為空字典
if dict_path: # 檢查是否配置了字典路徑try:with open(dict_path, 'r', encoding='utf8') as f: # 嘗試打開字典文件tempdict = json.load(f) # 加載 JSON 字典數(shù)據(jù)# 按照字典 key 的長度從長到短排序,確保優(yōu)先匹配長 key,避免短 key 干擾長 key 的匹配sortedkey = sorted(tempdict.keys(), key=lambda x: len(x), reverse=True)for i in sortedkey:prompt_dict[i] = tempdict[i] # 將排序后的字典數(shù)據(jù)存入 prompt_dictprint(f"\033[32m字典文件 {dict_path} 加載成功,共加載 {len(prompt_dict)} 個詞條。\033[0m") # 打印字典加載成功的消息except FileNotFoundError:print(f"\033[33m警告:字典文件 {dict_path} 未找到。\033[0m") # 警告用戶字典文件未找到except json.JSONDecodeError:print(f"\033[31m錯誤:字典文件 {dict_path} JSON 格式錯誤,請檢查字典文件。\033[0m") # 錯誤提示 JSON 格式錯誤except Exception as e:print(f"\033[31m讀取字典文件時發(fā)生未知錯誤: {e}\033[0m") # 捕獲其他可能的文件讀取或 JSON 解析錯誤def contains_japanese(text):"""檢測文本中是否包含日文字符。"""pattern = re.compile(r'[\u3040-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FE]') # 日文字符的 Unicode 范圍正則表達式return pattern.search(text) is not None # 使用正則表達式搜索文本中是否包含日文字符def has_repeated_sequence(string, count):"""檢測字符串中是否存在連續(xù)重復(fù)的字符或子串。"""# 檢查單個字符的重復(fù)for char in set(string):if string.count(char) >= count:return True# 檢查字符串片段(子串)的重復(fù)for size in range(2, len(string) // count + 1):for start in range(0, len(string) - size + 1):substring = string[start:start + size]matches = re.findall(re.escape(substring), string)if len(matches) >= count:return Truereturn False# 獲得文本中包含的字典詞匯 (優(yōu)化后)
def get_dict(text, dictionary):"""從文本中提取出在提示字典 (dictionary) 中存在的詞匯及其翻譯 (優(yōu)化版本,不修改原文).Args:text (str): 待處理的文本.dictionary (dict): 提示字典.Returns:dict: 一個字典,key 為在文本中找到的字典原文,value 為對應(yīng)的譯文.如果文本中沒有找到任何字典詞匯,則返回空字典."""res = {}for key in dictionary:if key in text:res[key] = dictionary[key]return resrequest_queue = Queue() # 創(chuàng)建請求隊列
def handle_translation(text, translation_queue):"""處理翻譯請求的核心函數(shù)."""text = unquote(text) # URL 解碼max_retries = 3 # 最大 API 請求重試次數(shù)retries = 0 # 重試計數(shù)器special_chars = [',', '。', '?','...'] # 句末特殊字符text_end_special_char = Noneif text and text[-1] in special_chars: # 避免空字符串索引錯誤text_end_special_char = text[-1]special_char_start = "「"special_char_end = "」"has_special_start = text.startswith(special_char_start)has_special_end = text.endswith(special_char_end)if has_special_start and has_special_end:text = text[len(special_char_start):-len(special_char_end)]try: # 捕獲 API 異常dict_inuse = get_dict(text, prompt_dict) # 獲取字典詞匯 (優(yōu)化: 僅調(diào)用一次)for i in range(len(prompt_list)): # 遍歷提示詞列表prompt = prompt_list[i]if dict_inuse: # 如果有字典詞匯,則添加字典提示prompt += dprompt_list[i] + str(dict_inuse)content_to_translate = prompt + text # 構(gòu)建完整的翻譯內(nèi)容response_test = client.models.generate_content( # API 調(diào)用model=Model_Type, contents=content_to_translate)translations = response_test.textprint(f"【API 原始輸出 (未經(jīng)處理):】\n{repr(translations)}") # 打印原始值if translations.endswith("\n"): # 移除尾部換行符translations = translations[:-1]print(f"【API 翻譯結(jié)果 (經(jīng)處理):】\n{repr(translations)}") # 打印處理后的值,用于調(diào)試或日志記錄# print(f'{prompt}\n{translations}') # 打印提示詞和翻譯結(jié)果, 調(diào)試用if has_special_start and has_special_end: # 特殊字符處理if not translations.startswith(special_char_start):translations = special_char_start + translationsif not translations.endswith(special_char_end):translations = translations + special_char_endtranslation_end_special_char = Noneif translations and translations[-1] in special_chars: # 避免空字符串索引錯誤translation_end_special_char = translations[-1]if text_end_special_char and translation_end_special_char:if text_end_special_char != translation_end_special_char:translations = translations[:-1] + text_end_special_charelif text_end_special_char and not translation_end_special_char:translations += text_end_special_charelif not text_end_special_char and translation_end_special_char:translations = translations[:-1]contains_japanese_characters = contains_japanese(translations) # 檢測日文repeat_check = has_repeated_sequence(translations, repeat_count) # 重復(fù)檢測if not contains_japanese_characters and not repeat_check: # 質(zhì)量檢測通過則跳出循環(huán)breakelif contains_japanese_characters:print("\033[31m檢測到譯文中包含日文字符,嘗試使用下一個提示詞進行翻譯。\033[0m")continueelif repeat_check:print("\033[31m檢測到譯文中存在重復(fù)短語。\033[0m")# 可以在此處添加更復(fù)雜的重試策略,例如更換提示詞組合,調(diào)整模型參數(shù)等 (當(dāng)前版本暫未實現(xiàn))breakif not contains_japanese_characters and not repeat_check: # 最終質(zhì)量檢測pass # 翻譯成功print(f"\033[36m[譯文]\033[0m:\033[31m {translations}\033[0m")print("-------------------------------------------------------------------------------------------------------")translation_queue.put(translations) # 放入結(jié)果隊列except Exception as e: # API 異常處理retries += 1print(f"\033[31mAPI請求超時或發(fā)生錯誤 (第 {retries} 次重試): {e}\033[0m") # 打印錯誤信息if retries == max_retries:print(f"\033[31m達到最大重試次數(shù),翻譯失敗。\033[0m")translation_queue.put(False) # 放入失敗標(biāo)志return # 達到最大重試次數(shù),返回time.sleep(1) # 等待重試handle_translation(text, translation_queue) # 遞歸重試return # 重試后返回@app.route('/translate', methods=['GET'])
def translate():"""Flask 路由函數(shù),處理 "/translate" GET 請求."""text = request.args.get('text') # 獲取待翻譯文本print(f"\033[36m[原文]\033[0m \033[35m{text}\033[0m") # 打印原文translation_queue = Queue() # 創(chuàng)建結(jié)果隊列request_queue.put_nowait(text) # 放入請求隊列with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: # 使用配置的線程池大小 (直接使用硬編碼值)future = executor.submit(handle_translation, text, translation_queue) # 提交翻譯任務(wù)try: # 超時處理translation_result = future.result(timeout=30) # 獲取結(jié)果,設(shè)置超時時間except concurrent.futures.TimeoutError:print("\033[31m翻譯請求超時。\033[0m") # 打印超時信息return "[請求超時] " + text, 500 # 返回超時錯誤translation = translation_queue.get() # 獲取翻譯結(jié)果request_queue.get_nowait() # 從請求隊列移除已處理請求if isinstance(translation, str): # 翻譯成功return translation # 返回翻譯結(jié)果else: # 翻譯失敗return "[翻譯失敗] " , 500 # 返回失敗狀態(tài)碼def main():"""主函數(shù),啟動 Flask 應(yīng)用和 gevent 服務(wù)器."""print("\033[31m服務(wù)器在 http://127.0.0.1:4000 上啟動\033[0m") # 啟動信息http_server = WSGIServer(('127.0.0.1', 4000), app, log=None, error_log=None) # 創(chuàng)建 gevent WSGIServer 實例http_server.serve_forever() # 啟動服務(wù)器if __name__ == '__main__':main() # 運行主函數(shù)
我的上一篇帖子:XUnity.AutoTranslator-deepseek——調(diào)用騰訊的DeepSeek V3 API,實現(xiàn)Unity游戲中日文文本的自動翻譯
本項目地址:項目地址