sakuraumi commited on
Commit
3ea78af
1 Parent(s): f7375b3

Create translate_novel.py

Browse files
Files changed (1) hide show
  1. translate_novel.py +146 -0
translate_novel.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
2
+ from argparse import ArgumentParser
3
+ import random
4
+ import time
5
+ import re
6
+ from tqdm import tqdm
7
+
8
+ def get_novel_text_list(data_path, text_length):
9
+ data_list = list()
10
+ with open(data_path, 'r', encoding="utf-8") as f:
11
+ data = f.read()
12
+ data = data.replace(" ", "")
13
+ data_raw = re.sub('\n+', '\n', data)
14
+ data = data_raw.strip().split("\n")
15
+ i = 0
16
+ while i < len(data):
17
+ r = random.randint(int(text_length/2), text_length)
18
+ text = ""
19
+ while len(text) < r:
20
+ if i >= len(data):
21
+ break
22
+ if len(text) > max(- len(data[i]) + r, 0):
23
+ break
24
+ else:
25
+ text += data[i] + "\n"
26
+ i += 1
27
+ text = text.strip()
28
+ data_list.append(text)
29
+ return data_raw, data_list
30
+
31
+ def get_prompt(input, model_version):
32
+ if model_version == '0.5' or model_version == '0.8':
33
+ prompt = "<reserved_106>将下面的日文文本翻译成中文:" + input + "<reserved_107>"
34
+ return prompt
35
+ if model_version == '0.7':
36
+ prompt = f"<|im_start|>user\n将下面的日文文本翻译成中文:{input}<|im_end|>\n<|im_start|>assistant\n"
37
+ return prompt
38
+ if model_version == '0.1':
39
+ prompt = "Human: \n将下面的日文文本翻译成中文:" + input + "\n\nAssistant: \n"
40
+ return prompt
41
+ if model_version == '0.4':
42
+ prompt = "User: 将下面的日文文本翻译成中文:" + input + "\nAssistant: "
43
+ return prompt
44
+
45
+ raise ValueError(f"Wrong model version{model_version}, please view https://huggingface.co/sakuraumi/Sakura-13B-Galgame")
46
+
47
+ def split_response(response, model_version):
48
+ response = response.replace("</s>", "")
49
+ if model_version == '0.5' or model_version == '0.8':
50
+ output = response.split("<reserved_107>")[1]
51
+ return output
52
+ if model_version == '0.7':
53
+ output = response.split("<|im_start|>assistant\n")[1]
54
+ return output
55
+ if model_version == '0.1':
56
+ output = response.split("\n\nAssistant: \n")[1]
57
+ return output
58
+ if model_version == '0.4':
59
+ output = response.split("\nAssistant: ")[1]
60
+ return output
61
+
62
+ raise ValueError(f"Wrong model version{model_version}, please view https://huggingface.co/sakuraumi/Sakura-13B-Galgame")
63
+
64
+ def get_model_response(model: AutoModelForCausalLM, tokenizer: AutoTokenizer, prompt: str, model_version: str, generation_config: GenerationConfig):
65
+
66
+ generation = model.generate(**tokenizer(prompt, return_tensors="pt").to(model.device), generation_config=generation_config)[0]
67
+ response = tokenizer.decode(generation)
68
+ output = split_response(response, model_version)
69
+ return output
70
+
71
+ def get_compare_text(source_text, translated_text):
72
+ source_text_list = source_text.strip().split("\n")
73
+ translated_text_list = translated_text.strip().split("\n")
74
+ output_text = ""
75
+ if len(source_text_list) != len(translated_text_list):
76
+ print("error occurred when output compared text, fallback to output only translated text.")
77
+ return translated_text
78
+ else:
79
+ for i in range(len(source_text_list)):
80
+ output_text += source_text_list[i] + "\n" + translated_text_list[i] + "\n\n"
81
+ output_text = output_text.strip()
82
+ return output_text
83
+
84
+
85
+
86
+ def main():
87
+ parser = ArgumentParser()
88
+ parser.add_argument("--model_name_or_path", type=str, default="SakuraLLM/Sakura-13B-LNovel-v0.8", help="model huggingface id or local path.")
89
+ parser.add_argument("--use_gptq_model", action="store_true", help="whether your model is gptq quantized.")
90
+ parser.add_argument("--model_version", type=str, default="0.8", help="model version written on huggingface readme, now we have ['0.1', '0.4', '0.5', '0.7', '0.8']")
91
+ parser.add_argument("--data_path", type=str, default="data.txt", help="file path of the text you want to translate.")
92
+ parser.add_argument("--output_path", type=str, default="data_translated.txt", help="save path of the text model translated.")
93
+ parser.add_argument("--text_length", type=int, default=512, help="input max length in each inference.")
94
+ parser.add_argument("--compare_text", action="store_true", help="whether to output with both source text and translated text in order to compare.")
95
+ args = parser.parse_args()
96
+
97
+ if args.use_gptq_model:
98
+ from auto_gptq import AutoGPTQForCausalLM
99
+
100
+ generation_config = GenerationConfig(
101
+ temperature=1.0,
102
+ top_p=0.3,
103
+ top_k=40,
104
+ num_beams=1,
105
+ bos_token_id=1,
106
+ eos_token_id=2,
107
+ pad_token_id=0,
108
+ max_new_tokens=1024,
109
+ min_new_tokens=1,
110
+ do_sample=True
111
+ )
112
+
113
+ print("loading...")
114
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=False, trust_remote_code=True)
115
+
116
+ if args.use_gptq_model:
117
+ model = AutoGPTQForCausalLM.from_quantized(args.model_name_or_path, device="cuda:0", trust_remote_code=True)
118
+ else:
119
+ model = AutoModelForCausalLM.from_pretrained(args.model_name_or_path, device_map="auto", trust_remote_code=True)
120
+
121
+ print("translating...")
122
+ start = time.time()
123
+
124
+ data_raw, data_list = get_novel_text_list(args.data_path, args.text_length)
125
+ data = ""
126
+ for d in tqdm(data_list):
127
+ prompt = get_prompt(d, args.model_version)
128
+ output = get_model_response(model, tokenizer, prompt, args.model_version, generation_config)
129
+ data += output.strip() + "\n"
130
+
131
+ end = time.time()
132
+ print("translation completed, used time: ", end-start)
133
+
134
+ print("saving...")
135
+ if args.compare_text:
136
+ with open(args.output_path, 'w', encoding='utf-8') as f_w:
137
+ f_w.write(get_compare_text(data_raw, data))
138
+ else:
139
+ with open(args.output_path, 'w', encoding='utf-8') as f_w:
140
+ f_w.write(data)
141
+
142
+ print("completed.")
143
+
144
+ if __name__ == "__main__":
145
+
146
+ main()