forked from zhilizju/Awesome-instruction-tuning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.py
45 lines (31 loc) · 1.04 KB
/
translator.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
import sys
import json
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM,pipeline
model_name=sys.argv[1]
source_data_path=sys.argv[2]
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
translator=pipeline("translation",model=model,tokenizer=tokenizer)
def translate(scentence):
scentences=scentence.split('\n')
result=''
for i in range(len(scentences)):
if(len(scentences[i])!=0):
result+=translator(scentences[i])[0]['translation_text']
if(i!=len(scentences)-1):
result+='\n'
return result
with open(source_data_path) as f:
source_data=json.load(f)
translated_data=[]
for dic in tqdm(source_data):
temp={}
for key,value in dic.items():
if(len(value)==0):
temp[key]=value
continue
temp[key]=translate(value)
translated_data.append(temp)
with open('translated_data.json','w') as f:
json.dump(translated_data,f,ensure_ascii=False,indent=4)