rkihacker commited on
Commit
e50ca24
·
verified ·
1 Parent(s): 6b64125

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +56 -20
main.py CHANGED
@@ -6,7 +6,7 @@ import random
6
  import logging
7
  import ipaddress
8
 
9
- # Configure logging to output to stdout
10
  logging.basicConfig(
11
  level=logging.INFO,
12
  format="%(asctime)s - %(levelname)s - %(message)s",
@@ -21,6 +21,22 @@ API_URLS = [
21
  "https://stage.api.deepinfra.com/v1/openai/chat/completions",
22
  ]
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  def generate_random_ip() -> str:
25
  """Generate a random IPv4 address, avoiding reserved ranges."""
26
  while True:
@@ -32,31 +48,47 @@ def generate_random_ip() -> str:
32
  async def proxy_deepinfra(request: Request):
33
  """
34
  Proxies chat completion requests to the DeepInfra API.
35
- It randomizes the order of API URLs and uses the next as a fallback.
36
- Adds spoofed random IP headers.
37
  """
38
  try:
39
  body = await request.json()
40
  except json.JSONDecodeError:
41
  raise HTTPException(status_code=400, detail="Invalid JSON in request body")
42
 
43
- # Generate a random spoofed IP
44
  random_ip = generate_random_ip()
 
45
 
46
  headers = {
47
- 'sec-ch-ua-platform': request.headers.get('sec-ch-ua-platform', '"Windows"'),
48
- 'Referer': request.headers.get('Referer', 'https://deepinfra.com/'),
49
- 'sec-ch-ua': request.headers.get('sec-ch-ua', '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"'),
50
- 'sec-ch-ua-mobile': request.headers.get('sec-ch-ua-mobile', '?0'),
51
- 'User-Agent': request.headers.get('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36'),
52
- 'accept': request.headers.get('accept', 'text/event-stream'),
53
- 'X-Deepinfra-Source': request.headers.get('X-Deepinfra-Source', 'web-embed'),
54
- 'Content-Type': request.headers.get('Content-Type', 'application/json'),
55
 
56
  # Spoofed IP headers
57
- 'X-Forwarded-For': random_ip,
58
- 'X-Real-IP': random_ip,
59
- 'Forwarded': f'for={random_ip};proto=https',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
 
62
  shuffled_urls = random.sample(API_URLS, len(API_URLS))
@@ -64,10 +96,14 @@ async def proxy_deepinfra(request: Request):
64
  async def stream_generator():
65
  last_error = None
66
  for url in shuffled_urls:
67
- logging.info(f"Attempting to connect to: {url} with spoofed IP {random_ip}")
 
 
68
  try:
69
  async with httpx.AsyncClient() as client:
70
- async with client.stream("POST", url, headers=headers, json=body, timeout=None) as response:
 
 
71
  response.raise_for_status()
72
  logging.info(f"Successfully connected. Streaming from: {url}")
73
  async for chunk in response.aiter_bytes():
@@ -75,11 +111,11 @@ async def proxy_deepinfra(request: Request):
75
  return
76
  except (httpx.RequestError, httpx.HTTPStatusError) as e:
77
  last_error = e
78
- logging.warning(f"Failed to connect to {url}: {e}. Trying next URL.")
 
 
79
  continue
80
  if last_error:
81
  logging.error(f"All API endpoints failed. Last error: {last_error}")
82
- # In a streaming response, we can't easily raise an HTTPException after starting.
83
- # The connection will simply close, which the client will see as a failed request.
84
 
85
  return StreamingResponse(stream_generator(), media_type="text-event-stream")
 
6
  import logging
7
  import ipaddress
8
 
9
+ # Configure logging
10
  logging.basicConfig(
11
  level=logging.INFO,
12
  format="%(asctime)s - %(levelname)s - %(message)s",
 
21
  "https://stage.api.deepinfra.com/v1/openai/chat/completions",
22
  ]
23
 
24
+ # A pool of User-Agents (you can expand this list)
25
+ USER_AGENTS = [
26
+ # Chrome (Windows)
27
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
28
+ # Firefox (Windows)
29
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0",
30
+ # Safari (macOS)
31
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15",
32
+ # Edge (Windows)
33
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0",
34
+ # Chrome (Android)
35
+ "Mozilla/5.0 (Linux; Android 14; Pixel 7 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36",
36
+ # Safari (iOS)
37
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1",
38
+ ]
39
+
40
  def generate_random_ip() -> str:
41
  """Generate a random IPv4 address, avoiding reserved ranges."""
42
  while True:
 
48
  async def proxy_deepinfra(request: Request):
49
  """
50
  Proxies chat completion requests to the DeepInfra API.
51
+ Randomizes API URLs, spoofed random IP, fake headers, and User-Agent rotation.
 
52
  """
53
  try:
54
  body = await request.json()
55
  except json.JSONDecodeError:
56
  raise HTTPException(status_code=400, detail="Invalid JSON in request body")
57
 
58
+ # Random spoofed IP + random User-Agent
59
  random_ip = generate_random_ip()
60
+ user_agent = random.choice(USER_AGENTS)
61
 
62
  headers = {
63
+ # Browser/device headers
64
+ "User-Agent": user_agent,
65
+ "accept": "text/event-stream",
66
+ "sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
67
+ "sec-ch-ua-mobile": "?0",
68
+ "sec-ch-ua-platform": '"Windows"',
69
+ "Referer": "https://deepinfra.com/",
70
+ "Origin": "https://deepinfra.com",
71
 
72
  # Spoofed IP headers
73
+ "X-Forwarded-For": random_ip,
74
+ "X-Real-IP": random_ip,
75
+ "Forwarded": f"for={random_ip};proto=https",
76
+
77
+ # Extra fake headers
78
+ "DNT": "1",
79
+ "Pragma": "no-cache",
80
+ "Cache-Control": "no-cache",
81
+ "Accept-Encoding": "gzip, deflate, br, zstd",
82
+ "Accept-Language": "en-US,en;q=0.9,fr;q=0.8,de;q=0.7",
83
+ "Upgrade-Insecure-Requests": "1",
84
+ "Sec-Fetch-Dest": "document",
85
+ "Sec-Fetch-Mode": "navigate",
86
+ "Sec-Fetch-Site": "none",
87
+ "Sec-Fetch-User": "?1",
88
+
89
+ # Deepinfra-specific
90
+ "X-Deepinfra-Source": request.headers.get("X-Deepinfra-Source", "web-embed"),
91
+ "Content-Type": "application/json",
92
  }
93
 
94
  shuffled_urls = random.sample(API_URLS, len(API_URLS))
 
96
  async def stream_generator():
97
  last_error = None
98
  for url in shuffled_urls:
99
+ logging.info(
100
+ f"Attempting to connect to: {url} with spoofed IP {random_ip} and UA {user_agent}"
101
+ )
102
  try:
103
  async with httpx.AsyncClient() as client:
104
+ async with client.stream(
105
+ "POST", url, headers=headers, json=body, timeout=None
106
+ ) as response:
107
  response.raise_for_status()
108
  logging.info(f"Successfully connected. Streaming from: {url}")
109
  async for chunk in response.aiter_bytes():
 
111
  return
112
  except (httpx.RequestError, httpx.HTTPStatusError) as e:
113
  last_error = e
114
+ logging.warning(
115
+ f"Failed to connect to {url}: {e}. Trying next URL."
116
+ )
117
  continue
118
  if last_error:
119
  logging.error(f"All API endpoints failed. Last error: {last_error}")
 
 
120
 
121
  return StreamingResponse(stream_generator(), media_type="text-event-stream")