qingxu99 commited on
Commit
f38929b
1 Parent(s): c8a9069

+Latex全文中英互译插件

Browse files
crazy_functional.py CHANGED
@@ -78,6 +78,8 @@ def get_crazy_functions():
78
  from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
79
  from crazy_functions.Latex全文润色 import Latex英文润色
80
  from crazy_functions.Latex全文润色 import Latex中文润色
 
 
81
 
82
  function_plugins.update({
83
  "批量翻译PDF文档(多线程)": {
@@ -128,6 +130,21 @@ def get_crazy_functions():
128
  "AsButton": False, # 加入下拉菜单中
129
  "Function": HotReload(Latex中文润色)
130
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  })
132
 
133
  ###################### 第三组插件 ###########################
 
78
  from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
79
  from crazy_functions.Latex全文润色 import Latex英文润色
80
  from crazy_functions.Latex全文润色 import Latex中文润色
81
+ from crazy_functions.Latex全文翻译 import Latex中译英
82
+ from crazy_functions.Latex全文翻译 import Latex英译中
83
 
84
  function_plugins.update({
85
  "批量翻译PDF文档(多线程)": {
 
130
  "AsButton": False, # 加入下拉菜单中
131
  "Function": HotReload(Latex中文润色)
132
  },
133
+
134
+ "Latex项目全文中译英(输入路径或上传压缩包)": {
135
+ # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
136
+ "Color": "stop",
137
+ "AsButton": False, # 加入下拉菜单中
138
+ "Function": HotReload(Latex中译英)
139
+ },
140
+ "Latex项目全文英译中(输入路径或上传压缩包)": {
141
+ # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
142
+ "Color": "stop",
143
+ "AsButton": False, # 加入下拉菜单中
144
+ "Function": HotReload(Latex英译中)
145
+ },
146
+
147
+
148
  })
149
 
150
  ###################### 第三组插件 ###########################
crazy_functions/Latex全文翻译.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from toolbox import update_ui
2
+ from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
3
+ fast_debug = False
4
+
5
+ class PaperFileGroup():
6
+ def __init__(self):
7
+ self.file_paths = []
8
+ self.file_contents = []
9
+ self.sp_file_contents = []
10
+ self.sp_file_index = []
11
+ self.sp_file_tag = []
12
+
13
+ # count_token
14
+ import tiktoken
15
+ from toolbox import get_conf
16
+ enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
17
+ def get_token_num(txt): return len(enc.encode(txt))
18
+ self.get_token_num = get_token_num
19
+
20
+ def run_file_split(self, max_token_limit=1900):
21
+ """
22
+ 将长文本分离开来
23
+ """
24
+ for index, file_content in enumerate(self.file_contents):
25
+ if self.get_token_num(file_content) < max_token_limit:
26
+ self.sp_file_contents.append(file_content)
27
+ self.sp_file_index.append(index)
28
+ self.sp_file_tag.append(self.file_paths[index])
29
+ else:
30
+ from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
31
+ segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit)
32
+ for j, segment in enumerate(segments):
33
+ self.sp_file_contents.append(segment)
34
+ self.sp_file_index.append(index)
35
+ self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex")
36
+
37
+ print('Segmentation: done')
38
+
39
+ def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'):
40
+ import time, os, re
41
+ from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
42
+
43
+ # <-------- 读取Latex文件,删除其中的所有注释 ---------->
44
+ pfg = PaperFileGroup()
45
+
46
+ for index, fp in enumerate(file_manifest):
47
+ with open(fp, 'r', encoding='utf-8') as f:
48
+ file_content = f.read()
49
+ # 定义注释的正则表达式
50
+ comment_pattern = r'%.*'
51
+ # 使用正则表达式查找注释,并替换为空字符串
52
+ clean_tex_content = re.sub(comment_pattern, '', file_content)
53
+ # 记录删除注释后的文本
54
+ pfg.file_paths.append(fp)
55
+ pfg.file_contents.append(clean_tex_content)
56
+
57
+ # <-------- 拆分过长的latex文件 ---------->
58
+ pfg.run_file_split(max_token_limit=1024)
59
+ n_split = len(pfg.sp_file_contents)
60
+
61
+ # <-------- 抽取摘要 ---------->
62
+ # if language == 'en':
63
+ # abs_extract_inputs = f"Please write an abstract for this paper"
64
+
65
+ # # 单线,获取文章meta信息
66
+ # paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive(
67
+ # inputs=abs_extract_inputs,
68
+ # inputs_show_user=f"正在抽取摘要信息。",
69
+ # llm_kwargs=llm_kwargs,
70
+ # chatbot=chatbot, history=[],
71
+ # sys_prompt="Your job is to collect information from materials。",
72
+ # )
73
+
74
+ # <-------- 多线程润色开始 ---------->
75
+ if language == 'en->zh':
76
+ inputs_array = ["Below is a section from an English academic paper, translate it into Chinese, do not modify any latex command such as \section, \cite and equations:" +
77
+ f"\n\n{frag}" for frag in pfg.sp_file_contents]
78
+ inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
79
+ sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
80
+ elif language == 'zh->en':
81
+ inputs_array = [f"Below is a section from a Chinese academic paper, translate it into English, do not modify any latex command such as \section, \cite and equations:" +
82
+ f"\n\n{frag}" for frag in pfg.sp_file_contents]
83
+ inputs_show_user_array = [f"润色 {f}" for f in pfg.sp_file_tag]
84
+ sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
85
+
86
+ gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
87
+ inputs_array=inputs_array,
88
+ inputs_show_user_array=inputs_show_user_array,
89
+ llm_kwargs=llm_kwargs,
90
+ chatbot=chatbot,
91
+ history_array=[[""] for _ in range(n_split)],
92
+ sys_prompt_array=sys_prompt_array,
93
+ max_workers=10, # OpenAI所允许的最大并行过载
94
+ scroller_max_len = 80
95
+ )
96
+
97
+ # <-------- 整理结果,退出 ---------->
98
+ create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md"
99
+ res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name)
100
+ history = gpt_response_collection
101
+ chatbot.append((f"{fp}完成了吗?", res))
102
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
103
+
104
+
105
+
106
+
107
+
108
+ @CatchException
109
+ def Latex英译中(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
110
+ # 基本信息:功能、贡献者
111
+ chatbot.append([
112
+ "函数插件功能?",
113
+ "对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"])
114
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
115
+
116
+ # 尝试导入依赖,如果缺少依赖,则给出安装建议
117
+ try:
118
+ import tiktoken
119
+ except:
120
+ report_execption(chatbot, history,
121
+ a=f"解析项目: {txt}",
122
+ b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
123
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
124
+ return
125
+ history = [] # 清空历史,以免输入溢出
126
+ import glob, os
127
+ if os.path.exists(txt):
128
+ project_folder = txt
129
+ else:
130
+ if txt == "": txt = '空空如也的输入栏'
131
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
132
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
133
+ return
134
+ file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
135
+ if len(file_manifest) == 0:
136
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
137
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
138
+ return
139
+ yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en->zh')
140
+
141
+
142
+
143
+
144
+
145
+ @CatchException
146
+ def Latex中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
147
+ # 基本信息:功能、贡献者
148
+ chatbot.append([
149
+ "函数插件功能?",
150
+ "对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"])
151
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
152
+
153
+ # 尝试导入依赖,如果缺少依赖,则给出安装建议
154
+ try:
155
+ import tiktoken
156
+ except:
157
+ report_execption(chatbot, history,
158
+ a=f"解析项目: {txt}",
159
+ b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
160
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
161
+ return
162
+ history = [] # 清空历史,以免输入溢出
163
+ import glob, os
164
+ if os.path.exists(txt):
165
+ project_folder = txt
166
+ else:
167
+ if txt == "": txt = '空空如也的输入栏'
168
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
169
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
170
+ return
171
+ file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
172
+ if len(file_manifest) == 0:
173
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
174
+ yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
175
+ return
176
+ yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh->en')