MaktubCN commited on
Commit
112b614
1 Parent(s): abed758

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -121
app.py CHANGED
@@ -1,5 +1,4 @@
1
- import os
2
- os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
3
 
4
  help_menu_description = \
5
  """Github源代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),
@@ -16,86 +15,72 @@ help_menu_description = \
16
 
17
  def main():
18
  import subprocess, sys
19
- import logging, uuid, traceback
20
-
21
- try:
22
- # 安装指定版本的 Gradio
23
- subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://public.agent-matrix.com/publish/gradio-3.32.8-py3-none-any.whl'])
24
- import gradio as gr
25
- print(f"Gradio version: {gr.__version__}")
26
- if gr.__version__ not in ['3.32.8']:
27
- raise ModuleNotFoundError("使用项目内置Gradio获取最优体验! 请运行 `pip install -r requirements.txt` 指令安装内置Gradio及其他依赖, 详情信息见requirements.txt.")
28
-
29
- from request_llms.bridge_all import predict
30
- from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith
31
-
32
- # 获取配置
33
- proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')
34
- CHATBOT_HEIGHT, LAYOUT, AVAIL_LLM_MODELS, AUTO_CLEAR_TXT = get_conf('CHATBOT_HEIGHT', 'LAYOUT', 'AVAIL_LLM_MODELS', 'AUTO_CLEAR_TXT')
35
- ENABLE_AUDIO, AUTO_CLEAR_TXT, PATH_LOGGING, AVAIL_THEMES, THEME, ADD_WAIFU = get_conf('ENABLE_AUDIO', 'AUTO_CLEAR_TXT', 'PATH_LOGGING', 'AVAIL_THEMES', 'THEME', 'ADD_WAIFU')
36
- DARK_MODE, NUM_CUSTOM_BASIC_BTN, SSL_KEYFILE, SSL_CERTFILE = get_conf('DARK_MODE', 'NUM_CUSTOM_BASIC_BTN', 'SSL_KEYFILE', 'SSL_CERTFILE')
37
- INIT_SYS_PROMPT = get_conf('INIT_SYS_PROMPT')
38
-
39
- # 如果WEB_PORT是-1, 则随机选取WEB端口
40
- PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
41
- from check_proxy import get_current_version
42
- from themes.theme import adjust_theme, advanced_css, theme_declaration, js_code_clear, js_code_reset, js_code_show_or_hide, js_code_show_or_hide_group2
43
- from themes.theme import js_code_for_css_changing, js_code_for_toggle_darkmode, js_code_for_persistent_cookie_init
44
- from themes.theme import load_dynamic_theme, to_cookie_str, from_cookie_str, init_cookie
45
- title_html = f"<h1 align=\"center\">GPT 学术优化 {get_current_version()}</h1>{theme_declaration}"
46
-
47
- # 问询记录, python 版本建议3.9+(越新越好)
48
- os.makedirs(PATH_LOGGING, exist_ok=True)
49
- try:
50
- logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, encoding="utf-8",
51
- format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
52
- except:
53
- logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO,
54
- format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
55
- # Disable logging output from the 'httpx' logger
56
- logging.getLogger("httpx").setLevel(logging.WARNING)
57
- print(f"所有问询记录将自动保存在本地目录./{PATH_LOGGING}/chat_secrets.log, 请注意自我隐私保护哦!")
58
-
59
- # 一些普通功能模块
60
- from core_functional import get_core_functions
61
- functional = get_core_functions()
62
-
63
- # 高级函数插件
64
- from crazy_functional import get_crazy_functions
65
- DEFAULT_FN_GROUPS = get_conf('DEFAULT_FN_GROUPS')
66
- plugins = get_crazy_functions()
67
- all_plugin_groups = list(set([g for _, plugin in plugins.items() for g in plugin['Group'].split('|')]))
68
- match_group = lambda tags, groups: any([g in groups for g in tags.split('|')])
69
-
70
- # 处理markdown文本格式的转变
71
- gr.Chatbot.postprocess = format_io
72
-
73
- # 做一些外观色彩上的调整
74
- set_theme = adjust_theme()
75
-
76
- # 代理与自动更新
77
- from check_proxy import check_proxy, auto_update, warm_up_modules
78
- proxy_info = check_proxy(proxies)
79
-
80
- gr_L1 = lambda: gr.Row().style()
81
- gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id, min_width=400)
82
- if LAYOUT == "TOP-DOWN":
83
- gr_L1 = lambda: DummyWith()
84
- gr_L2 = lambda scale, elem_id: gr.Row()
85
- CHATBOT_HEIGHT /= 2
86
-
87
- cancel_handles = []
88
- customize_btns = {}
89
- predefined_btns = {}
90
- with gr.Blocks(title="GPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
91
- gr.HTML(title_html)
92
- gr.HTML('''<center><a href="https://huggingface.co/spaces/qingxu98/gpt-academic?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>请您打开此页面后务必点击上方的“复制空间”(Duplicate Space)按钮!<font color="#FF00FF">使用时,先在输入框填���API-KEY然后回车键提交。</font><br/>切忌在“复制空间”(Duplicate Space)之前填入API_KEY或进行提问,否则您的API_KEY将极可能被空间所有者攫取!<br/>支持任意数量的OpenAI密钥和API2D密钥共存,例如输入"openai-key1,api2d-key2",然后提交,即可同时使用两种模型接口。</center>''')
93
- secret_css, dark_mode, py_pickle_cookie = gr.Textbox(visible=False), gr.Textbox(DARK_MODE, visible=False), gr.Textbox(visible=False)
94
- cookies = gr.State(load_chat_cookies())
95
-
96
- # 添加一个隐藏的 Textbox 用于存储 URL 参数
97
- url_params = gr.Textbox(label="URL Parameters", visible=False)
98
-
99
  with gr_L1():
100
  with gr_L2(scale=2, elem_id="gpt-chat"):
101
  chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}", elem_id="gpt-chatbot")
@@ -395,45 +380,33 @@ def main():
395
  demo.load(None, inputs=[dark_mode], outputs=None, _js="""(dark_mode)=>{apply_cookie_for_checkbox(dark_mode);}""") # 配置暗色主题或亮色主题
396
  demo.load(None, inputs=[gr.Textbox(LAYOUT, visible=False)], outputs=None, _js='(LAYOUT)=>{GptAcademicJavaScriptInit(LAYOUT);}')
397
 
398
- # 启动 Gradio 的延迟任务
399
- def run_delayed_tasks():
400
- import threading, webbrowser, time
401
- print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
402
- if DARK_MODE:
403
- print(f"\t「暗色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
404
- else:
405
- print(f"\t「亮色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
406
-
407
- def auto_updates():
408
- time.sleep(0)
409
- auto_update()
410
- def open_browser():
411
- time.sleep(2)
412
- webbrowser.open_new_tab(f"http://localhost:{PORT}")
413
- def warm_up_mods():
414
- time.sleep(6)
415
- warm_up_modules()
416
-
417
- threading.Thread(target=auto_updates, name="self-upgrade", daemon=True).start() # 查看自动更新
418
- threading.Thread(target=open_browser, name="open-browser", daemon=True).start() # 打开浏览器页面
419
- threading.Thread(target=warm_up_mods, name="warm-up", daemon=True).start() # 预热tiktoken模块
420
-
421
- run_delayed_tasks()
422
- demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=False, favicon_path="docs/logo.png", blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile"])
423
-
424
- # 如果需要在二级路径下运行
425
- # CUSTOM_PATH = get_conf('CUSTOM_PATH')
426
- # if CUSTOM_PATH != "/":
427
- # from toolbox import run_gradio_in_subpath
428
- # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH)
429
- # else:
430
- # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png",
431
- # blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile",f"{PATH_LOGGING}/admin"])
432
-
433
- except Exception as e:
434
- print("Unhandled exception during application startup:")
435
- traceback.print_exc()
436
- sys.exit(1)
437
 
438
  if __name__ == "__main__":
439
  main()
 
1
+ import os; os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
 
2
 
3
  help_menu_description = \
4
  """Github源代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),
 
15
 
16
  def main():
17
  import subprocess, sys
18
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://public.agent-matrix.com/publish/gradio-3.32.8-py3-none-any.whl'])
19
+ import gradio as gr
20
+ if gr.__version__ not in ['3.32.8']:
21
+ raise ModuleNotFoundError("使用项目内置Gradio获取最优体验! 请运行 `pip install -r requirements.txt` 指令安装内置Gradio及其他依赖, 详情信息见requirements.txt.")
22
+ from request_llms.bridge_all import predict
23
+ from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith
24
+ # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址
25
+ proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION = get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION')
26
+ CHATBOT_HEIGHT, LAYOUT, AVAIL_LLM_MODELS, AUTO_CLEAR_TXT = get_conf('CHATBOT_HEIGHT', 'LAYOUT', 'AVAIL_LLM_MODELS', 'AUTO_CLEAR_TXT')
27
+ ENABLE_AUDIO, AUTO_CLEAR_TXT, PATH_LOGGING, AVAIL_THEMES, THEME, ADD_WAIFU = get_conf('ENABLE_AUDIO', 'AUTO_CLEAR_TXT', 'PATH_LOGGING', 'AVAIL_THEMES', 'THEME', 'ADD_WAIFU')
28
+ DARK_MODE, NUM_CUSTOM_BASIC_BTN, SSL_KEYFILE, SSL_CERTFILE = get_conf('DARK_MODE', 'NUM_CUSTOM_BASIC_BTN', 'SSL_KEYFILE', 'SSL_CERTFILE')
29
+ INIT_SYS_PROMPT = get_conf('INIT_SYS_PROMPT')
30
+
31
+ # 如果WEB_PORT是-1, 则随机选取WEB端口
32
+ PORT = find_free_port() if WEB_PORT <= 0 else WEB_PORT
33
+ from check_proxy import get_current_version
34
+ from themes.theme import adjust_theme, advanced_css, theme_declaration, js_code_clear, js_code_reset, js_code_show_or_hide, js_code_show_or_hide_group2
35
+ from themes.theme import js_code_for_css_changing, js_code_for_toggle_darkmode, js_code_for_persistent_cookie_init
36
+ from themes.theme import load_dynamic_theme, to_cookie_str, from_cookie_str, init_cookie
37
+ title_html = f"<h1 align=\"center\">GPT 学术优化 {get_current_version()}</h1>{theme_declaration}"
38
+
39
+ # 问询记录, python 版本建议3.9+(越新越好)
40
+ import logging, uuid
41
+ os.makedirs(PATH_LOGGING, exist_ok=True)
42
+ try:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, encoding="utf-8", format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
43
+ except:logging.basicConfig(filename=f"{PATH_LOGGING}/chat_secrets.log", level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
44
+ # Disable logging output from the 'httpx' logger
45
+ logging.getLogger("httpx").setLevel(logging.WARNING)
46
+ print(f"所有问询记录将自动保存在本地目录./{PATH_LOGGING}/chat_secrets.log, 请注意自我隐私保护哦!")
47
+
48
+ # 一些普通功能模块
49
+ from core_functional import get_core_functions
50
+ functional = get_core_functions()
51
+
52
+ # 高级函数插件
53
+ from crazy_functional import get_crazy_functions
54
+ DEFAULT_FN_GROUPS = get_conf('DEFAULT_FN_GROUPS')
55
+ plugins = get_crazy_functions()
56
+ all_plugin_groups = list(set([g for _, plugin in plugins.items() for g in plugin['Group'].split('|')]))
57
+ match_group = lambda tags, groups: any([g in groups for g in tags.split('|')])
58
+
59
+ # 处理markdown文本格式的转变
60
+ gr.Chatbot.postprocess = format_io
61
+
62
+ # 做一些外观色彩上的调整
63
+ set_theme = adjust_theme()
64
+
65
+ # 代理与自动更新
66
+ from check_proxy import check_proxy, auto_update, warm_up_modules
67
+ proxy_info = check_proxy(proxies)
68
+
69
+ gr_L1 = lambda: gr.Row().style()
70
+ gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id, min_width=400)
71
+ if LAYOUT == "TOP-DOWN":
72
+ gr_L1 = lambda: DummyWith()
73
+ gr_L2 = lambda scale, elem_id: gr.Row()
74
+ CHATBOT_HEIGHT /= 2
75
+
76
+ cancel_handles = []
77
+ customize_btns = {}
78
+ predefined_btns = {}
79
+ with gr.Blocks(title="GPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
80
+ gr.HTML(title_html)
81
+ gr.HTML('''<center><a href="https://huggingface.co/spaces/qingxu98/gpt-academic?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>请您打开此页面后务必点击上方的“复制空间”(Duplicate Space)按钮!<font color="#FF00FF">使用时,先在输入框填入API-KEY然后回车。</font><br/>切忌在“复制空间��(Duplicate Space)之前填入API_KEY或进行提问,否则您的API_KEY将极可能被空间所有者攫取!<br/>支持任意数量的OpenAI的密钥和API2D的密钥共存,例如输入"OpenAI密钥1,API2D密钥2",然后提交,即可同时使用两种模型接口。</center>''')
82
+ secret_css, dark_mode, py_pickle_cookie = gr.Textbox(visible=False), gr.Textbox(DARK_MODE, visible=False), gr.Textbox(visible=False)
83
+ cookies = gr.State(load_chat_cookies())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  with gr_L1():
85
  with gr_L2(scale=2, elem_id="gpt-chat"):
86
  chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}", elem_id="gpt-chatbot")
 
380
  demo.load(None, inputs=[dark_mode], outputs=None, _js="""(dark_mode)=>{apply_cookie_for_checkbox(dark_mode);}""") # 配置暗色主题或亮色主题
381
  demo.load(None, inputs=[gr.Textbox(LAYOUT, visible=False)], outputs=None, _js='(LAYOUT)=>{GptAcademicJavaScriptInit(LAYOUT);}')
382
 
383
+ # gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
384
+ def run_delayed_tasks():
385
+ import threading, webbrowser, time
386
+ print(f"如果浏览器没有自动打开,请复制并转到以下URL:")
387
+ if DARK_MODE: print(f"\t「暗色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
388
+ else: print(f"\t「亮色主题已启用(支持动态切换主题)」: http://localhost:{PORT}")
389
+
390
+ def auto_updates(): time.sleep(0); auto_update()
391
+ def open_browser(): time.sleep(2); webbrowser.open_new_tab(f"http://localhost:{PORT}")
392
+ def warm_up_mods(): time.sleep(6); warm_up_modules()
393
+
394
+ threading.Thread(target=auto_updates, name="self-upgrade", daemon=True).start() # 查看自动更新
395
+ threading.Thread(target=open_browser, name="open-browser", daemon=True).start() # 打开浏览器页面
396
+ threading.Thread(target=warm_up_mods, name="warm-up", daemon=True).start() # 预热tiktoken模块
397
+
398
+ run_delayed_tasks()
399
+ demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", share=False, favicon_path="docs/logo.png", blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile"])
400
+
401
+
402
+ # 如果需要在二级路径下运行
403
+ # CUSTOM_PATH = get_conf('CUSTOM_PATH')
404
+ # if CUSTOM_PATH != "/":
405
+ # from toolbox import run_gradio_in_subpath
406
+ # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH)
407
+ # else:
408
+ # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png",
409
+ # blocked_paths=["config.py","config_private.py","docker-compose.yml","Dockerfile",f"{PATH_LOGGING}/admin"])
 
 
 
 
 
 
 
 
 
 
 
 
410
 
411
  if __name__ == "__main__":
412
  main()