check_proxy.py 8.0 KB

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