陈浩然 commited on
Commit
528fbf7
·
1 Parent(s): f332663

重磅升级:全面接入阿里 Qwen2.5-0.5B-Instruct 大语言模型作为文学翻译与润色中枢,赋予文本顶级的现代可读性与自然文学语感

Browse files
Files changed (2) hide show
  1. app.py +67 -57
  2. requirements.txt +1 -1
app.py CHANGED
@@ -10,30 +10,29 @@ import threading
10
  torch.cuda.is_available = lambda: False
11
  torch.cuda.is_initialized = lambda: False
12
 
13
- from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModelForSeq2SeqLM
14
 
15
  # 1. 载入英文基座生成模型 SmolLM2-360M
16
  BASE_MODEL_ID = "HuggingFaceTB/SmolLM2-360M"
17
- print(f"正在载入 Base 模型 {BASE_MODEL_ID}...")
18
- tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
19
- model = AutoModelForCausalLM.from_pretrained(
20
  BASE_MODEL_ID,
21
  torch_dtype=torch.float32,
22
  low_cpu_mem_usage=True
23
  )
24
- print("Base 模型装载完毕。")
25
-
26
- # 2. 载入 Meta 现代 6 亿参数多语言高精度互译大模型 NLLB-200-600M
27
- TRANS_MODEL_ID = "facebook/nllb-200-distilled-600M"
28
- print(f"正在载入现代多语言翻译大模型 {TRANS_MODEL_ID}...")
29
- trans_tokenizer = AutoTokenizer.from_pretrained(TRANS_MODEL_ID, src_lang="eng_Latn")
30
- trans_model = AutoModelForSeq2SeqLM.from_pretrained(
31
- TRANS_MODEL_ID,
32
  torch_dtype=torch.float32,
33
  low_cpu_mem_usage=True
34
  )
35
- target_lang_id = trans_tokenizer.convert_tokens_to_ids("zho_Hans")
36
- print(f"NLLB-200 翻译模型装载完毕,目标语言 ID (zho_Hans): {target_lang_id}")
37
 
38
  crypto_rand = random.SystemRandom()
39
 
@@ -66,7 +65,7 @@ BANNED_STRINGS = [
66
  ]
67
  BAD_WORDS_IDS = []
68
  for item in BANNED_STRINGS:
69
- tokens = tokenizer.encode(item, add_special_tokens=False)
70
  if tokens:
71
  BAD_WORDS_IDS.append(tokens)
72
 
@@ -74,44 +73,63 @@ def is_code_or_junk(text: str) -> bool:
74
  """检测是否为代码片段、语法乱码或技术文档垃圾"""
75
  if not text or len(text.strip()) < 10:
76
  return True
77
- # 匹配编程语法符号 (花括号、分号、冒号运算符、指针等)
78
  if re.search(r"[\{\}\;\:\=\>\<\$\#\\\_\|\&\^\~\`]{2,}", text):
79
  return True
80
- # 匹配编程关键字
81
  code_keywords = r"(?i)\b(?:function|def|return|package|import|class|var|const|void|null|undefined|console|include|typeof|lambda)\b"
82
  if re.search(code_keywords, text):
83
  return True
84
- # 统计标点符号与非字母比例
85
  special_char_count = len(re.findall(r"[\{\}\(\)\[\]\;\:\=\+\-\*\/\<\>\&\|\$\#\\]", text))
86
  if special_char_count / max(len(text), 1) > 0.08:
87
  return True
88
  return False
89
 
90
- def translate_to_chinese(text: str) -> str:
91
- """使用 Meta NLLB-200-600M 进行高质量中英互译,天然输出标准中标点,杜绝断层空格"""
92
- if not text or len(text.strip()) < 3:
93
- return text
94
- inputs = trans_tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  with torch.no_grad():
96
- translated = trans_model.generate(
97
  **inputs,
98
- forced_bos_token_id=target_lang_id,
99
- max_new_tokens=256
 
 
100
  )
101
- result = trans_tokenizer.batch_decode(translated, skip_special_tokens=True)[0]
102
- return result.strip()
 
 
103
 
104
  def clean_output(text: str) -> str:
105
  """去除 HTML 标签、格式序号与维基百科引用 [1], [2], [note]"""
106
  text = re.sub(r"</?[a-zA-Z0-9]+[^>]*>", "", text)
107
  text = text.replace("<|endoftext|>", "").replace("<|im_end|>", "").replace("<|im_start|>", "")
108
- # 彻底清除所有 [1], [2], [note 1], [citation needed], [a] 等维基百科脚注序号
109
  text = re.sub(r"\[[0-9a-zA-Z\s,\.\-_:\'\"]*\]", "", text)
110
  text = re.sub(r"(?m)^\s*(?:[0-9]+[.\、\)]|[一二三四五六七八九十]+[、\.]|[(\(][0-9一二三四五六七八九十]+[)\)]|[①②③④⑤⑥⑦⑧⑨⑩]|(?:第[一二三四五六七八九十0-9]+[条点个部分阶段、::]))\s*", "", text)
111
  text = re.sub(r"\s+[0-9]+[.\、]\s*", " ", text)
112
  text = re.sub(r"\n{3,}", "\n\n", text)
113
 
114
- # 截取到最后一个完整的标点符号收尾
115
  match = re.search(r"[.!?。!?\n][^.!?。!?\n]*$", text)
116
  if match and match.start() > 20:
117
  text = text[:match.start() + 1]
@@ -121,15 +139,14 @@ def clean_chinese(text: str) -> str:
121
  """彻底清除翻译后残留的希腊字母、英文字母、特殊符号与任何方括号注记,确保 100% 纯净可读中文"""
122
  if not text:
123
  return ""
124
- # 1. 彻底清除所有希腊字母(Greek & Coptic: \u0370-\u03ff, Greek Extended: \u1f00-\u1fff)
125
  text = re.sub(r"[\u0370-\u03ff\u1f00-\u1fff]+", "", text)
126
- # 2. 彻底清除未翻译的英文字符与拉丁残片
127
  text = re.sub(r"[a-zA-Z]+", "", text)
128
- # 3. 清除所有方括号、花括号、分号、项目符号与无意义杂质符号
129
  text = re.sub(r"\[[^\]]*\]", "", text)
130
  text = re.sub(r"【[^】]*】", "", text)
131
  text = re.sub(r"[\[\]【】\{\}\(\)\;\:\=\+\-\*\/\<\>\&\|\$\#\\•·~_\`]+", "", text)
132
- # 4. 清除汉字间多余空格与重复堆叠标点
133
  text = re.sub(r"\s+", "", text)
134
  text = re.sub(r"[。\.]{2,}", "。", text)
135
  text = re.sub(r"[,,]{2,}", ",", text)
@@ -137,14 +154,8 @@ def clean_chinese(text: str) -> str:
137
  text = re.sub(r"[??]{2,}", "?", text)
138
  text = re.sub(r"^[,。!?、;:\s]+", "", text)
139
  text = text.strip()
140
- # 确保结尾有标点
141
  if text and text[-1] not in ["。", "!", "?", "”", "’"]:
142
  text += "。"
143
-
144
- # 如果中文被污染为大量编程术语,直接丢弃
145
- if re.search(r"(?:函数|代码|未定义|程序包|参数从查询|返回值|变量名)", text) and len(text) < 60:
146
- return ""
147
-
148
  return text
149
 
150
  # 全局同步状态
@@ -168,7 +179,7 @@ def add_server_log(msg: str):
168
  GLOBAL_STATE["logs"] = GLOBAL_STATE["logs"][-20:]
169
 
170
  def background_generation_loop():
171
- """后台无限生成线程,确保随时有文本供应"""
172
  add_server_log("后台异步生成线程已就绪,启动自回归循环...")
173
 
174
  while True:
@@ -187,9 +198,8 @@ def background_generation_loop():
187
  if not raw_context or len(raw_context.strip()) < 10:
188
  entry = crypto_rand.choice(GREEK_DICTIONARY)
189
  seed = entry.get("single_word_seed", "Χάος")
190
- # 人称代词驱动器:深度激发第一人称与第二人称叙事(我、你、你们、他们)
191
  starter = crypto_rand.choice([
192
- "I ", "You ", "They ", "We ", "I remember ", "You told me that ", "When they look at us, ", "I say to you that ", "You always asked me "
193
  ])
194
  prompt = f"{seed}\n{starter}"
195
  add_server_log(f"注入希腊词源: 《{seed}》 (代词引导: {starter.strip()})")
@@ -203,40 +213,40 @@ def background_generation_loop():
203
  GLOBAL_STATE["progress"] = 35
204
 
205
  device = "cpu"
206
- model.to(device)
207
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
208
 
209
- add_server_log("SmolLM2-360M CPU 自回归推理中 (max_new_tokens=200, temp=0.72)...")
210
  with torch.no_grad():
211
- output_ids = model.generate(
212
  **inputs,
213
- max_new_tokens=200,
214
  do_sample=True,
215
  temperature=0.72,
216
  top_p=0.88,
217
  repetition_penalty=1.18,
218
  bad_words_ids=BAD_WORDS_IDS,
219
- pad_token_id=tokenizer.eos_token_id
220
  )
221
 
222
  with state_lock:
223
- GLOBAL_STATE["current_stage"] = "TRANSLATING_NLLB200"
224
  GLOBAL_STATE["progress"] = 70
225
 
226
  generated_tokens = output_ids[0][inputs.input_ids.shape[1]:]
227
- decoded_suffix = tokenizer.decode(generated_tokens, skip_special_tokens=True)
228
  raw_content = (starter + decoded_suffix) if starter else decoded_suffix
229
  raw_content = clean_output(raw_content)
230
 
231
  if is_code_or_junk(raw_content):
232
- add_server_log("拦截到编程代码/符号垃圾,主动丢弃并重新抽取文学种子。")
233
  with state_lock:
234
  if len(GLOBAL_STATE["blocks"]) > 0:
235
  GLOBAL_STATE["blocks"][-1]["raw_text"] = ""
236
  continue
237
 
238
- add_server_log(f"SmolLM2 生成完毕 ({len(raw_content)} 字符),送入 Meta NLLB-200 高精度翻译中...")
239
- translated = translate_to_chinese(raw_content)
240
 
241
  with state_lock:
242
  GLOBAL_STATE["current_stage"] = "STREAM_READY"
@@ -244,7 +254,7 @@ def background_generation_loop():
244
 
245
  cleaned = clean_chinese(translated)
246
 
247
- if not cleaned or len(cleaned) < 5:
248
  add_server_log("翻译结果为空,重置上下文准备重新生成。")
249
  with state_lock:
250
  if len(GLOBAL_STATE["blocks"]) > 0:
@@ -261,14 +271,14 @@ def background_generation_loop():
261
  GLOBAL_STATE["blocks"].append(new_block)
262
  if len(GLOBAL_STATE["blocks"]) > 30:
263
  GLOBAL_STATE["blocks"] = GLOBAL_STATE["blocks"][-30:]
264
- add_server_log(f"段落就绪并发布 (字数: {len(cleaned)}): {cleaned[:24]}...")
265
 
266
  except Exception as e:
267
  add_server_log(f"生成管线异常: {e}")
268
  finally:
269
  with state_lock:
270
  GLOBAL_STATE["is_generating"] = False
271
- # 极速流水线:微休 2 秒即刻启动下一段生成,彻底消除 30 秒断流卡顿
272
  time.sleep(2)
273
 
274
  # 启动后台引擎
 
10
  torch.cuda.is_available = lambda: False
11
  torch.cuda.is_initialized = lambda: False
12
 
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
 
15
  # 1. 载入英文基座生成模型 SmolLM2-360M
16
  BASE_MODEL_ID = "HuggingFaceTB/SmolLM2-360M"
17
+ print(f"正在载入 Base 生成模型 {BASE_MODEL_ID}...")
18
+ base_tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID)
19
+ base_model = AutoModelForCausalLM.from_pretrained(
20
  BASE_MODEL_ID,
21
  torch_dtype=torch.float32,
22
  low_cpu_mem_usage=True
23
  )
24
+ print("Base 生成模型装载完毕。")
25
+
26
+ # 2. 载入阿里顶级大语言模型 Qwen2.5-0.5B-Instruct 作为文学翻译与润色中枢
27
+ LLM_MODEL_ID = "Qwen/Qwen2.5-0.5B-Instruct"
28
+ print(f"正在载入文学翻译大语言模型 {LLM_MODEL_ID}...")
29
+ llm_tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
30
+ llm_model = AutoModelForCausalLM.from_pretrained(
31
+ LLM_MODEL_ID,
32
  torch_dtype=torch.float32,
33
  low_cpu_mem_usage=True
34
  )
35
+ print("Qwen2.5-0.5B 大语言模型翻译中枢装载完毕。")
 
36
 
37
  crypto_rand = random.SystemRandom()
38
 
 
65
  ]
66
  BAD_WORDS_IDS = []
67
  for item in BANNED_STRINGS:
68
+ tokens = base_tokenizer.encode(item, add_special_tokens=False)
69
  if tokens:
70
  BAD_WORDS_IDS.append(tokens)
71
 
 
73
  """检测是否为代码片段、语法乱码或技术文档垃圾"""
74
  if not text or len(text.strip()) < 10:
75
  return True
 
76
  if re.search(r"[\{\}\;\:\=\>\<\$\#\\\_\|\&\^\~\`]{2,}", text):
77
  return True
 
78
  code_keywords = r"(?i)\b(?:function|def|return|package|import|class|var|const|void|null|undefined|console|include|typeof|lambda)\b"
79
  if re.search(code_keywords, text):
80
  return True
 
81
  special_char_count = len(re.findall(r"[\{\}\(\)\[\]\;\:\=\+\-\*\/\<\>\&\|\$\#\\]", text))
82
  if special_char_count / max(len(text), 1) > 0.08:
83
  return True
84
  return False
85
 
86
+ def translate_with_llm(english_text: str) -> str:
87
+ """使用阿里 Qwen2.5 大语言模型进行高质量文学翻与润色赋予本极高的现代可读性自然语感"""
88
+ if not english_text or len(english_text.strip()) < 3:
89
+ return ""
90
+
91
+ messages = [
92
+ {
93
+ "role": "system",
94
+ "content": (
95
+ "你是一位杰出的文学翻译家。你的任务是将英文意识流文本翻译为优美、通顺、极具现代文学可读性的中文长段落。\n"
96
+ "翻译准则:\n"
97
+ "1. 语言自然通畅,多用人称代词(我、你、他们),读起来像现代小说或散文随笔;\n"
98
+ "2. 严禁出现机翻生硬腔、英文残留、代码符号或方括号序号;\n"
99
+ "3. 仅输出最终中文译文,严禁输出任何解释、附言或前后缀标记。"
100
+ )
101
+ },
102
+ {
103
+ "role": "user",
104
+ "content": f"请将以下英文文本翻译并润色为一段地道通顺的中文:\n\n{english_text}"
105
+ }
106
+ ]
107
+
108
+ prompt = llm_tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
109
+ inputs = llm_tokenizer(prompt, return_tensors="pt")
110
+
111
  with torch.no_grad():
112
+ output_ids = llm_model.generate(
113
  **inputs,
114
+ max_new_tokens=256,
115
+ temperature=0.65,
116
+ top_p=0.88,
117
+ repetition_penalty=1.15
118
  )
119
+
120
+ gen_tokens = output_ids[0][inputs.input_ids.shape[1]:]
121
+ chinese_text = llm_tokenizer.decode(gen_tokens, skip_special_tokens=True).strip()
122
+ return chinese_text
123
 
124
  def clean_output(text: str) -> str:
125
  """去除 HTML 标签、格式序号与维基百科引用 [1], [2], [note]"""
126
  text = re.sub(r"</?[a-zA-Z0-9]+[^>]*>", "", text)
127
  text = text.replace("<|endoftext|>", "").replace("<|im_end|>", "").replace("<|im_start|>", "")
 
128
  text = re.sub(r"\[[0-9a-zA-Z\s,\.\-_:\'\"]*\]", "", text)
129
  text = re.sub(r"(?m)^\s*(?:[0-9]+[.\、\)]|[一二三四五六七八九十]+[、\.]|[(\(][0-9一二三四五六七八九十]+[)\)]|[①②③④⑤⑥⑦⑧⑨⑩]|(?:第[一二三四五六七八九十0-9]+[条点个部分阶段、::]))\s*", "", text)
130
  text = re.sub(r"\s+[0-9]+[.\、]\s*", " ", text)
131
  text = re.sub(r"\n{3,}", "\n\n", text)
132
 
 
133
  match = re.search(r"[.!?。!?\n][^.!?。!?\n]*$", text)
134
  if match and match.start() > 20:
135
  text = text[:match.start() + 1]
 
139
  """彻底清除翻译后残留的希腊字母、英文字母、特殊符号与任何方括号注记,确保 100% 纯净可读中文"""
140
  if not text:
141
  return ""
142
+ # 彻底清除所有希腊字母与外文字母
143
  text = re.sub(r"[\u0370-\u03ff\u1f00-\u1fff]+", "", text)
 
144
  text = re.sub(r"[a-zA-Z]+", "", text)
145
+ # 清除所有方括号、花括号、分号、项目符号与无意义杂质符号
146
  text = re.sub(r"\[[^\]]*\]", "", text)
147
  text = re.sub(r"【[^】]*】", "", text)
148
  text = re.sub(r"[\[\]【】\{\}\(\)\;\:\=\+\-\*\/\<\>\&\|\$\#\\•·~_\`]+", "", text)
149
+ # 清除多余空格与重复标点
150
  text = re.sub(r"\s+", "", text)
151
  text = re.sub(r"[。\.]{2,}", "。", text)
152
  text = re.sub(r"[,,]{2,}", ",", text)
 
154
  text = re.sub(r"[??]{2,}", "?", text)
155
  text = re.sub(r"^[,。!?、;:\s]+", "", text)
156
  text = text.strip()
 
157
  if text and text[-1] not in ["。", "!", "?", "”", "’"]:
158
  text += "。"
 
 
 
 
 
159
  return text
160
 
161
  # 全局同步状态
 
179
  GLOBAL_STATE["logs"] = GLOBAL_STATE["logs"][-20:]
180
 
181
  def background_generation_loop():
182
+ """后台无限生成线程,确保随时有高水准学文本供应"""
183
  add_server_log("后台异步生成线程已就绪,启动自回归循环...")
184
 
185
  while True:
 
198
  if not raw_context or len(raw_context.strip()) < 10:
199
  entry = crypto_rand.choice(GREEK_DICTIONARY)
200
  seed = entry.get("single_word_seed", "Χάος")
 
201
  starter = crypto_rand.choice([
202
+ "I remember that ", "You once told me that ", "When they looked at us, ", "I said to you that ", "You always asked me if "
203
  ])
204
  prompt = f"{seed}\n{starter}"
205
  add_server_log(f"注入希腊词源: 《{seed}》 (代词引导: {starter.strip()})")
 
213
  GLOBAL_STATE["progress"] = 35
214
 
215
  device = "cpu"
216
+ base_model.to(device)
217
+ inputs = base_tokenizer(prompt, return_tensors="pt").to(device)
218
 
219
+ add_server_log("SmolLM2-360M CPU 自回归推理中 (max_new_tokens=180, temp=0.72)...")
220
  with torch.no_grad():
221
+ output_ids = base_model.generate(
222
  **inputs,
223
+ max_new_tokens=180,
224
  do_sample=True,
225
  temperature=0.72,
226
  top_p=0.88,
227
  repetition_penalty=1.18,
228
  bad_words_ids=BAD_WORDS_IDS,
229
+ pad_token_id=base_tokenizer.eos_token_id
230
  )
231
 
232
  with state_lock:
233
+ GLOBAL_STATE["current_stage"] = "TRANSLATING_QWEN_LLM"
234
  GLOBAL_STATE["progress"] = 70
235
 
236
  generated_tokens = output_ids[0][inputs.input_ids.shape[1]:]
237
+ decoded_suffix = base_tokenizer.decode(generated_tokens, skip_special_tokens=True)
238
  raw_content = (starter + decoded_suffix) if starter else decoded_suffix
239
  raw_content = clean_output(raw_content)
240
 
241
  if is_code_or_junk(raw_content):
242
+ add_server_log("拦截到代码片段或技术符号,主动丢弃并重新抽取文学种子。")
243
  with state_lock:
244
  if len(GLOBAL_STATE["blocks"]) > 0:
245
  GLOBAL_STATE["blocks"][-1]["raw_text"] = ""
246
  continue
247
 
248
+ add_server_log(f"SmolLM2 生成完毕 ({len(raw_content)} 字符),送入 Qwen2.5 大模型文学翻译与润色...")
249
+ translated = translate_with_llm(raw_content)
250
 
251
  with state_lock:
252
  GLOBAL_STATE["current_stage"] = "STREAM_READY"
 
254
 
255
  cleaned = clean_chinese(translated)
256
 
257
+ if not cleaned or len(cleaned) < 10:
258
  add_server_log("翻译结果为空,重置上下文准备重新生成。")
259
  with state_lock:
260
  if len(GLOBAL_STATE["blocks"]) > 0:
 
271
  GLOBAL_STATE["blocks"].append(new_block)
272
  if len(GLOBAL_STATE["blocks"]) > 30:
273
  GLOBAL_STATE["blocks"] = GLOBAL_STATE["blocks"][-30:]
274
+ add_server_log(f"高可读性文学段落就绪 (字数: {len(cleaned)}): {cleaned[:24]}...")
275
 
276
  except Exception as e:
277
  add_server_log(f"生成管线异常: {e}")
278
  finally:
279
  with state_lock:
280
  GLOBAL_STATE["is_generating"] = False
281
+ # 极速流水线:微休 2 秒即刻启动下一段生成
282
  time.sleep(2)
283
 
284
  # 启动后台引擎
requirements.txt CHANGED
@@ -4,4 +4,4 @@ accelerate
4
  gradio
5
  spaces
6
  sentencepiece
7
- sacremoses
 
4
  gradio
5
  spaces
6
  sentencepiece
7
+ tiktoken