Spaces:
Running
Running
移除陈旧函数
Browse files- crazy_functions/下载arxiv论文翻译摘要.py +0 -1
- crazy_functions/总结word文档.py +0 -1
- crazy_functions/批量总结PDF文档.py +0 -1
- crazy_functions/批量总结PDF文档pdfminer.py +0 -1
- crazy_functions/批量翻译PDF文档_多线程.py +105 -12
- crazy_functions/理解PDF文档内容.py +0 -1
- crazy_functions/生成函数注释.py +0 -1
- crazy_functions/读文章写摘要.py +0 -1
- request_llm/bridge_chatgpt.py +4 -33
- toolbox.py +5 -9
crazy_functions/下载arxiv论文翻译摘要.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
from toolbox import update_ui
|
| 2 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down, get_conf
|
| 4 |
import re, requests, unicodedata, os
|
| 5 |
|
|
|
|
| 1 |
from toolbox import update_ui
|
|
|
|
| 2 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down, get_conf
|
| 3 |
import re, requests, unicodedata, os
|
| 4 |
|
crazy_functions/总结word文档.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
fast_debug = False
|
|
|
|
|
|
|
| 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
|
crazy_functions/批量总结PDF文档.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
import re
|
|
|
|
|
|
|
| 1 |
from toolbox import update_ui
|
| 2 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 3 |
import re
|
crazy_functions/批量总结PDF文档pdfminer.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
|
|
|
|
|
|
|
| 1 |
from toolbox import update_ui
|
| 2 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 3 |
|
crazy_functions/批量翻译PDF文档_多线程.py
CHANGED
|
@@ -2,10 +2,12 @@ from toolbox import CatchException, report_execption, write_results_to_file
|
|
| 2 |
from toolbox import update_ui
|
| 3 |
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
| 4 |
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
|
| 5 |
-
|
| 6 |
|
| 7 |
def read_and_clean_pdf_text(fp):
|
| 8 |
"""
|
|
|
|
|
|
|
| 9 |
**输入参数说明**
|
| 10 |
- `fp`:需要读取和清理文本的pdf文件路径
|
| 11 |
|
|
@@ -22,17 +24,43 @@ def read_and_clean_pdf_text(fp):
|
|
| 22 |
- 清除重复的换行
|
| 23 |
- 将每个换行符替换为两个换行符,使每个段落之间有两个换行符分隔
|
| 24 |
"""
|
| 25 |
-
import fitz
|
| 26 |
import re
|
| 27 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
# file_content = ""
|
| 29 |
with fitz.open(fp) as doc:
|
| 30 |
meta_txt = []
|
| 31 |
meta_font = []
|
|
|
|
|
|
|
|
|
|
| 32 |
for index, page in enumerate(doc):
|
| 33 |
# file_content += page.get_text()
|
| 34 |
text_areas = page.get_text("dict") # 获取页面上的文本信息
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# 块元提取 for each word segment with in line for each line cross-line words for each block
|
| 37 |
meta_txt.extend([" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
| 38 |
'- ', '') for t in text_areas['blocks'] if 'lines' in t])
|
|
@@ -41,6 +69,56 @@ def read_and_clean_pdf_text(fp):
|
|
| 41 |
if index == 0:
|
| 42 |
page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
| 43 |
'- ', '') for t in text_areas['blocks'] if 'lines' in t]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
def 把字符太少的块清除为回车(meta_txt):
|
| 46 |
for index, block_txt in enumerate(meta_txt):
|
|
@@ -85,6 +163,10 @@ def read_and_clean_pdf_text(fp):
|
|
| 85 |
# 换行 -> 双换行
|
| 86 |
meta_txt = meta_txt.replace('\n', '\n\n')
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
return meta_txt, page_one_meta
|
| 89 |
|
| 90 |
|
|
@@ -145,21 +227,23 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
|
|
| 145 |
TOKEN_LIMIT_PER_FRAGMENT = 1600
|
| 146 |
generated_conclusion_files = []
|
| 147 |
for index, fp in enumerate(file_manifest):
|
|
|
|
| 148 |
# 读取PDF文件
|
| 149 |
file_content, page_one = read_and_clean_pdf_text(fp)
|
|
|
|
| 150 |
# 递归地切割PDF文件
|
| 151 |
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
| 152 |
from toolbox import get_conf
|
| 153 |
enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
|
| 154 |
def get_token_num(txt): return len(enc.encode(txt))
|
| 155 |
-
# 分解文本
|
| 156 |
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
|
| 157 |
txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
|
| 158 |
page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
|
| 159 |
txt=str(page_one), get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT//4)
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
|
|
|
| 163 |
# 单线,获取文章meta信息
|
| 164 |
paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
| 165 |
inputs=f"以下是一篇学术论文的基础信息,请从中提取出“标题”、“收录会议或期刊”、“作者”、“摘要”、“编号”、“作者邮箱”这六个部分。请用markdown格式输出,最后用中文翻译摘要部分。请提取:{paper_meta}",
|
|
@@ -168,23 +252,32 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
|
|
| 168 |
chatbot=chatbot, history=[],
|
| 169 |
sys_prompt="Your job is to collect information from materials。",
|
| 170 |
)
|
|
|
|
| 171 |
# 多线,翻译
|
| 172 |
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
| 173 |
inputs_array=[
|
| 174 |
-
f"
|
| 175 |
-
inputs_show_user_array=[f"" for
|
| 176 |
llm_kwargs=llm_kwargs,
|
| 177 |
chatbot=chatbot,
|
| 178 |
history_array=[[paper_meta] for _ in paper_fragments],
|
| 179 |
sys_prompt_array=[
|
| 180 |
-
"
|
| 181 |
max_workers=16 # OpenAI所允许的最大并行过载
|
| 182 |
)
|
| 183 |
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
final.extend(gpt_response_collection)
|
| 186 |
create_report_file_name = f"{os.path.basename(fp)}.trans.md"
|
| 187 |
res = write_results_to_file(final, file_name=create_report_file_name)
|
|
|
|
|
|
|
| 188 |
generated_conclusion_files.append(f'./gpt_log/{create_report_file_name}')
|
| 189 |
chatbot.append((f"{fp}完成了吗?", res))
|
| 190 |
yield from update_ui(chatbot=chatbot, history=chatbot) # 刷新界面
|
|
@@ -200,4 +293,4 @@ def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot,
|
|
| 200 |
if os.path.exists(pdf_path):
|
| 201 |
os.remove(pdf_path)
|
| 202 |
chatbot.append(("给出输出文件清单", str(generated_conclusion_files)))
|
| 203 |
-
yield from update_ui(chatbot=chatbot, history=chatbot
|
|
|
|
| 2 |
from toolbox import update_ui
|
| 3 |
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
| 4 |
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
|
| 5 |
+
from colorful import *
|
| 6 |
|
| 7 |
def read_and_clean_pdf_text(fp):
|
| 8 |
"""
|
| 9 |
+
这个函数用于分割pdf,用了很多trick,逻辑较乱,效果奇好,不建议任何人去读这个函数
|
| 10 |
+
|
| 11 |
**输入参数说明**
|
| 12 |
- `fp`:需要读取和清理文本的pdf文件路径
|
| 13 |
|
|
|
|
| 24 |
- 清除重复的换行
|
| 25 |
- 将每个换行符替换为两个换行符,使每个段落之间有两个换行符分隔
|
| 26 |
"""
|
| 27 |
+
import fitz, copy
|
| 28 |
import re
|
| 29 |
import numpy as np
|
| 30 |
+
fc = 0
|
| 31 |
+
fs = 1
|
| 32 |
+
fb = 2
|
| 33 |
+
REMOVE_FOOT_NOTE = True
|
| 34 |
+
REMOVE_FOOT_FFSIZE_PERCENT = 0.95
|
| 35 |
+
def primary_ffsize(l):
|
| 36 |
+
fsize_statiscs = {}
|
| 37 |
+
for wtf in l['spans']:
|
| 38 |
+
if wtf['size'] not in fsize_statiscs: fsize_statiscs[wtf['size']] = 0
|
| 39 |
+
fsize_statiscs[wtf['size']] += len(wtf['text'])
|
| 40 |
+
return max(fsize_statiscs, key=fsize_statiscs.get)
|
| 41 |
+
|
| 42 |
+
def ffsize_same(a,b):
|
| 43 |
+
return abs((a-b)/max(a,b)) < 0.02
|
| 44 |
# file_content = ""
|
| 45 |
with fitz.open(fp) as doc:
|
| 46 |
meta_txt = []
|
| 47 |
meta_font = []
|
| 48 |
+
|
| 49 |
+
meta_line = []
|
| 50 |
+
meta_span = []
|
| 51 |
for index, page in enumerate(doc):
|
| 52 |
# file_content += page.get_text()
|
| 53 |
text_areas = page.get_text("dict") # 获取页面上的文本信息
|
| 54 |
+
for t in text_areas['blocks']:
|
| 55 |
+
if 'lines' in t:
|
| 56 |
+
pf = 998
|
| 57 |
+
for l in t['lines']:
|
| 58 |
+
txt_line = "".join([wtf['text'] for wtf in l['spans']])
|
| 59 |
+
pf = primary_ffsize(l)
|
| 60 |
+
meta_line.append([txt_line, pf, l['bbox'], l])
|
| 61 |
+
for wtf in l['spans']: # for l in t['lines']:
|
| 62 |
+
meta_span.append([wtf['text'], wtf['size'], len(wtf['text'])])
|
| 63 |
+
# meta_line.append(["NEW_BLOCK", pf])
|
| 64 |
# 块元提取 for each word segment with in line for each line cross-line words for each block
|
| 65 |
meta_txt.extend([" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
| 66 |
'- ', '') for t in text_areas['blocks'] if 'lines' in t])
|
|
|
|
| 69 |
if index == 0:
|
| 70 |
page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
| 71 |
'- ', '') for t in text_areas['blocks'] if 'lines' in t]
|
| 72 |
+
# 获取正文主字体
|
| 73 |
+
fsize_statiscs = {}
|
| 74 |
+
for span in meta_span:
|
| 75 |
+
if span[1] not in fsize_statiscs: fsize_statiscs[span[1]] = 0
|
| 76 |
+
fsize_statiscs[span[1]] += span[2]
|
| 77 |
+
main_fsize = max(fsize_statiscs, key=fsize_statiscs.get)
|
| 78 |
+
if REMOVE_FOOT_NOTE:
|
| 79 |
+
give_up_fize_threshold = main_fsize * REMOVE_FOOT_FFSIZE_PERCENT
|
| 80 |
+
|
| 81 |
+
# 切分和重新整合
|
| 82 |
+
mega_sec = []
|
| 83 |
+
sec = []
|
| 84 |
+
for index, line in enumerate(meta_line):
|
| 85 |
+
if index == 0:
|
| 86 |
+
sec.append(line[fc])
|
| 87 |
+
continue
|
| 88 |
+
if REMOVE_FOOT_NOTE:
|
| 89 |
+
if meta_line[index][fs] <= give_up_fize_threshold:
|
| 90 |
+
continue
|
| 91 |
+
if ffsize_same(meta_line[index][fs], meta_line[index-1][fs]):
|
| 92 |
+
# 尝试识别段落
|
| 93 |
+
if meta_line[index][fc].endswith('.') and\
|
| 94 |
+
(meta_line[index-1][fc] != 'NEW_BLOCK') and \
|
| 95 |
+
(meta_line[index][fb][2] - meta_line[index][fb][0]) < (meta_line[index-1][fb][2] - meta_line[index-1][fb][0]) * 0.7:
|
| 96 |
+
sec[-1] += line[fc]
|
| 97 |
+
sec[-1] += "\n\n"
|
| 98 |
+
else:
|
| 99 |
+
sec[-1] += " "
|
| 100 |
+
sec[-1] += line[fc]
|
| 101 |
+
else:
|
| 102 |
+
if (index+1 < len(meta_line)) and \
|
| 103 |
+
meta_line[index][fs] > main_fsize:
|
| 104 |
+
# 单行 + 字体大
|
| 105 |
+
mega_sec.append(copy.deepcopy(sec))
|
| 106 |
+
sec = []
|
| 107 |
+
sec.append("# " + line[fc])
|
| 108 |
+
else:
|
| 109 |
+
# 尝试识别section
|
| 110 |
+
if meta_line[index-1][fs] > meta_line[index][fs]:
|
| 111 |
+
sec.append("\n" + line[fc])
|
| 112 |
+
else:
|
| 113 |
+
sec.append(line[fc])
|
| 114 |
+
mega_sec.append(copy.deepcopy(sec))
|
| 115 |
+
|
| 116 |
+
finals = []
|
| 117 |
+
for ms in mega_sec:
|
| 118 |
+
final = " ".join(ms)
|
| 119 |
+
final = final.replace('- ', ' ')
|
| 120 |
+
finals.append(final)
|
| 121 |
+
meta_txt = finals
|
| 122 |
|
| 123 |
def 把字符太少的块清除为回车(meta_txt):
|
| 124 |
for index, block_txt in enumerate(meta_txt):
|
|
|
|
| 163 |
# 换行 -> 双换行
|
| 164 |
meta_txt = meta_txt.replace('\n', '\n\n')
|
| 165 |
|
| 166 |
+
for f in finals:
|
| 167 |
+
print亮黄(f)
|
| 168 |
+
print亮绿('***************************')
|
| 169 |
+
|
| 170 |
return meta_txt, page_one_meta
|
| 171 |
|
| 172 |
|
|
|
|
| 227 |
TOKEN_LIMIT_PER_FRAGMENT = 1600
|
| 228 |
generated_conclusion_files = []
|
| 229 |
for index, fp in enumerate(file_manifest):
|
| 230 |
+
|
| 231 |
# 读取PDF文件
|
| 232 |
file_content, page_one = read_and_clean_pdf_text(fp)
|
| 233 |
+
|
| 234 |
# 递归地切割PDF文件
|
| 235 |
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
| 236 |
from toolbox import get_conf
|
| 237 |
enc = tiktoken.encoding_for_model(*get_conf('LLM_MODEL'))
|
| 238 |
def get_token_num(txt): return len(enc.encode(txt))
|
|
|
|
| 239 |
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
|
| 240 |
txt=file_content, get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT)
|
| 241 |
page_one_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
|
| 242 |
txt=str(page_one), get_token_fn=get_token_num, limit=TOKEN_LIMIT_PER_FRAGMENT//4)
|
| 243 |
+
|
| 244 |
+
# 为了更好的效果,我们剥离Introduction之后的部分(如果有)
|
| 245 |
+
paper_meta = page_one_fragments[0].split('introduction')[0].split('Introduction')[0].split('INTRODUCTION')[0]
|
| 246 |
+
|
| 247 |
# 单线,获取文章meta信息
|
| 248 |
paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
| 249 |
inputs=f"以下是一篇学术论文的基础信息,请从中提取出“标题”、“收录会议或期刊”、“作者”、“摘要”、“编号”、“作者邮箱”这六个部分。请用markdown格式输出,最后用中文翻译摘要部分。请提取:{paper_meta}",
|
|
|
|
| 252 |
chatbot=chatbot, history=[],
|
| 253 |
sys_prompt="Your job is to collect information from materials。",
|
| 254 |
)
|
| 255 |
+
|
| 256 |
# 多线,翻译
|
| 257 |
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
| 258 |
inputs_array=[
|
| 259 |
+
f"以下是你需要翻译的论文片段:\n{frag}" for frag in paper_fragments],
|
| 260 |
+
inputs_show_user_array=[f"\n---\n 原文: \n\n {frag.replace('#', '')} \n---\n 翻译:\n " for frag in paper_fragments],
|
| 261 |
llm_kwargs=llm_kwargs,
|
| 262 |
chatbot=chatbot,
|
| 263 |
history_array=[[paper_meta] for _ in paper_fragments],
|
| 264 |
sys_prompt_array=[
|
| 265 |
+
"请你作为一个学术翻译,负责把学术论文的片段准确翻译成中文。" for _ in paper_fragments],
|
| 266 |
max_workers=16 # OpenAI所允许的最大并行过载
|
| 267 |
)
|
| 268 |
|
| 269 |
+
# 整理报告的格式
|
| 270 |
+
for i,k in enumerate(gpt_response_collection):
|
| 271 |
+
if i%2==0:
|
| 272 |
+
gpt_response_collection[i] = f"\n\n---\n\n ## 原文[{i//2}/{len(gpt_response_collection)//2}]: \n\n {paper_fragments[i//2].replace('#', '')} \n\n---\n\n ## 翻译[{i//2}/{len(gpt_response_collection)//2}]:\n "
|
| 273 |
+
else:
|
| 274 |
+
gpt_response_collection[i] = gpt_response_collection[i]
|
| 275 |
+
final = ["一、论文概况\n\n---\n\n", paper_meta_info.replace('# ', '### ') + '\n\n---\n\n', "二、论文翻译", ""]
|
| 276 |
final.extend(gpt_response_collection)
|
| 277 |
create_report_file_name = f"{os.path.basename(fp)}.trans.md"
|
| 278 |
res = write_results_to_file(final, file_name=create_report_file_name)
|
| 279 |
+
|
| 280 |
+
# 更新UI
|
| 281 |
generated_conclusion_files.append(f'./gpt_log/{create_report_file_name}')
|
| 282 |
chatbot.append((f"{fp}完成了吗?", res))
|
| 283 |
yield from update_ui(chatbot=chatbot, history=chatbot) # 刷新界面
|
|
|
|
| 293 |
if os.path.exists(pdf_path):
|
| 294 |
os.remove(pdf_path)
|
| 295 |
chatbot.append(("给出输出文件清单", str(generated_conclusion_files)))
|
| 296 |
+
yield from update_ui(chatbot=chatbot, history=chatbot) # 刷新界面
|
crazy_functions/理解PDF文档内容.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
import re
|
|
|
|
|
|
|
| 1 |
from toolbox import update_ui
|
| 2 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 3 |
import re
|
crazy_functions/生成函数注释.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
fast_debug = False
|
|
|
|
|
|
|
| 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
|
crazy_functions/读文章写摘要.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from request_llm.bridge_chatgpt import predict_no_ui
|
| 2 |
from toolbox import update_ui
|
| 3 |
from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
|
| 4 |
fast_debug = False
|
|
|
|
|
|
|
| 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
|
request_llm/bridge_chatgpt.py
CHANGED
|
@@ -39,38 +39,6 @@ def get_full_error(chunk, stream_response):
|
|
| 39 |
break
|
| 40 |
return chunk
|
| 41 |
|
| 42 |
-
def predict_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):
|
| 43 |
-
"""
|
| 44 |
-
发送至chatGPT,等待回复,一次性完成,不显示中间过程。
|
| 45 |
-
predict函数的简化版。
|
| 46 |
-
用于payload比较大的情况,或者用于实现多线、带嵌套的复杂功能。
|
| 47 |
-
|
| 48 |
-
inputs 是本次问询的输入
|
| 49 |
-
top_p, temperature是chatGPT的内部调优参数
|
| 50 |
-
history 是之前的对话列表
|
| 51 |
-
(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误,然后raise ConnectionAbortedError)
|
| 52 |
-
"""
|
| 53 |
-
headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=False)
|
| 54 |
-
|
| 55 |
-
retry = 0
|
| 56 |
-
while True:
|
| 57 |
-
try:
|
| 58 |
-
# make a POST request to the API endpoint, stream=False
|
| 59 |
-
response = requests.post(API_URL, headers=headers, proxies=proxies,
|
| 60 |
-
json=payload, stream=False, timeout=TIMEOUT_SECONDS*2); break
|
| 61 |
-
except requests.exceptions.ReadTimeout as e:
|
| 62 |
-
retry += 1
|
| 63 |
-
traceback.print_exc()
|
| 64 |
-
if retry > MAX_RETRY: raise TimeoutError
|
| 65 |
-
if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')
|
| 66 |
-
|
| 67 |
-
try:
|
| 68 |
-
result = json.loads(response.text)["choices"][0]["message"]["content"]
|
| 69 |
-
return result
|
| 70 |
-
except Exception as e:
|
| 71 |
-
if "choices" not in response.text: print(response.text)
|
| 72 |
-
raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text)
|
| 73 |
-
|
| 74 |
|
| 75 |
def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
|
| 76 |
"""
|
|
@@ -276,7 +244,10 @@ def generate_payload(inputs, llm_kwargs, history, system_prompt, stream):
|
|
| 276 |
"presence_penalty": 0,
|
| 277 |
"frequency_penalty": 0,
|
| 278 |
}
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
| 280 |
return headers,payload
|
| 281 |
|
| 282 |
|
|
|
|
| 39 |
break
|
| 40 |
return chunk
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
|
| 44 |
"""
|
|
|
|
| 244 |
"presence_penalty": 0,
|
| 245 |
"frequency_penalty": 0,
|
| 246 |
}
|
| 247 |
+
try:
|
| 248 |
+
print(f" {llm_kwargs['llm_model']} : {conversation_cnt} : {inputs[:100]}")
|
| 249 |
+
except:
|
| 250 |
+
print('输入中可能存在乱码。')
|
| 251 |
return headers,payload
|
| 252 |
|
| 253 |
|
toolbox.py
CHANGED
|
@@ -87,10 +87,10 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
|
|
| 87 |
top_p, temperature: gpt参数
|
| 88 |
history: gpt参数 对话历史
|
| 89 |
sys_prompt: gpt参数 sys_prompt
|
| 90 |
-
long_connection:
|
| 91 |
"""
|
| 92 |
import time
|
| 93 |
-
from request_llm.bridge_chatgpt import
|
| 94 |
from toolbox import get_conf
|
| 95 |
TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')
|
| 96 |
# 多线程的时候,需要一个mutable结构在不同线程之间传递信息
|
|
@@ -101,13 +101,9 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp
|
|
| 101 |
def mt(i_say, history):
|
| 102 |
while True:
|
| 103 |
try:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
else:
|
| 108 |
-
mutable[0] = predict_no_ui(
|
| 109 |
-
inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)
|
| 110 |
-
break
|
| 111 |
except ConnectionAbortedError as token_exceeded_error:
|
| 112 |
# 尝试计算比例,尽可能多地保留文本
|
| 113 |
p_ratio, n_exceed = get_reduce_token_percent(
|
|
|
|
| 87 |
top_p, temperature: gpt参数
|
| 88 |
history: gpt参数 对话历史
|
| 89 |
sys_prompt: gpt参数 sys_prompt
|
| 90 |
+
long_connection: 是否采用更稳定的连接方式(推荐)(已弃用)
|
| 91 |
"""
|
| 92 |
import time
|
| 93 |
+
from request_llm.bridge_chatgpt import predict_no_ui_long_connection
|
| 94 |
from toolbox import get_conf
|
| 95 |
TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')
|
| 96 |
# 多线程的时候,需要一个mutable结构在不同线程之间传递信息
|
|
|
|
| 101 |
def mt(i_say, history):
|
| 102 |
while True:
|
| 103 |
try:
|
| 104 |
+
mutable[0] = predict_no_ui_long_connection(
|
| 105 |
+
inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)
|
| 106 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
except ConnectionAbortedError as token_exceeded_error:
|
| 108 |
# 尝试计算比例,尽可能多地保留文本
|
| 109 |
p_ratio, n_exceed = get_reduce_token_percent(
|