check_proxy.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. def check_proxy(proxies):
  2. import requests
  3. proxies_https = proxies['https'] if proxies is not None else '无'
  4. try:
  5. response = requests.get("https://ipapi.co/json/", proxies=proxies, timeout=4)
  6. data = response.json()
  7. if 'country_name' in data:
  8. country = data['country_name']
  9. result = f"代理配置 {proxies_https}, 代理所在地:{country}"
  10. elif 'error' in data:
  11. alternative = _check_with_backup_source(proxies)
  12. if alternative is None:
  13. result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限"
  14. else:
  15. result = f"代理配置 {proxies_https}, 代理所在地:{alternative}"
  16. else:
  17. result = f"代理配置 {proxies_https}, 代理数据解析失败:{data}"
  18. print(result)
  19. return result
  20. except:
  21. result = f"代理配置 {proxies_https}, 代理所在地查询超时,代理可能无效"
  22. print(result)
  23. return result
  24. def _check_with_backup_source(proxies):
  25. import random, string, requests
  26. random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=32))
  27. try: return requests.get(f"http://{random_string}.edns.ip-api.com/json", proxies=proxies, timeout=4).json()['dns']['geo']
  28. except: return None
  29. def backup_and_download(current_version, remote_version):
  30. """
  31. 一键更新协议:备份和下载
  32. """
  33. from toolbox import get_conf
  34. import shutil
  35. import os
  36. import requests
  37. import zipfile
  38. os.makedirs(f'./history', exist_ok=True)
  39. backup_dir = f'./history/backup-{current_version}/'
  40. new_version_dir = f'./history/new-version-{remote_version}/'
  41. if os.path.exists(new_version_dir):
  42. return new_version_dir
  43. os.makedirs(new_version_dir)
  44. shutil.copytree('./', backup_dir, ignore=lambda x, y: ['history'])
  45. proxies = get_conf('proxies')
  46. try: r = requests.get('https://github.com/binary-husky/chatgpt_academic/archive/refs/heads/master.zip', proxies=proxies, stream=True)
  47. except: r = requests.get('https://public.gpt-academic.top/publish/master.zip', proxies=proxies, stream=True)
  48. zip_file_path = backup_dir+'/master.zip'
  49. with open(zip_file_path, 'wb+') as f:
  50. f.write(r.content)
  51. dst_path = new_version_dir
  52. with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
  53. for zip_info in zip_ref.infolist():
  54. dst_file_path = os.path.join(dst_path, zip_info.filename)
  55. if os.path.exists(dst_file_path):
  56. os.remove(dst_file_path)
  57. zip_ref.extract(zip_info, dst_path)
  58. return new_version_dir
  59. def patch_and_restart(path):
  60. """
  61. 一键更新协议:覆盖和重启
  62. """
  63. from distutils import dir_util
  64. import shutil
  65. import os
  66. import sys
  67. import time
  68. import glob
  69. from colorful import print亮黄, print亮绿, print亮红
  70. # if not using config_private, move origin config.py as config_private.py
  71. if not os.path.exists('config_private.py'):
  72. print亮黄('由于您没有设置config_private.py私密配置,现将您的现有配置移动至config_private.py以防止配置丢失,',
  73. '另外您可以随时在history子文件夹下找回旧版的程序。')
  74. shutil.copyfile('config.py', 'config_private.py')
  75. path_new_version = glob.glob(path + '/*-master')[0]
  76. dir_util.copy_tree(path_new_version, './')
  77. print亮绿('代码已经更新,即将更新pip包依赖……')
  78. for i in reversed(range(5)): time.sleep(1); print(i)
  79. try:
  80. import subprocess
  81. subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'])
  82. except:
  83. print亮红('pip包依赖安装出现问题,需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。')
  84. print亮绿('更新完成,您可以随时在history子文件夹下找回旧版的程序,5s之后重启')
  85. print亮红('假如重启失败,您可能需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。')
  86. print(' ------------------------------ -----------------------------------')
  87. for i in reversed(range(8)): time.sleep(1); print(i)
  88. os.execl(sys.executable, sys.executable, *sys.argv)
  89. def get_current_version():
  90. import json
  91. try:
  92. with open('./version', 'r', encoding='utf8') as f:
  93. current_version = json.loads(f.read())['version']
  94. except:
  95. current_version = ""
  96. return current_version
  97. def auto_update(raise_error=False):
  98. """
  99. 一键更新协议:查询版本和用户意见
  100. """
  101. try:
  102. from toolbox import get_conf
  103. import requests
  104. import json
  105. proxies = get_conf('proxies')
  106. try: response = requests.get("https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5)
  107. except: response = requests.get("https://public.gpt-academic.top/publish/version", proxies=proxies, timeout=5)
  108. remote_json_data = json.loads(response.text)
  109. remote_version = remote_json_data['version']
  110. if remote_json_data["show_feature"]:
  111. new_feature = "新功能:" + remote_json_data["new_feature"]
  112. else:
  113. new_feature = ""
  114. with open('./version', 'r', encoding='utf8') as f:
  115. current_version = f.read()
  116. current_version = json.loads(current_version)['version']
  117. if (remote_version - current_version) >= 0.01-1e-5:
  118. from colorful import print亮黄
  119. print亮黄(f'\n新版本可用。新版本:{remote_version},当前版本:{current_version}。{new_feature}')
  120. print('(1)Github更新地址:\nhttps://github.com/binary-husky/chatgpt_academic\n')
  121. user_instruction = input('(2)是否一键更新代码(Y+回车=确认,输入其他/无输入+回车=不更新)?')
  122. if user_instruction in ['Y', 'y']:
  123. path = backup_and_download(current_version, remote_version)
  124. try:
  125. patch_and_restart(path)
  126. except:
  127. msg = '更新失败。'
  128. if raise_error:
  129. from toolbox import trimmed_format_exc
  130. msg += trimmed_format_exc()
  131. print(msg)
  132. else:
  133. print('自动更新程序:已禁用')
  134. return
  135. else:
  136. return
  137. except:
  138. msg = '自动更新程序:已禁用。建议排查:代理网络配置。'
  139. if raise_error:
  140. from toolbox import trimmed_format_exc
  141. msg += trimmed_format_exc()
  142. print(msg)
  143. def warm_up_modules():
  144. print('正在执行一些模块的预热 ...')
  145. from toolbox import ProxyNetworkActivate
  146. from request_llms.bridge_all import model_info
  147. with ProxyNetworkActivate("Warmup_Modules"):
  148. enc = model_info["gpt-3.5-turbo"]['tokenizer']
  149. enc.encode("模块预热", disallowed_special=())
  150. enc = model_info["gpt-4"]['tokenizer']
  151. enc.encode("模块预热", disallowed_special=())
  152. def warm_up_vectordb():
  153. print('正在执行一些模块的预热 ...')
  154. from toolbox import ProxyNetworkActivate
  155. with ProxyNetworkActivate("Warmup_Modules"):
  156. import nltk
  157. with ProxyNetworkActivate("Warmup_Modules"): nltk.download("punkt")
  158. if __name__ == '__main__':
  159. import os
  160. os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
  161. from toolbox import get_conf
  162. proxies = get_conf('proxies')
  163. check_proxy(proxies)