translation_en2zh.py 1.11 KB
Newer Older
MPU王荣胜's avatar
MPU王荣胜 committed
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
import json 
import openai
import time
from tqdm import tqdm

# 设置 OpenAI API 账户信息
openai.api_key = "xxx"

# 定义翻译函数
def translate_text(text):
    # 请翻译成中文,你可以适当润色翻译的内容,但是要保证整句话通顺并且原意不变:
    prompt = "Translate the following English text to Chinese"+str(text)
    completion = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "你是一个非常优秀的中英文翻译器。"},
        {"role": "user", "content": prompt}
    ]
    )
    #print(completion.choices[0].message['content'])
    return str(completion.choices[0].message['content'])

with open('./openi-en.json') as f:
    data = json.load(f)

for i in tqdm(range(len(data['annotations']))):
    # 获取字典对象
    annotation = data['annotations'][i]['caption']

    translation = translate_text(annotation)
    #print(translation)
    data['annotations'][i]['caption'] = str(translation)

# 写入json文件
with open('openi-zh.json', 'w') as f1:
    json.dump(data, f1)