前面不是写了一个将SCI文献的PDF转换为Markdown格式的工具,现在这个工具是为了完善工具链写出来的,转换完就可以马上将文献翻译成中文。
首先安装依赖
bash
pip install openai
业务代码如下:
python
import openai
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class MarkdownTranslator:
def __init__(self, config_file):
self.config = self.load_config(config_file)
openai.api_key = self.config.get('OPENAI_API_KEY')
openai.base_url = self.config.get('OPENAI_API_BASE')
openai.default_headers = {"x-foo": "true"}
# 从配置文件获取OpenAI API密钥和自定义服务器地址
def load_config(self, config_file):
try:
with open(config_file, 'r', encoding='utf-8') as file:
config = json.load(file)
return config
except Exception as e:
logging.error(f"Error reading config file {config_file}: {e}")
raise
# 读取Markdown文件
def read_markdown(self, file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
logging.error(f"Error reading file {file_path}: {e}")
raise
# 将翻译后的内容写入新的Markdown文件
def write_markdown(self, file_path, content):
try:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
except Exception as e:
logging.error(f"Error writing file {file_path}: {e}")
raise
# 翻译函数
def translate_text(self, text, source_lang='en', target_lang='zh'):
try:
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "user",
"content": f"请将以下{source_lang}文本翻译成{target_lang}:\n{text}"
}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
logging.error(f"Error translating text: {e}")
return text # 返回原文以防止翻译失败
# 处理Markdown内容
def process_markdown_content(self, content, source_lang, target_lang):
lines = content.split('\n')
translated_lines = []
def translate_line(index, line):
if line.strip(): # 忽略空行
translated_line = self.translate_text(line, source_lang, target_lang)
translated_lines.append((index, translated_line))
else:
translated_lines.append((index, '')) # 保持空行
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(translate_line, i, line) for i, line in enumerate(lines)]
for future in as_completed(futures):
future.result() # 等待所有线程完成
# 按原始顺序排序
translated_lines.sort(key=lambda x: x[0])
return '\n'.join(line for _, line in translated_lines)
# 翻译文件
def translate_file(self, input_file, output_file, source_lang='en', target_lang='zh'):
# 打印参数
logging.info(f"Translating file from {source_lang} to {target_lang}...")
logging.info(f"OpenAi_key: {openai.api_key}")
logging.info(f"OpenAi_base: {openai.base_url}")
# 读取原始Markdown文件
markdown_content = self.read_markdown(input_file)
# 处理并翻译内容
translated_content = self.process_markdown_content(markdown_content, source_lang, target_lang)
# 写入新Markdown文件
self.write_markdown(output_file, translated_content)
if __name__ == "__main__":
# 输入和输出文件路径
input_file_path = 'input.md' # 输入的Markdown文件
output_file_path = 'output.md' # 输出的Markdown文件
# 可选的源语言和目标语言
source_language = 'en' # 源语言(默认为英文)
target_language = 'zh' # 目标语言(默认为中文)
translator = MarkdownTranslator('config.json')
translator.translate_file(input_file_path, output_file_path, source_language, target_language)
config.json文件内容如下:
json
{
"OPENAI_API_KEY": "your_openai_api_key",
"OPENAI_API_BASE": "https://api.openai.com" # 可以用满足OpenAI API格式的自定义服务器地址
}
这个工具的使用方法也很简单,只需要指定输入的Markdown文件路径和输出的Markdown文件路径,以及可选的源语言和目标语言,就可以将Markdown文件中的英文内容翻译成中文。