Spaces:
Paused
Paused
Upload app.py
Browse files
app.py
CHANGED
|
@@ -781,7 +781,7 @@ def build_payload(request_data, model_id):
|
|
| 781 |
|
| 782 |
return payload
|
| 783 |
|
| 784 |
-
# 修改
|
| 785 |
PROXY_API_BASE = "https://269900.xyz"
|
| 786 |
PROXY_CHECK_INTERVAL = 300 # 5分钟检查一次代理可用性
|
| 787 |
PROXY_MAX_LATENCY = 5000 # 最大延迟(毫秒)
|
|
@@ -793,43 +793,95 @@ class ProxyManager:
|
|
| 793 |
self.proxies: List[Dict[str, Union[str, int, float]]] = []
|
| 794 |
self.last_update = 0
|
| 795 |
self.lock = threading.Lock()
|
| 796 |
-
self.session = aiohttp.ClientSession()
|
| 797 |
|
| 798 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
"""异步获取代理列表"""
|
| 800 |
try:
|
| 801 |
-
# 使用基本的 fetch_all 端点
|
| 802 |
endpoint = f"{PROXY_API_BASE}/fetch_all?region=cn&count=5"
|
| 803 |
-
|
| 804 |
-
async with self.session.get(endpoint, timeout=PROXY_TIMEOUT) as response:
|
| 805 |
if response.status == 200:
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
for proxy_str in proxy_list:
|
| 815 |
-
proxy_info = self._parse_proxy_string(proxy_str)
|
| 816 |
-
if proxy_info:
|
| 817 |
-
self.proxies.append(proxy_info)
|
| 818 |
-
|
| 819 |
-
self.last_update = time.time()
|
| 820 |
-
logger.info(f"Successfully fetched {len(self.proxies)} proxies")
|
| 821 |
-
|
| 822 |
-
except Exception as e:
|
| 823 |
-
logger.error(f"Error parsing proxy response: {e}")
|
| 824 |
else:
|
| 825 |
logger.error(f"Failed to fetch proxies, status: {response.status}")
|
| 826 |
-
|
| 827 |
except Exception as e:
|
| 828 |
logger.error(f"Error in fetch_proxies: {e}")
|
| 829 |
finally:
|
| 830 |
if not self.proxies:
|
| 831 |
logger.warning("No proxies available, will retry later")
|
| 832 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 833 |
def _parse_proxy_string(self, proxy_str: str) -> Optional[Dict[str, Union[str, int, float]]]:
|
| 834 |
"""解析代理字符串"""
|
| 835 |
try:
|
|
@@ -837,7 +889,6 @@ class ProxyManager:
|
|
| 837 |
if not proxy_str:
|
| 838 |
return None
|
| 839 |
|
| 840 |
-
# 解析代理类型和地址
|
| 841 |
if proxy_str.startswith(('http://', 'https://', 'socks4://', 'socks5://')):
|
| 842 |
proxy_type = proxy_str.split('://')[0]
|
| 843 |
address = proxy_str.split('://')[1]
|
|
@@ -845,7 +896,6 @@ class ProxyManager:
|
|
| 845 |
proxy_type = 'http'
|
| 846 |
address = proxy_str
|
| 847 |
|
| 848 |
-
# 解析IP和端口
|
| 849 |
if ':' in address:
|
| 850 |
ip, port = address.split(':')
|
| 851 |
port = int(port)
|
|
@@ -865,52 +915,6 @@ class ProxyManager:
|
|
| 865 |
logger.error(f"Error parsing proxy string '{proxy_str}': {e}")
|
| 866 |
return None
|
| 867 |
|
| 868 |
-
def get_proxy(self) -> Optional[str]:
|
| 869 |
-
"""获取一个可用的代理"""
|
| 870 |
-
with self.lock:
|
| 871 |
-
current_time = time.time()
|
| 872 |
-
|
| 873 |
-
if not self.proxies or (current_time - self.last_update) > PROXY_CHECK_INTERVAL:
|
| 874 |
-
# 使用异步事件循环
|
| 875 |
-
loop = asyncio.new_event_loop()
|
| 876 |
-
asyncio.set_event_loop(loop)
|
| 877 |
-
try:
|
| 878 |
-
loop.run_until_complete(self.fetch_proxies())
|
| 879 |
-
except Exception as e:
|
| 880 |
-
logger.error(f"Error updating proxies: {e}")
|
| 881 |
-
finally:
|
| 882 |
-
loop.close()
|
| 883 |
-
|
| 884 |
-
if not self.proxies:
|
| 885 |
-
return None
|
| 886 |
-
|
| 887 |
-
# 选择失败次数最少且最近最少使用的代理
|
| 888 |
-
valid_proxies = [p for p in self.proxies if p['fails'] < 3]
|
| 889 |
-
if not valid_proxies:
|
| 890 |
-
return None
|
| 891 |
-
|
| 892 |
-
proxy = min(valid_proxies, key=lambda x: (x['fails'], x['last_use']))
|
| 893 |
-
proxy['last_use'] = current_time
|
| 894 |
-
|
| 895 |
-
# 返回格式化的代理URL
|
| 896 |
-
return proxy['url']
|
| 897 |
-
|
| 898 |
-
async def check_proxy(self, proxy_url: str) -> bool:
|
| 899 |
-
"""检查代理是否可用"""
|
| 900 |
-
try:
|
| 901 |
-
async with self.session.get(
|
| 902 |
-
'https://www.google.com',
|
| 903 |
-
proxy=proxy_url,
|
| 904 |
-
timeout=PROXY_TIMEOUT
|
| 905 |
-
) as response:
|
| 906 |
-
return response.status == 200
|
| 907 |
-
except Exception:
|
| 908 |
-
return False
|
| 909 |
-
|
| 910 |
-
async def close(self):
|
| 911 |
-
"""关闭会话"""
|
| 912 |
-
await self.session.close()
|
| 913 |
-
|
| 914 |
# 修改代理管理器的创建方式
|
| 915 |
proxy_manager = None
|
| 916 |
|
|
@@ -1072,6 +1076,5 @@ if __name__ == "__main__":
|
|
| 1072 |
def cleanup():
|
| 1073 |
"""清理资源"""
|
| 1074 |
if proxy_manager:
|
| 1075 |
-
|
| 1076 |
-
loop.run_until_complete(proxy_manager.close())
|
| 1077 |
|
|
|
|
| 781 |
|
| 782 |
return payload
|
| 783 |
|
| 784 |
+
# 修改理相关的常量和配置
|
| 785 |
PROXY_API_BASE = "https://269900.xyz"
|
| 786 |
PROXY_CHECK_INTERVAL = 300 # 5分钟检查一次代理可用性
|
| 787 |
PROXY_MAX_LATENCY = 5000 # 最大延迟(毫秒)
|
|
|
|
| 793 |
self.proxies: List[Dict[str, Union[str, int, float]]] = []
|
| 794 |
self.last_update = 0
|
| 795 |
self.lock = threading.Lock()
|
|
|
|
| 796 |
|
| 797 |
+
def _create_session(self):
|
| 798 |
+
"""创建新的 aiohttp session"""
|
| 799 |
+
return aiohttp.ClientSession()
|
| 800 |
+
|
| 801 |
+
async def _fetch_proxies_async(self, session):
|
| 802 |
"""异步获取代理列表"""
|
| 803 |
try:
|
|
|
|
| 804 |
endpoint = f"{PROXY_API_BASE}/fetch_all?region=cn&count=5"
|
| 805 |
+
async with session.get(endpoint, timeout=aiohttp.ClientTimeout(total=PROXY_TIMEOUT)) as response:
|
|
|
|
| 806 |
if response.status == 200:
|
| 807 |
+
text = await response.text()
|
| 808 |
+
proxy_list = [p.strip() for p in text.split(',') if p.strip()]
|
| 809 |
+
|
| 810 |
+
with self.lock:
|
| 811 |
+
self.proxies = []
|
| 812 |
+
for proxy_str in proxy_list:
|
| 813 |
+
proxy_info = self._parse_proxy_string(proxy_str)
|
| 814 |
+
if proxy_info:
|
| 815 |
+
self.proxies.append(proxy_info)
|
| 816 |
|
| 817 |
+
self.last_update = time.time()
|
| 818 |
+
logger.info(f"Successfully fetched {len(self.proxies)} proxies")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 819 |
else:
|
| 820 |
logger.error(f"Failed to fetch proxies, status: {response.status}")
|
|
|
|
| 821 |
except Exception as e:
|
| 822 |
logger.error(f"Error in fetch_proxies: {e}")
|
| 823 |
finally:
|
| 824 |
if not self.proxies:
|
| 825 |
logger.warning("No proxies available, will retry later")
|
| 826 |
|
| 827 |
+
def fetch_proxies(self):
|
| 828 |
+
"""同步包装异步函数"""
|
| 829 |
+
async def _run():
|
| 830 |
+
async with self._create_session() as session:
|
| 831 |
+
await self._fetch_proxies_async(session)
|
| 832 |
+
|
| 833 |
+
loop = asyncio.new_event_loop()
|
| 834 |
+
asyncio.set_event_loop(loop)
|
| 835 |
+
try:
|
| 836 |
+
loop.run_until_complete(_run())
|
| 837 |
+
except Exception as e:
|
| 838 |
+
logger.error(f"Error in fetch_proxies sync wrapper: {e}")
|
| 839 |
+
finally:
|
| 840 |
+
loop.close()
|
| 841 |
+
|
| 842 |
+
def get_proxy(self) -> Optional[str]:
|
| 843 |
+
"""获取一个可用的代理"""
|
| 844 |
+
with self.lock:
|
| 845 |
+
current_time = time.time()
|
| 846 |
+
|
| 847 |
+
if not self.proxies or (current_time - self.last_update) > PROXY_CHECK_INTERVAL:
|
| 848 |
+
self.fetch_proxies()
|
| 849 |
+
|
| 850 |
+
if not self.proxies:
|
| 851 |
+
return None
|
| 852 |
+
|
| 853 |
+
valid_proxies = [p for p in self.proxies if p['fails'] < 3]
|
| 854 |
+
if not valid_proxies:
|
| 855 |
+
return None
|
| 856 |
+
|
| 857 |
+
proxy = min(valid_proxies, key=lambda x: (x['fails'], x['last_use']))
|
| 858 |
+
proxy['last_use'] = current_time
|
| 859 |
+
return proxy['url']
|
| 860 |
+
|
| 861 |
+
def mark_proxy_failed(self, proxy_url: str) -> None:
|
| 862 |
+
"""标记代理失败"""
|
| 863 |
+
with self.lock:
|
| 864 |
+
for proxy in self.proxies:
|
| 865 |
+
if proxy['url'] == proxy_url:
|
| 866 |
+
proxy['fails'] += 1
|
| 867 |
+
if proxy['fails'] >= 3:
|
| 868 |
+
self.proxies.remove(proxy)
|
| 869 |
+
logger.info(f"Removed failed proxy: {proxy_url}")
|
| 870 |
+
break
|
| 871 |
+
|
| 872 |
+
async def check_proxy(self, proxy_url: str) -> bool:
|
| 873 |
+
"""检查代理是否可用"""
|
| 874 |
+
async with self._create_session() as session:
|
| 875 |
+
try:
|
| 876 |
+
async with session.get(
|
| 877 |
+
'https://www.google.com',
|
| 878 |
+
proxy=proxy_url,
|
| 879 |
+
timeout=aiohttp.ClientTimeout(total=PROXY_TIMEOUT)
|
| 880 |
+
) as response:
|
| 881 |
+
return response.status == 200
|
| 882 |
+
except Exception:
|
| 883 |
+
return False
|
| 884 |
+
|
| 885 |
def _parse_proxy_string(self, proxy_str: str) -> Optional[Dict[str, Union[str, int, float]]]:
|
| 886 |
"""解析代理字符串"""
|
| 887 |
try:
|
|
|
|
| 889 |
if not proxy_str:
|
| 890 |
return None
|
| 891 |
|
|
|
|
| 892 |
if proxy_str.startswith(('http://', 'https://', 'socks4://', 'socks5://')):
|
| 893 |
proxy_type = proxy_str.split('://')[0]
|
| 894 |
address = proxy_str.split('://')[1]
|
|
|
|
| 896 |
proxy_type = 'http'
|
| 897 |
address = proxy_str
|
| 898 |
|
|
|
|
| 899 |
if ':' in address:
|
| 900 |
ip, port = address.split(':')
|
| 901 |
port = int(port)
|
|
|
|
| 915 |
logger.error(f"Error parsing proxy string '{proxy_str}': {e}")
|
| 916 |
return None
|
| 917 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 918 |
# 修改代理管理器的创建方式
|
| 919 |
proxy_manager = None
|
| 920 |
|
|
|
|
| 1076 |
def cleanup():
|
| 1077 |
"""清理资源"""
|
| 1078 |
if proxy_manager:
|
| 1079 |
+
logger.info("Cleaning up resources...")
|
|
|
|
| 1080 |
|