-
Notifications
You must be signed in to change notification settings - Fork 16
/
translate_md.py
66 lines (51 loc) · 1.89 KB
/
translate_md.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import requests
from dotenv import load_dotenv
# 加载 .env 文件中的环境变量
load_dotenv()
# 配置选项
OPENAI_URL = os.getenv("OPENAI_URL")
API_KEY = os.getenv("API_KEY")
MODEL = os.getenv("MODEL")
INPUT_FILE = os.getenv("INPUT_FILE")
OUTPUT_FILE = os.getenv("OUTPUT_FILE")
TARGET_LANGUAGE = os.getenv("TARGET_LANGUAGE")
def read_markdown_file(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
def write_markdown_file(file_path, content):
with open(file_path, 'w', encoding='utf-8') as file:
file.write(content)
def translate_text(text):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
prompt = f"Translate the following text to {TARGET_LANGUAGE} Markdown syntax is not preserved :\n\n{text}"
data = {
"model": MODEL,
"messages": [{"role": "user", "content": prompt}]
}
response = requests.post(OPENAI_URL, headers=headers, json=data)
if response.status_code == 200:
return response.json()['choices'][0]['message']['content']
else:
print(f"Error: {response.status_code} - {response.text}")
return None
def main():
if not os.path.exists(INPUT_FILE):
print(f"Input file {INPUT_FILE} does not exist.")
return
markdown_content = read_markdown_file(INPUT_FILE)
if markdown_content.startswith('```'):
markdown_content = markdown_content[3:].strip()
if markdown_content.endswith('```'):
markdown_content = markdown_content[:-3].strip()
translated_content = translate_text(markdown_content)
if translated_content:
write_markdown_file(OUTPUT_FILE, translated_content)
print(f"Translation completed. Output saved to {OUTPUT_FILE}.")
else:
print("Translation failed.")
if __name__ == "__main__":
main()