toolbox.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  1. import markdown
  2. import importlib
  3. import time
  4. import inspect
  5. import re
  6. import os
  7. import base64
  8. import gradio
  9. import shutil
  10. import glob
  11. import math
  12. from latex2mathml.converter import convert as tex2mathml
  13. from functools import wraps, lru_cache
  14. pj = os.path.join
  15. default_user_name = 'default_user'
  16. """
  17. ========================================================================
  18. 第一部分
  19. 函数插件输入输出接驳区
  20. - ChatBotWithCookies: 带Cookies的Chatbot类,为实现更多强大的功能做基础
  21. - ArgsGeneralWrapper: 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构
  22. - update_ui: 刷新界面用 yield from update_ui(chatbot, history)
  23. - CatchException: 将插件中出的所有问题显示在界面上
  24. - HotReload: 实现插件的热更新
  25. - trimmed_format_exc: 打印traceback,为了安全而隐藏绝对地址
  26. ========================================================================
  27. """
  28. class ChatBotWithCookies(list):
  29. def __init__(self, cookie):
  30. """
  31. cookies = {
  32. 'top_p': top_p,
  33. 'temperature': temperature,
  34. 'lock_plugin': bool,
  35. "files_to_promote": ["file1", "file2"],
  36. "most_recent_uploaded": {
  37. "path": "uploaded_path",
  38. "time": time.time(),
  39. "time_str": "timestr",
  40. }
  41. }
  42. """
  43. self._cookies = cookie
  44. def write_list(self, list):
  45. for t in list:
  46. self.append(t)
  47. def get_list(self):
  48. return [t for t in self]
  49. def get_cookies(self):
  50. return self._cookies
  51. def ArgsGeneralWrapper(f):
  52. """
  53. 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
  54. """
  55. def decorated(request: gradio.Request, cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg, *args):
  56. txt_passon = txt
  57. if txt == "" and txt2 != "": txt_passon = txt2
  58. # 引入一个有cookie的chatbot
  59. if request.username is not None:
  60. user_name = request.username
  61. else:
  62. user_name = default_user_name
  63. cookies.update({
  64. 'top_p': top_p,
  65. 'api_key': cookies['api_key'],
  66. 'llm_model': llm_model,
  67. 'temperature': temperature,
  68. 'user_name': user_name,
  69. })
  70. llm_kwargs = {
  71. 'api_key': cookies['api_key'],
  72. 'llm_model': llm_model,
  73. 'top_p': top_p,
  74. 'max_length': max_length,
  75. 'temperature': temperature,
  76. 'client_ip': request.client.host,
  77. 'most_recent_uploaded': cookies.get('most_recent_uploaded')
  78. }
  79. plugin_kwargs = {
  80. "advanced_arg": plugin_advanced_arg,
  81. }
  82. chatbot_with_cookie = ChatBotWithCookies(cookies)
  83. chatbot_with_cookie.write_list(chatbot)
  84. if cookies.get('lock_plugin', None) is None:
  85. # 正常状态
  86. if len(args) == 0: # 插件通道
  87. yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, request)
  88. else: # 对话通道,或者基础功能通道
  89. yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args)
  90. else:
  91. # 处理少数情况下的特殊插件的锁定状态
  92. module, fn_name = cookies['lock_plugin'].split('->')
  93. f_hot_reload = getattr(importlib.import_module(module, fn_name), fn_name)
  94. yield from f_hot_reload(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, request)
  95. # 判断一下用户是否错误地通过对话通道进入,如果是,则进行提醒
  96. final_cookies = chatbot_with_cookie.get_cookies()
  97. # len(args) != 0 代表“提交”键对话通道,或者基础功能通道
  98. if len(args) != 0 and 'files_to_promote' in final_cookies and len(final_cookies['files_to_promote']) > 0:
  99. chatbot_with_cookie.append(
  100. ["检测到**滞留的缓存文档**,请及时处理。", "请及时点击“**保存当前对话**”获取所有滞留文档。"])
  101. yield from update_ui(chatbot_with_cookie, final_cookies['history'], msg="检测到被滞留的缓存文档")
  102. return decorated
  103. def update_ui(chatbot, history, msg='正常', **kwargs): # 刷新界面
  104. """
  105. 刷新用户界面
  106. """
  107. assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时, 可用clear将其清空, 然后用for+append循环重新赋值。"
  108. cookies = chatbot.get_cookies()
  109. # 备份一份History作为记录
  110. cookies.update({'history': history})
  111. # 解决插件锁定时的界面显示问题
  112. if cookies.get('lock_plugin', None):
  113. label = cookies.get('llm_model', "") + " | " + "正在锁定插件" + cookies.get('lock_plugin', None)
  114. chatbot_gr = gradio.update(value=chatbot, label=label)
  115. if cookies.get('label', "") != label: cookies['label'] = label # 记住当前的label
  116. elif cookies.get('label', None):
  117. chatbot_gr = gradio.update(value=chatbot, label=cookies.get('llm_model', ""))
  118. cookies['label'] = None # 清空label
  119. else:
  120. chatbot_gr = chatbot
  121. yield cookies, chatbot_gr, history, msg
  122. def update_ui_lastest_msg(lastmsg, chatbot, history, delay=1): # 刷新界面
  123. """
  124. 刷新用户界面
  125. """
  126. if len(chatbot) == 0: chatbot.append(["update_ui_last_msg", lastmsg])
  127. chatbot[-1] = list(chatbot[-1])
  128. chatbot[-1][-1] = lastmsg
  129. yield from update_ui(chatbot=chatbot, history=history)
  130. time.sleep(delay)
  131. def trimmed_format_exc():
  132. import os, traceback
  133. str = traceback.format_exc()
  134. current_path = os.getcwd()
  135. replace_path = "."
  136. return str.replace(current_path, replace_path)
  137. def CatchException(f):
  138. """
  139. 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。
  140. """
  141. @wraps(f)
  142. def decorated(main_input, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, *args, **kwargs):
  143. try:
  144. yield from f(main_input, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, *args, **kwargs)
  145. except Exception as e:
  146. from check_proxy import check_proxy
  147. from toolbox import get_conf
  148. proxies = get_conf('proxies')
  149. tb_str = '```\n' + trimmed_format_exc() + '```'
  150. if len(chatbot_with_cookie) == 0:
  151. chatbot_with_cookie.clear()
  152. chatbot_with_cookie.append(["插件调度异常", "异常原因"])
  153. chatbot_with_cookie[-1] = (chatbot_with_cookie[-1][0], f"[Local Message] 插件调用出错: \n\n{tb_str} \n")
  154. yield from update_ui(chatbot=chatbot_with_cookie, history=history, msg=f'异常 {e}') # 刷新界面
  155. return decorated
  156. def HotReload(f):
  157. """
  158. HotReload的装饰器函数,用于实现Python函数插件的热更新。
  159. 函数热更新是指在不停止程序运行的情况下,更新函数代码,从而达到实时更新功能。
  160. 在装饰器内部,使用wraps(f)来保留函数的元信息,并定义了一个名为decorated的内部函数。
  161. 内部函数通过使用importlib模块的reload函数和inspect模块的getmodule函数来重新加载并获取函数模块,
  162. 然后通过getattr函数获取函数名,并在新模块中重新加载函数。
  163. 最后,使用yield from语句返回重新加载过的函数,并在被装饰的函数上执行。
  164. 最终,装饰器函数返回内部函数。这个内部函数可以将函数的原始定义更新为最新版本,并执行函数的新版本。
  165. """
  166. if get_conf('PLUGIN_HOT_RELOAD'):
  167. @wraps(f)
  168. def decorated(*args, **kwargs):
  169. fn_name = f.__name__
  170. f_hot_reload = getattr(importlib.reload(inspect.getmodule(f)), fn_name)
  171. yield from f_hot_reload(*args, **kwargs)
  172. return decorated
  173. else:
  174. return f
  175. """
  176. ========================================================================
  177. 第二部分
  178. 其他小工具:
  179. - write_history_to_file: 将结果写入markdown文件中
  180. - regular_txt_to_markdown: 将普通文本转换为Markdown格式的文本。
  181. - report_exception: 向chatbot中添加简单的意外错误信息
  182. - text_divide_paragraph: 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
  183. - markdown_convertion: 用多种方式组合,将markdown转化为好看的html
  184. - format_io: 接管gradio默认的markdown处理方式
  185. - on_file_uploaded: 处理文件的上传(自动解压)
  186. - on_report_generated: 将生成的报告自动投射到文件上传区
  187. - clip_history: 当历史上下文过长时,自动截断
  188. - get_conf: 获取设置
  189. - select_api_key: 根据当前的模型类别,抽取可用的api-key
  190. ========================================================================
  191. """
  192. def get_reduce_token_percent(text):
  193. """
  194. * 此函数未来将被弃用
  195. """
  196. try:
  197. # text = "maximum context length is 4097 tokens. However, your messages resulted in 4870 tokens"
  198. pattern = r"(\d+)\s+tokens\b"
  199. match = re.findall(pattern, text)
  200. EXCEED_ALLO = 500 # 稍微留一点余地,否则在回复时会因余量太少出问题
  201. max_limit = float(match[0]) - EXCEED_ALLO
  202. current_tokens = float(match[1])
  203. ratio = max_limit / current_tokens
  204. assert ratio > 0 and ratio < 1
  205. return ratio, str(int(current_tokens - max_limit))
  206. except:
  207. return 0.5, '不详'
  208. def write_history_to_file(history, file_basename=None, file_fullname=None, auto_caption=True):
  209. """
  210. 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。
  211. """
  212. import os
  213. import time
  214. if file_fullname is None:
  215. if file_basename is not None:
  216. file_fullname = pj(get_log_folder(), file_basename)
  217. else:
  218. file_fullname = pj(get_log_folder(), f'GPT-Academic-{gen_time_str()}.md')
  219. os.makedirs(os.path.dirname(file_fullname), exist_ok=True)
  220. with open(file_fullname, 'w', encoding='utf8') as f:
  221. f.write('# GPT-Academic Report\n')
  222. for i, content in enumerate(history):
  223. try:
  224. if type(content) != str: content = str(content)
  225. except:
  226. continue
  227. if i % 2 == 0 and auto_caption:
  228. f.write('## ')
  229. try:
  230. f.write(content)
  231. except:
  232. # remove everything that cannot be handled by utf8
  233. f.write(content.encode('utf-8', 'ignore').decode())
  234. f.write('\n\n')
  235. res = os.path.abspath(file_fullname)
  236. return res
  237. def regular_txt_to_markdown(text):
  238. """
  239. 将普通文本转换为Markdown格式的文本。
  240. """
  241. text = text.replace('\n', '\n\n')
  242. text = text.replace('\n\n\n', '\n\n')
  243. text = text.replace('\n\n\n', '\n\n')
  244. return text
  245. def report_exception(chatbot, history, a, b):
  246. """
  247. 向chatbot中添加错误信息
  248. """
  249. chatbot.append((a, b))
  250. history.extend([a, b])
  251. def text_divide_paragraph(text):
  252. """
  253. 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。
  254. """
  255. pre = '<div class="markdown-body">'
  256. suf = '</div>'
  257. if text.startswith(pre) and text.endswith(suf):
  258. return text
  259. if '```' in text:
  260. # careful input
  261. return text
  262. elif '</div>' in text:
  263. # careful input
  264. return text
  265. else:
  266. # whatever input
  267. lines = text.split("\n")
  268. for i, line in enumerate(lines):
  269. lines[i] = lines[i].replace(" ", "&nbsp;")
  270. text = "</br>".join(lines)
  271. return pre + text + suf
  272. @lru_cache(maxsize=128) # 使用 lru缓存 加快转换速度
  273. def markdown_convertion(txt):
  274. """
  275. 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。
  276. """
  277. pre = '<div class="markdown-body">'
  278. suf = '</div>'
  279. if txt.startswith(pre) and txt.endswith(suf):
  280. # print('警告,输入了已经经过转化的字符串,二次转化可能出问题')
  281. return txt # 已经被转化过,不需要再次转化
  282. markdown_extension_configs = {
  283. 'mdx_math': {
  284. 'enable_dollar_delimiter': True,
  285. 'use_gitlab_delimiters': False,
  286. },
  287. }
  288. find_equation_pattern = r'<script type="math/tex(?:.*?)>(.*?)</script>'
  289. def tex2mathml_catch_exception(content, *args, **kwargs):
  290. try:
  291. content = tex2mathml(content, *args, **kwargs)
  292. except:
  293. content = content
  294. return content
  295. def replace_math_no_render(match):
  296. content = match.group(1)
  297. if 'mode=display' in match.group(0):
  298. content = content.replace('\n', '</br>')
  299. return f"<font color=\"#00FF00\">$$</font><font color=\"#FF00FF\">{content}</font><font color=\"#00FF00\">$$</font>"
  300. else:
  301. return f"<font color=\"#00FF00\">$</font><font color=\"#FF00FF\">{content}</font><font color=\"#00FF00\">$</font>"
  302. def replace_math_render(match):
  303. content = match.group(1)
  304. if 'mode=display' in match.group(0):
  305. if '\\begin{aligned}' in content:
  306. content = content.replace('\\begin{aligned}', '\\begin{array}')
  307. content = content.replace('\\end{aligned}', '\\end{array}')
  308. content = content.replace('&', ' ')
  309. content = tex2mathml_catch_exception(content, display="block")
  310. return content
  311. else:
  312. return tex2mathml_catch_exception(content)
  313. def markdown_bug_hunt(content):
  314. """
  315. 解决一个mdx_math的bug(单$包裹begin命令时多余<script>)
  316. """
  317. content = content.replace('<script type="math/tex">\n<script type="math/tex; mode=display">',
  318. '<script type="math/tex; mode=display">')
  319. content = content.replace('</script>\n</script>', '</script>')
  320. return content
  321. def is_equation(txt):
  322. """
  323. 判定是否为公式 | 测试1 写出洛伦兹定律,使用tex格式公式 测试2 给出柯西不等式,使用latex格式 测试3 写出麦克斯韦方程组
  324. """
  325. if '```' in txt and '```reference' not in txt: return False
  326. if '$' not in txt and '\\[' not in txt: return False
  327. mathpatterns = {
  328. r'(?<!\\|\$)(\$)([^\$]+)(\$)': {'allow_multi_lines': False}, #  $...$
  329. r'(?<!\\)(\$\$)([^\$]+)(\$\$)': {'allow_multi_lines': True}, # $$...$$
  330. r'(?<!\\)(\\\[)(.+?)(\\\])': {'allow_multi_lines': False}, # \[...\]
  331. # r'(?<!\\)(\\\()(.+?)(\\\))': {'allow_multi_lines': False}, # \(...\)
  332. # r'(?<!\\)(\\begin{([a-z]+?\*?)})(.+?)(\\end{\2})': {'allow_multi_lines': True}, # \begin...\end
  333. # r'(?<!\\)(\$`)([^`]+)(`\$)': {'allow_multi_lines': False}, # $`...`$
  334. }
  335. matches = []
  336. for pattern, property in mathpatterns.items():
  337. flags = re.ASCII | re.DOTALL if property['allow_multi_lines'] else re.ASCII
  338. matches.extend(re.findall(pattern, txt, flags))
  339. if len(matches) == 0: return False
  340. contain_any_eq = False
  341. illegal_pattern = re.compile(r'[^\x00-\x7F]|echo')
  342. for match in matches:
  343. if len(match) != 3: return False
  344. eq_canidate = match[1]
  345. if illegal_pattern.search(eq_canidate):
  346. return False
  347. else:
  348. contain_any_eq = True
  349. return contain_any_eq
  350. def fix_markdown_indent(txt):
  351. # fix markdown indent
  352. if (' - ' not in txt) or ('. ' not in txt):
  353. return txt # do not need to fix, fast escape
  354. # walk through the lines and fix non-standard indentation
  355. lines = txt.split("\n")
  356. pattern = re.compile(r'^\s+-')
  357. activated = False
  358. for i, line in enumerate(lines):
  359. if line.startswith('- ') or line.startswith('1. '):
  360. activated = True
  361. if activated and pattern.match(line):
  362. stripped_string = line.lstrip()
  363. num_spaces = len(line) - len(stripped_string)
  364. if (num_spaces % 4) == 3:
  365. num_spaces_should_be = math.ceil(num_spaces / 4) * 4
  366. lines[i] = ' ' * num_spaces_should_be + stripped_string
  367. return '\n'.join(lines)
  368. txt = fix_markdown_indent(txt)
  369. if is_equation(txt): # 有$标识的公式符号,且没有代码段```的标识
  370. # convert everything to html format
  371. split = markdown.markdown(text='---')
  372. convert_stage_1 = markdown.markdown(text=txt, extensions=['sane_lists', 'tables', 'mdx_math', 'fenced_code'],
  373. extension_configs=markdown_extension_configs)
  374. convert_stage_1 = markdown_bug_hunt(convert_stage_1)
  375. # 1. convert to easy-to-copy tex (do not render math)
  376. convert_stage_2_1, n = re.subn(find_equation_pattern, replace_math_no_render, convert_stage_1, flags=re.DOTALL)
  377. # 2. convert to rendered equation
  378. convert_stage_2_2, n = re.subn(find_equation_pattern, replace_math_render, convert_stage_1, flags=re.DOTALL)
  379. # cat them together
  380. return pre + convert_stage_2_1 + f'{split}' + convert_stage_2_2 + suf
  381. else:
  382. return pre + markdown.markdown(txt, extensions=['sane_lists', 'tables', 'fenced_code', 'codehilite']) + suf
  383. def close_up_code_segment_during_stream(gpt_reply):
  384. """
  385. 在gpt输出代码的中途(输出了前面的```,但还没输出完后面的```),补上后面的```
  386. Args:
  387. gpt_reply (str): GPT模型返回的回复字符串。
  388. Returns:
  389. str: 返回一个新的字符串,将输出代码片段的“后面的```”补上。
  390. """
  391. if '```' not in gpt_reply:
  392. return gpt_reply
  393. if gpt_reply.endswith('```'):
  394. return gpt_reply
  395. # 排除了以上两个情况,我们
  396. segments = gpt_reply.split('```')
  397. n_mark = len(segments) - 1
  398. if n_mark % 2 == 1:
  399. return gpt_reply + '\n```' # 输出代码片段中!
  400. else:
  401. return gpt_reply
  402. def format_io(self, y):
  403. """
  404. 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。
  405. """
  406. if y is None or y == []:
  407. return []
  408. i_ask, gpt_reply = y[-1]
  409. # 输入部分太自由,预处理一波
  410. if i_ask is not None: i_ask = text_divide_paragraph(i_ask)
  411. # 当代码输出半截的时候,试着补上后个```
  412. if gpt_reply is not None: gpt_reply = close_up_code_segment_during_stream(gpt_reply)
  413. # process
  414. y[-1] = (
  415. None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code', 'tables']),
  416. None if gpt_reply is None else markdown_convertion(gpt_reply)
  417. )
  418. return y
  419. def find_free_port():
  420. """
  421. 返回当前系统中可用的未使用端口。
  422. """
  423. import socket
  424. from contextlib import closing
  425. with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
  426. s.bind(('', 0))
  427. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  428. return s.getsockname()[1]
  429. def extract_archive(file_path, dest_dir):
  430. import zipfile
  431. import tarfile
  432. import os
  433. # Get the file extension of the input file
  434. file_extension = os.path.splitext(file_path)[1]
  435. # Extract the archive based on its extension
  436. if file_extension == '.zip':
  437. with zipfile.ZipFile(file_path, 'r') as zipobj:
  438. zipobj.extractall(path=dest_dir)
  439. print("Successfully extracted zip archive to {}".format(dest_dir))
  440. elif file_extension in ['.tar', '.gz', '.bz2']:
  441. with tarfile.open(file_path, 'r:*') as tarobj:
  442. tarobj.extractall(path=dest_dir)
  443. print("Successfully extracted tar archive to {}".format(dest_dir))
  444. # 第三方库,需要预先pip install rarfile
  445. # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以
  446. elif file_extension == '.rar':
  447. try:
  448. import rarfile
  449. with rarfile.RarFile(file_path) as rf:
  450. rf.extractall(path=dest_dir)
  451. print("Successfully extracted rar archive to {}".format(dest_dir))
  452. except:
  453. print("Rar format requires additional dependencies to install")
  454. return '\n\n解压失败! 需要安装pip install rarfile来解压rar文件。建议:使用zip压缩格式。'
  455. # 第三方库,需要预先pip install py7zr
  456. elif file_extension == '.7z':
  457. try:
  458. import py7zr
  459. with py7zr.SevenZipFile(file_path, mode='r') as f:
  460. f.extractall(path=dest_dir)
  461. print("Successfully extracted 7z archive to {}".format(dest_dir))
  462. except:
  463. print("7z format requires additional dependencies to install")
  464. return '\n\n解压失败! 需要安装pip install py7zr来解压7z文件'
  465. else:
  466. return ''
  467. return ''
  468. def find_recent_files(directory):
  469. """
  470. me: find files that is created with in one minutes under a directory with python, write a function
  471. gpt: here it is!
  472. """
  473. import os
  474. import time
  475. current_time = time.time()
  476. one_minute_ago = current_time - 60
  477. recent_files = []
  478. if not os.path.exists(directory):
  479. os.makedirs(directory, exist_ok=True)
  480. for filename in os.listdir(directory):
  481. file_path = pj(directory, filename)
  482. if file_path.endswith('.log'):
  483. continue
  484. created_time = os.path.getmtime(file_path)
  485. if created_time >= one_minute_ago:
  486. if os.path.isdir(file_path):
  487. continue
  488. recent_files.append(file_path)
  489. return recent_files
  490. def file_already_in_downloadzone(file, user_path):
  491. try:
  492. parent_path = os.path.abspath(user_path)
  493. child_path = os.path.abspath(file)
  494. if os.path.samefile(os.path.commonpath([parent_path, child_path]), parent_path):
  495. return True
  496. else:
  497. return False
  498. except:
  499. return False
  500. def promote_file_to_downloadzone(file, rename_file=None, chatbot=None):
  501. # 将文件复制一份到下载区
  502. import shutil
  503. if chatbot is not None:
  504. user_name = get_user(chatbot)
  505. else:
  506. user_name = default_user_name
  507. if not os.path.exists(file):
  508. raise FileNotFoundError(f'文件{file}不存在')
  509. user_path = get_log_folder(user_name, plugin_name=None)
  510. if file_already_in_downloadzone(file, user_path):
  511. new_path = file
  512. else:
  513. user_path = get_log_folder(user_name, plugin_name='downloadzone')
  514. if rename_file is None: rename_file = f'{gen_time_str()}-{os.path.basename(file)}'
  515. new_path = pj(user_path, rename_file)
  516. # 如果已经存在,先删除
  517. if os.path.exists(new_path) and not os.path.samefile(new_path, file): os.remove(new_path)
  518. # 把文件复制过去
  519. if not os.path.exists(new_path): shutil.copyfile(file, new_path)
  520. # 将文件添加到chatbot cookie中
  521. if chatbot is not None:
  522. if 'files_to_promote' in chatbot._cookies:
  523. current = chatbot._cookies['files_to_promote']
  524. else:
  525. current = []
  526. if new_path not in current: # 避免把同一个文件添加多次
  527. chatbot._cookies.update({'files_to_promote': [new_path] + current})
  528. return new_path
  529. def disable_auto_promotion(chatbot):
  530. chatbot._cookies.update({'files_to_promote': []})
  531. return
  532. def del_outdated_uploads(outdate_time_seconds, target_path_base=None):
  533. if target_path_base is None:
  534. user_upload_dir = get_conf('PATH_PRIVATE_UPLOAD')
  535. else:
  536. user_upload_dir = target_path_base
  537. current_time = time.time()
  538. one_hour_ago = current_time - outdate_time_seconds
  539. # Get a list of all subdirectories in the user_upload_dir folder
  540. # Remove subdirectories that are older than one hour
  541. for subdirectory in glob.glob(f'{user_upload_dir}/*'):
  542. subdirectory_time = os.path.getmtime(subdirectory)
  543. if subdirectory_time < one_hour_ago:
  544. try:
  545. shutil.rmtree(subdirectory)
  546. except:
  547. pass
  548. return
  549. def html_local_file(file):
  550. base_path = os.path.dirname(__file__) # 项目目录
  551. if os.path.exists(str(file)):
  552. file = f'file={file.replace(base_path, ".")}'
  553. return file
  554. def html_local_img(__file, layout='left', max_width=None, max_height=None, md=True):
  555. style = ''
  556. if max_width is not None:
  557. style += f"max-width: {max_width};"
  558. if max_height is not None:
  559. style += f"max-height: {max_height};"
  560. __file = html_local_file(__file)
  561. a = f'<div align="{layout}"><img src="{__file}" style="{style}"></div>'
  562. if md:
  563. a = f'![{__file}]({__file})'
  564. return a
  565. def file_manifest_filter_type(file_list, filter_: list = None):
  566. new_list = []
  567. if not filter_: filter_ = ['png', 'jpg', 'jpeg']
  568. for file in file_list:
  569. if str(os.path.basename(file)).split('.')[-1] in filter_:
  570. new_list.append(html_local_img(file, md=False))
  571. else:
  572. new_list.append(file)
  573. return new_list
  574. def to_markdown_tabs(head: list, tabs: list, alignment=':---:', column=False):
  575. """
  576. Args:
  577. head: 表头:[]
  578. tabs: 表值:[[列1], [列2], [列3], [列4]]
  579. alignment: :--- 左对齐, :---: 居中对齐, ---: 右对齐
  580. column: True to keep data in columns, False to keep data in rows (default).
  581. Returns:
  582. A string representation of the markdown table.
  583. """
  584. if column:
  585. transposed_tabs = list(map(list, zip(*tabs)))
  586. else:
  587. transposed_tabs = tabs
  588. # Find the maximum length among the columns
  589. max_len = max(len(column) for column in transposed_tabs)
  590. tab_format = "| %s "
  591. tabs_list = "".join([tab_format % i for i in head]) + '|\n'
  592. tabs_list += "".join([tab_format % alignment for i in head]) + '|\n'
  593. for i in range(max_len):
  594. row_data = [tab[i] if i < len(tab) else '' for tab in transposed_tabs]
  595. row_data = file_manifest_filter_type(row_data, filter_=None)
  596. tabs_list += "".join([tab_format % i for i in row_data]) + '|\n'
  597. return tabs_list
  598. def on_file_uploaded(request: gradio.Request, files, chatbot, txt, txt2, checkboxes, cookies):
  599. """
  600. 当文件被上传时的回调函数
  601. """
  602. if len(files) == 0:
  603. return chatbot, txt
  604. # 创建工作路径
  605. user_name = default_user_name if not request.username else request.username
  606. time_tag = gen_time_str()
  607. target_path_base = get_upload_folder(user_name, tag=time_tag)
  608. os.makedirs(target_path_base, exist_ok=True)
  609. # 移除过时的旧文件从而节省空间&保护隐私
  610. outdate_time_seconds = 3600 # 一小时
  611. del_outdated_uploads(outdate_time_seconds, get_upload_folder(user_name))
  612. # 逐个文件转移到目标路径
  613. upload_msg = ''
  614. for file in files:
  615. file_origin_name = os.path.basename(file.orig_name)
  616. this_file_path = pj(target_path_base, file_origin_name)
  617. shutil.move(file.name, this_file_path)
  618. upload_msg += extract_archive(file_path=this_file_path, dest_dir=this_file_path + '.extract')
  619. # 整理文件集合 输出消息
  620. moved_files = [fp for fp in glob.glob(f'{target_path_base}/**/*', recursive=True)]
  621. moved_files_str = to_markdown_tabs(head=['文件'], tabs=[moved_files])
  622. chatbot.append(['我上传了文件,请查收',
  623. f'[Local Message] 收到以下文件: \n\n{moved_files_str}' +
  624. f'\n\n调用路径参数已自动修正到: \n\n{txt}' +
  625. f'\n\n现在您点击任意函数插件时,以上文件将被作为输入参数' + upload_msg])
  626. txt, txt2 = target_path_base, ""
  627. if "浮动输入区" in checkboxes:
  628. txt, txt2 = txt2, txt
  629. # 记录近期文件
  630. cookies.update({
  631. 'most_recent_uploaded': {
  632. 'path': target_path_base,
  633. 'time': time.time(),
  634. 'time_str': time_tag
  635. }})
  636. return chatbot, txt, txt2, cookies
  637. def on_report_generated(cookies, files, chatbot):
  638. # from toolbox import find_recent_files
  639. # PATH_LOGGING = get_conf('PATH_LOGGING')
  640. if 'files_to_promote' in cookies:
  641. report_files = cookies['files_to_promote']
  642. cookies.pop('files_to_promote')
  643. else:
  644. report_files = []
  645. # report_files = find_recent_files(PATH_LOGGING)
  646. if len(report_files) == 0:
  647. return cookies, None, chatbot
  648. # files.extend(report_files)
  649. file_links = ''
  650. for f in report_files: file_links += f'<br/><a href="file={os.path.abspath(f)}" target="_blank">{f}</a>'
  651. chatbot.append(['报告如何远程获取?', f'报告已经添加到右侧“文件上传区”(可能处于折叠状态),请查收。{file_links}'])
  652. return cookies, report_files, chatbot
  653. def load_chat_cookies():
  654. API_KEY, LLM_MODEL, AZURE_API_KEY = get_conf('API_KEY', 'LLM_MODEL', 'AZURE_API_KEY')
  655. AZURE_CFG_ARRAY, NUM_CUSTOM_BASIC_BTN = get_conf('AZURE_CFG_ARRAY', 'NUM_CUSTOM_BASIC_BTN')
  656. # deal with azure openai key
  657. if is_any_api_key(AZURE_API_KEY):
  658. if is_any_api_key(API_KEY):
  659. API_KEY = API_KEY + ',' + AZURE_API_KEY
  660. else:
  661. API_KEY = AZURE_API_KEY
  662. if len(AZURE_CFG_ARRAY) > 0:
  663. for azure_model_name, azure_cfg_dict in AZURE_CFG_ARRAY.items():
  664. if not azure_model_name.startswith('azure'):
  665. raise ValueError("AZURE_CFG_ARRAY中配置的模型必须以azure开头")
  666. AZURE_API_KEY_ = azure_cfg_dict["AZURE_API_KEY"]
  667. if is_any_api_key(AZURE_API_KEY_):
  668. if is_any_api_key(API_KEY):
  669. API_KEY = API_KEY + ',' + AZURE_API_KEY_
  670. else:
  671. API_KEY = AZURE_API_KEY_
  672. customize_fn_overwrite_ = {}
  673. for k in range(NUM_CUSTOM_BASIC_BTN):
  674. customize_fn_overwrite_.update({
  675. "自定义按钮" + str(k+1):{
  676. "Title": r"",
  677. "Prefix": r"请在自定义菜单中定义提示词前缀.",
  678. "Suffix": r"请在自定义菜单中定义提示词后缀",
  679. }
  680. })
  681. return {'api_key': API_KEY, 'llm_model': LLM_MODEL, 'customize_fn_overwrite': customize_fn_overwrite_}
  682. def is_openai_api_key(key):
  683. CUSTOM_API_KEY_PATTERN = get_conf('CUSTOM_API_KEY_PATTERN')
  684. if len(CUSTOM_API_KEY_PATTERN) != 0:
  685. API_MATCH_ORIGINAL = re.match(CUSTOM_API_KEY_PATTERN, key)
  686. else:
  687. API_MATCH_ORIGINAL = re.match(r"sk-[a-zA-Z0-9]{48}$", key)
  688. return bool(API_MATCH_ORIGINAL)
  689. def is_azure_api_key(key):
  690. API_MATCH_AZURE = re.match(r"[a-zA-Z0-9]{32}$", key)
  691. return bool(API_MATCH_AZURE)
  692. def is_api2d_key(key):
  693. API_MATCH_API2D = re.match(r"fk[a-zA-Z0-9]{6}-[a-zA-Z0-9]{32}$", key)
  694. return bool(API_MATCH_API2D)
  695. def is_any_api_key(key):
  696. if ',' in key:
  697. keys = key.split(',')
  698. for k in keys:
  699. if is_any_api_key(k): return True
  700. return False
  701. else:
  702. return is_openai_api_key(key) or is_api2d_key(key) or is_azure_api_key(key)
  703. def what_keys(keys):
  704. avail_key_list = {'OpenAI Key': 0, "Azure Key": 0, "API2D Key": 0}
  705. key_list = keys.split(',')
  706. for k in key_list:
  707. if is_openai_api_key(k):
  708. avail_key_list['OpenAI Key'] += 1
  709. for k in key_list:
  710. if is_api2d_key(k):
  711. avail_key_list['API2D Key'] += 1
  712. for k in key_list:
  713. if is_azure_api_key(k):
  714. avail_key_list['Azure Key'] += 1
  715. return f"检测到: OpenAI Key {avail_key_list['OpenAI Key']} 个, Azure Key {avail_key_list['Azure Key']} 个, API2D Key {avail_key_list['API2D Key']} 个"
  716. def select_api_key(keys, llm_model):
  717. import random
  718. avail_key_list = []
  719. key_list = keys.split(',')
  720. if llm_model.startswith('gpt-'):
  721. for k in key_list:
  722. if is_openai_api_key(k): avail_key_list.append(k)
  723. if llm_model.startswith('api2d-'):
  724. for k in key_list:
  725. if is_api2d_key(k): avail_key_list.append(k)
  726. if llm_model.startswith('azure-'):
  727. for k in key_list:
  728. if is_azure_api_key(k): avail_key_list.append(k)
  729. if len(avail_key_list) == 0:
  730. raise RuntimeError(f"您提供的api-key不满足要求,不包含任何可用于{llm_model}的api-key。您可能选择了错误的模型或请求源(右下角更换模型菜单中可切换openai,azure,claude,api2d等请求源)。")
  731. api_key = random.choice(avail_key_list) # 随机负载均衡
  732. return api_key
  733. def read_env_variable(arg, default_value):
  734. """
  735. 环境变量可以是 `GPT_ACADEMIC_CONFIG`(优先),也可以直接是`CONFIG`
  736. 例如在windows cmd中,既可以写:
  737. set USE_PROXY=True
  738. set API_KEY=sk-j7caBpkRoxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  739. set proxies={"http":"http://127.0.0.1:10085", "https":"http://127.0.0.1:10085",}
  740. set AVAIL_LLM_MODELS=["gpt-3.5-turbo", "chatglm"]
  741. set AUTHENTICATION=[("username", "password"), ("username2", "password2")]
  742. 也可以写:
  743. set GPT_ACADEMIC_USE_PROXY=True
  744. set GPT_ACADEMIC_API_KEY=sk-j7caBpkRoxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  745. set GPT_ACADEMIC_proxies={"http":"http://127.0.0.1:10085", "https":"http://127.0.0.1:10085",}
  746. set GPT_ACADEMIC_AVAIL_LLM_MODELS=["gpt-3.5-turbo", "chatglm"]
  747. set GPT_ACADEMIC_AUTHENTICATION=[("username", "password"), ("username2", "password2")]
  748. """
  749. from colorful import print亮红, print亮绿
  750. arg_with_prefix = "GPT_ACADEMIC_" + arg
  751. if arg_with_prefix in os.environ:
  752. env_arg = os.environ[arg_with_prefix]
  753. elif arg in os.environ:
  754. env_arg = os.environ[arg]
  755. else:
  756. raise KeyError
  757. print(f"[ENV_VAR] 尝试加载{arg},默认值:{default_value} --> 修正值:{env_arg}")
  758. try:
  759. if isinstance(default_value, bool):
  760. env_arg = env_arg.strip()
  761. if env_arg == 'True': r = True
  762. elif env_arg == 'False': r = False
  763. else: print('Enter True or False, but have:', env_arg); r = default_value
  764. elif isinstance(default_value, int):
  765. r = int(env_arg)
  766. elif isinstance(default_value, float):
  767. r = float(env_arg)
  768. elif isinstance(default_value, str):
  769. r = env_arg.strip()
  770. elif isinstance(default_value, dict):
  771. r = eval(env_arg)
  772. elif isinstance(default_value, list):
  773. r = eval(env_arg)
  774. elif default_value is None:
  775. assert arg == "proxies"
  776. r = eval(env_arg)
  777. else:
  778. print亮红(f"[ENV_VAR] 环境变量{arg}不支持通过环境变量设置! ")
  779. raise KeyError
  780. except:
  781. print亮红(f"[ENV_VAR] 环境变量{arg}加载失败! ")
  782. raise KeyError(f"[ENV_VAR] 环境变量{arg}加载失败! ")
  783. print亮绿(f"[ENV_VAR] 成功读取环境变量{arg}")
  784. return r
  785. @lru_cache(maxsize=128)
  786. def read_single_conf_with_lru_cache(arg):
  787. from colorful import print亮红, print亮绿, print亮蓝
  788. try:
  789. # 优先级1. 获取环境变量作为配置
  790. default_ref = getattr(importlib.import_module('config'), arg) # 读取默认值作为数据类型转换的参考
  791. r = read_env_variable(arg, default_ref)
  792. except:
  793. try:
  794. # 优先级2. 获取config_private中的配置
  795. r = getattr(importlib.import_module('config_private'), arg)
  796. except:
  797. # 优先级3. 获取config中的配置
  798. r = getattr(importlib.import_module('config'), arg)
  799. # 在读取API_KEY时,检查一下是不是忘了改config
  800. if arg == 'API_URL_REDIRECT':
  801. oai_rd = r.get("https://api.openai.com/v1/chat/completions", None) # API_URL_REDIRECT填写格式是错误的,请阅读`https://github.com/binary-husky/gpt_academic/wiki/项目配置说明`
  802. if oai_rd and not oai_rd.endswith('/completions'):
  803. print亮红("\n\n[API_URL_REDIRECT] API_URL_REDIRECT填错了。请阅读`https://github.com/binary-husky/gpt_academic/wiki/项目配置说明`。如果您确信自己没填错,无视此消息即可。")
  804. time.sleep(5)
  805. if arg == 'API_KEY':
  806. print亮蓝(f"[API_KEY] 本项目现已支持OpenAI和Azure的api-key。也支持同时填写多个api-key,如API_KEY=\"openai-key1,openai-key2,azure-key3\"")
  807. print亮蓝(f"[API_KEY] 您既可以在config.py中修改api-key(s),也可以在问题输入区输入临时的api-key(s),然后回车键提交后即可生效。")
  808. if is_any_api_key(r):
  809. print亮绿(f"[API_KEY] 您的 API_KEY 是: {r[:15]}*** API_KEY 导入成功")
  810. else:
  811. print亮红("[API_KEY] 您的 API_KEY 不满足任何一种已知的密钥格式,请在config文件中修改API密钥之后再运行。")
  812. if arg == 'proxies':
  813. if not read_single_conf_with_lru_cache('USE_PROXY'): r = None # 检查USE_PROXY,防止proxies单独起作用
  814. if r is None:
  815. print亮红('[PROXY] 网络代理状态:未配置。无代理状态下很可能无法访问OpenAI家族的模型。建议:检查USE_PROXY选项是否修改。')
  816. else:
  817. print亮绿('[PROXY] 网络代理状态:已配置。配置信息如下:', r)
  818. assert isinstance(r, dict), 'proxies格式错误,请注意proxies选项的格式,不要遗漏括号。'
  819. return r
  820. @lru_cache(maxsize=128)
  821. def get_conf(*args):
  822. """
  823. 本项目的所有配置都集中在config.py中。 修改配置有三种方法,您只需要选择其中一种即可:
  824. - 直接修改config.py
  825. - 创建并修改config_private.py
  826. - 修改环境变量(修改docker-compose.yml等价于修改容器内部的环境变量)
  827. 注意:如果您使用docker-compose部署,请修改docker-compose(等价于修改容器内部的环境变量)
  828. """
  829. res = []
  830. for arg in args:
  831. r = read_single_conf_with_lru_cache(arg)
  832. res.append(r)
  833. if len(res) == 1: return res[0]
  834. return res
  835. def clear_line_break(txt):
  836. txt = txt.replace('\n', ' ')
  837. txt = txt.replace(' ', ' ')
  838. txt = txt.replace(' ', ' ')
  839. return txt
  840. class DummyWith():
  841. """
  842. 这段代码定义了一个名为DummyWith的空上下文管理器,
  843. 它的作用是……额……就是不起作用,即在代码结构不变得情况下取代其他的上下文管理器。
  844. 上下文管理器是一种Python对象,用于与with语句一起使用,
  845. 以确保一些资源在代码块执行期间得到正确的初始化和清理。
  846. 上下文管理器必须实现两个方法,分别为 __enter__()和 __exit__()。
  847. 在上下文执行开始的情况下,__enter__()方法会在代码块被执行前被调用,
  848. 而在上下文执行结束时,__exit__()方法则会被调用。
  849. """
  850. def __enter__(self):
  851. return self
  852. def __exit__(self, exc_type, exc_value, traceback):
  853. return
  854. def run_gradio_in_subpath(demo, auth, port, custom_path):
  855. """
  856. 把gradio的运行地址更改到指定的二次路径上
  857. """
  858. def is_path_legal(path: str) -> bool:
  859. '''
  860. check path for sub url
  861. path: path to check
  862. return value: do sub url wrap
  863. '''
  864. if path == "/": return True
  865. if len(path) == 0:
  866. print("ilegal custom path: {}\npath must not be empty\ndeploy on root url".format(path))
  867. return False
  868. if path[0] == '/':
  869. if path[1] != '/':
  870. print("deploy on sub-path {}".format(path))
  871. return True
  872. return False
  873. print("ilegal custom path: {}\npath should begin with \'/\'\ndeploy on root url".format(path))
  874. return False
  875. if not is_path_legal(custom_path): raise RuntimeError('Ilegal custom path')
  876. import uvicorn
  877. import gradio as gr
  878. from fastapi import FastAPI
  879. app = FastAPI()
  880. if custom_path != "/":
  881. @app.get("/")
  882. def read_main():
  883. return {"message": f"Gradio is running at: {custom_path}"}
  884. app = gr.mount_gradio_app(app, demo, path=custom_path)
  885. uvicorn.run(app, host="0.0.0.0", port=port) # , auth=auth
  886. def clip_history(inputs, history, tokenizer, max_token_limit):
  887. """
  888. reduce the length of history by clipping.
  889. this function search for the longest entries to clip, little by little,
  890. until the number of token of history is reduced under threshold.
  891. 通过裁剪来缩短历史记录的长度。
  892. 此函数逐渐地搜索最长的条目进行剪辑,
  893. 直到历史记录的标记数量降低到阈值以下。
  894. """
  895. import numpy as np
  896. from request_llms.bridge_all import model_info
  897. def get_token_num(txt):
  898. return len(tokenizer.encode(txt, disallowed_special=()))
  899. input_token_num = get_token_num(inputs)
  900. if max_token_limit < 5000: output_token_expect = 256 # 4k & 2k models
  901. elif max_token_limit < 9000: output_token_expect = 512 # 8k models
  902. else: output_token_expect = 1024 # 16k & 32k models
  903. if input_token_num < max_token_limit * 3 / 4:
  904. # 当输入部分的token占比小于限制的3/4时,裁剪时
  905. # 1. 把input的余量留出来
  906. max_token_limit = max_token_limit - input_token_num
  907. # 2. 把输出用的余量留出来
  908. max_token_limit = max_token_limit - output_token_expect
  909. # 3. 如果余量太小了,直接清除历史
  910. if max_token_limit < output_token_expect:
  911. history = []
  912. return history
  913. else:
  914. # 当输入部分的token占比 > 限制的3/4时,直接清除历史
  915. history = []
  916. return history
  917. everything = ['']
  918. everything.extend(history)
  919. n_token = get_token_num('\n'.join(everything))
  920. everything_token = [get_token_num(e) for e in everything]
  921. # 截断时的颗粒度
  922. delta = max(everything_token) // 16
  923. while n_token > max_token_limit:
  924. where = np.argmax(everything_token)
  925. encoded = tokenizer.encode(everything[where], disallowed_special=())
  926. clipped_encoded = encoded[:len(encoded) - delta]
  927. everything[where] = tokenizer.decode(clipped_encoded)[:-1] # -1 to remove the may-be illegal char
  928. everything_token[where] = get_token_num(everything[where])
  929. n_token = get_token_num('\n'.join(everything))
  930. history = everything[1:]
  931. return history
  932. """
  933. ========================================================================
  934. 第三部分
  935. 其他小工具:
  936. - zip_folder: 把某个路径下所有文件压缩,然后转移到指定的另一个路径中(gpt写的)
  937. - gen_time_str: 生成时间戳
  938. - ProxyNetworkActivate: 临时地启动代理网络(如果有)
  939. - objdump/objload: 快捷的调试函数
  940. ========================================================================
  941. """
  942. def zip_folder(source_folder, dest_folder, zip_name):
  943. import zipfile
  944. import os
  945. # Make sure the source folder exists
  946. if not os.path.exists(source_folder):
  947. print(f"{source_folder} does not exist")
  948. return
  949. # Make sure the destination folder exists
  950. if not os.path.exists(dest_folder):
  951. print(f"{dest_folder} does not exist")
  952. return
  953. # Create the name for the zip file
  954. zip_file = pj(dest_folder, zip_name)
  955. # Create a ZipFile object
  956. with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
  957. # Walk through the source folder and add files to the zip file
  958. for foldername, subfolders, filenames in os.walk(source_folder):
  959. for filename in filenames:
  960. filepath = pj(foldername, filename)
  961. zipf.write(filepath, arcname=os.path.relpath(filepath, source_folder))
  962. # Move the zip file to the destination folder (if it wasn't already there)
  963. if os.path.dirname(zip_file) != dest_folder:
  964. os.rename(zip_file, pj(dest_folder, os.path.basename(zip_file)))
  965. zip_file = pj(dest_folder, os.path.basename(zip_file))
  966. print(f"Zip file created at {zip_file}")
  967. def zip_result(folder):
  968. t = gen_time_str()
  969. zip_folder(folder, get_log_folder(), f'{t}-result.zip')
  970. return pj(get_log_folder(), f'{t}-result.zip')
  971. def gen_time_str():
  972. import time
  973. return time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
  974. def get_log_folder(user=default_user_name, plugin_name='shared'):
  975. if user is None: user = default_user_name
  976. PATH_LOGGING = get_conf('PATH_LOGGING')
  977. if plugin_name is None:
  978. _dir = pj(PATH_LOGGING, user)
  979. else:
  980. _dir = pj(PATH_LOGGING, user, plugin_name)
  981. if not os.path.exists(_dir): os.makedirs(_dir)
  982. return _dir
  983. def get_upload_folder(user=default_user_name, tag=None):
  984. PATH_PRIVATE_UPLOAD = get_conf('PATH_PRIVATE_UPLOAD')
  985. if user is None: user = default_user_name
  986. if tag is None or len(tag) == 0:
  987. target_path_base = pj(PATH_PRIVATE_UPLOAD, user)
  988. else:
  989. target_path_base = pj(PATH_PRIVATE_UPLOAD, user, tag)
  990. return target_path_base
  991. def is_the_upload_folder(string):
  992. PATH_PRIVATE_UPLOAD = get_conf('PATH_PRIVATE_UPLOAD')
  993. pattern = r'^PATH_PRIVATE_UPLOAD[\\/][A-Za-z0-9_-]+[\\/]\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}$'
  994. pattern = pattern.replace('PATH_PRIVATE_UPLOAD', PATH_PRIVATE_UPLOAD)
  995. if re.match(pattern, string):
  996. return True
  997. else:
  998. return False
  999. def get_user(chatbotwithcookies):
  1000. return chatbotwithcookies._cookies.get('user_name', default_user_name)
  1001. class ProxyNetworkActivate():
  1002. """
  1003. 这段代码定义了一个名为ProxyNetworkActivate的空上下文管理器, 用于给一小段代码上代理
  1004. """
  1005. def __init__(self, task=None) -> None:
  1006. self.task = task
  1007. if not task:
  1008. # 不给定task, 那么我们默认代理生效
  1009. self.valid = True
  1010. else:
  1011. # 给定了task, 我们检查一下
  1012. from toolbox import get_conf
  1013. WHEN_TO_USE_PROXY = get_conf('WHEN_TO_USE_PROXY')
  1014. self.valid = (task in WHEN_TO_USE_PROXY)
  1015. def __enter__(self):
  1016. if not self.valid: return self
  1017. from toolbox import get_conf
  1018. proxies = get_conf('proxies')
  1019. if 'no_proxy' in os.environ: os.environ.pop('no_proxy')
  1020. if proxies is not None:
  1021. if 'http' in proxies: os.environ['HTTP_PROXY'] = proxies['http']
  1022. if 'https' in proxies: os.environ['HTTPS_PROXY'] = proxies['https']
  1023. return self
  1024. def __exit__(self, exc_type, exc_value, traceback):
  1025. os.environ['no_proxy'] = '*'
  1026. if 'HTTP_PROXY' in os.environ: os.environ.pop('HTTP_PROXY')
  1027. if 'HTTPS_PROXY' in os.environ: os.environ.pop('HTTPS_PROXY')
  1028. return
  1029. def objdump(obj, file='objdump.tmp'):
  1030. import pickle
  1031. with open(file, 'wb+') as f:
  1032. pickle.dump(obj, f)
  1033. return
  1034. def objload(file='objdump.tmp'):
  1035. import pickle, os
  1036. if not os.path.exists(file):
  1037. return
  1038. with open(file, 'rb') as f:
  1039. return pickle.load(f)
  1040. def Singleton(cls):
  1041. """
  1042. 一个单实例装饰器
  1043. """
  1044. _instance = {}
  1045. def _singleton(*args, **kargs):
  1046. if cls not in _instance:
  1047. _instance[cls] = cls(*args, **kargs)
  1048. return _instance[cls]
  1049. return _singleton
  1050. """
  1051. ========================================================================
  1052. 第四部分
  1053. 接驳void-terminal:
  1054. - set_conf: 在运行过程中动态地修改配置
  1055. - set_multi_conf: 在运行过程中动态地修改多个配置
  1056. - get_plugin_handle: 获取插件的句柄
  1057. - get_plugin_default_kwargs: 获取插件的默认参数
  1058. - get_chat_handle: 获取简单聊天的句柄
  1059. - get_chat_default_kwargs: 获取简单聊天的默认参数
  1060. ========================================================================
  1061. """
  1062. def set_conf(key, value):
  1063. from toolbox import read_single_conf_with_lru_cache, get_conf
  1064. read_single_conf_with_lru_cache.cache_clear()
  1065. get_conf.cache_clear()
  1066. os.environ[key] = str(value)
  1067. altered = get_conf(key)
  1068. return altered
  1069. def set_multi_conf(dic):
  1070. for k, v in dic.items(): set_conf(k, v)
  1071. return
  1072. def get_plugin_handle(plugin_name):
  1073. """
  1074. e.g. plugin_name = 'crazy_functions.批量Markdown翻译->Markdown翻译指定语言'
  1075. """
  1076. import importlib
  1077. assert '->' in plugin_name, \
  1078. "Example of plugin_name: crazy_functions.批量Markdown翻译->Markdown翻译指定语言"
  1079. module, fn_name = plugin_name.split('->')
  1080. f_hot_reload = getattr(importlib.import_module(module, fn_name), fn_name)
  1081. return f_hot_reload
  1082. def get_chat_handle():
  1083. """
  1084. """
  1085. from request_llms.bridge_all import predict_no_ui_long_connection
  1086. return predict_no_ui_long_connection
  1087. def get_plugin_default_kwargs():
  1088. """
  1089. """
  1090. from toolbox import ChatBotWithCookies
  1091. cookies = load_chat_cookies()
  1092. llm_kwargs = {
  1093. 'api_key': cookies['api_key'],
  1094. 'llm_model': cookies['llm_model'],
  1095. 'top_p': 1.0,
  1096. 'max_length': None,
  1097. 'temperature': 1.0,
  1098. }
  1099. chatbot = ChatBotWithCookies(llm_kwargs)
  1100. # txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port
  1101. DEFAULT_FN_GROUPS_kwargs = {
  1102. "main_input": "./README.md",
  1103. "llm_kwargs": llm_kwargs,
  1104. "plugin_kwargs": {},
  1105. "chatbot_with_cookie": chatbot,
  1106. "history": [],
  1107. "system_prompt": "You are a good AI.",
  1108. "web_port": None
  1109. }
  1110. return DEFAULT_FN_GROUPS_kwargs
  1111. def get_chat_default_kwargs():
  1112. """
  1113. """
  1114. cookies = load_chat_cookies()
  1115. llm_kwargs = {
  1116. 'api_key': cookies['api_key'],
  1117. 'llm_model': cookies['llm_model'],
  1118. 'top_p': 1.0,
  1119. 'max_length': None,
  1120. 'temperature': 1.0,
  1121. }
  1122. default_chat_kwargs = {
  1123. "inputs": "Hello there, are you ready?",
  1124. "llm_kwargs": llm_kwargs,
  1125. "history": [],
  1126. "sys_prompt": "You are AI assistant",
  1127. "observe_window": None,
  1128. "console_slience": False,
  1129. }
  1130. return default_chat_kwargs
  1131. def get_pictures_list(path):
  1132. file_manifest = [f for f in glob.glob(f'{path}/**/*.jpg', recursive=True)]
  1133. file_manifest += [f for f in glob.glob(f'{path}/**/*.jpeg', recursive=True)]
  1134. file_manifest += [f for f in glob.glob(f'{path}/**/*.png', recursive=True)]
  1135. return file_manifest
  1136. def have_any_recent_upload_image_files(chatbot):
  1137. _5min = 5 * 60
  1138. if chatbot is None: return False, None # chatbot is None
  1139. most_recent_uploaded = chatbot._cookies.get("most_recent_uploaded", None)
  1140. if not most_recent_uploaded: return False, None # most_recent_uploaded is None
  1141. if time.time() - most_recent_uploaded["time"] < _5min:
  1142. most_recent_uploaded = chatbot._cookies.get("most_recent_uploaded", None)
  1143. path = most_recent_uploaded['path']
  1144. file_manifest = get_pictures_list(path)
  1145. if len(file_manifest) == 0: return False, None
  1146. return True, file_manifest # most_recent_uploaded is new
  1147. else:
  1148. return False, None # most_recent_uploaded is too old
  1149. # Function to encode the image
  1150. def encode_image(image_path):
  1151. with open(image_path, "rb") as image_file:
  1152. return base64.b64encode(image_file.read()).decode('utf-8')
  1153. def get_max_token(llm_kwargs):
  1154. from request_llms.bridge_all import model_info
  1155. return model_info[llm_kwargs['llm_model']]['max_token']
  1156. def check_packages(packages=[]):
  1157. import importlib.util
  1158. for p in packages:
  1159. spam_spec = importlib.util.find_spec(p)
  1160. if spam_spec is None: raise ModuleNotFoundError