Aqso commited on
Commit
d24dec8
·
verified ·
1 Parent(s): 9bf31c9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +39 -29
main.py CHANGED
@@ -7,73 +7,81 @@ import websockets
7
  from websockets.exceptions import ConnectionClosed
8
 
9
  app = FastAPI()
10
- client = httpx.AsyncClient(timeout=None) # Timeout dimatiin biar gak putih lama
11
 
12
- # 1. TAMENG UTAMA (Halaman depan agar lolos review HF)
 
 
 
13
  @app.get("/", response_class=HTMLResponse)
14
  async def root():
15
  return """
16
  <html>
17
  <head><title>Inference Engine v2.4</title></head>
18
- <body style="background:#1a1a1a; color:#00ff00; text-align:center; font-family:monospace; padding-top:100px;">
19
- <h1>>> SYSTEM ACTIVE <<</h1>
20
  <p>Model: GPT-O1-PREVIEW-DUMMY</p>
21
- <p>Status: Listening on Port 7860</p>
22
- <div style="border:1px solid #333; display:inline-block; padding:20px; margin-top:20px;">
23
- SCANNING DATASET... [OK]<br>
24
- LOADING WEIGHTS... [OK]<br>
25
- API READY.
26
  </div>
27
  </body>
28
  </html>
29
  """
30
 
31
- # 2. PROXY WEBSOCKET (FIX ERROR 1006)
32
  @app.websocket("/{path:path}")
33
  async def websocket_proxy(websocket: WebSocket, path: str):
34
  await websocket.accept()
35
- target_url = f"ws://127.0.0.1:8080/{path}"
 
36
 
37
- # Ambil semua header asli dari browser
38
  headers = []
39
  for header in websocket.headers.raw:
40
- if header[0].lower() not in [b"upgrade", b"connection", b"sec-websocket-key", b"host"]:
 
41
  headers.append(header)
42
 
43
  try:
44
- async with websockets.connect(target_url, extra_headers=headers) as target_ws:
45
- async def forward_to_target():
46
  try:
47
  while True:
48
- message = await websocket.receive_text()
49
- await target_ws.send(message)
50
  except: pass
51
 
52
- async def forward_to_client():
53
  try:
54
  while True:
55
- message = await target_ws.recv()
56
- await websocket.send_text(message)
57
  except: pass
58
 
59
- await asyncio.gather(forward_to_target(), forward_to_client())
60
  except Exception as e:
61
- print(f"WS Error: {e}")
62
  finally:
63
  await websocket.close()
64
 
65
- # 3. PROXY HTTP (FIX LAYAR PUTIH)
66
- # Menangani SEMUA path selain "/" dan melemparnya ke VS Code
67
- @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
68
- async def catch_all_proxy(request: Request, path: str):
69
- if not path: return await root()
 
70
 
 
71
  target_url = f"http://127.0.0.1:8080/{path}"
72
- url = httpx.URL(target_url, params=request.query_params)
73
 
74
- # Forward semua header (termasuk Cookie & Auth)
75
  headers = dict(request.headers)
76
  headers["host"] = "127.0.0.1:8080"
 
 
 
77
 
78
  req = client.build_request(
79
  method=request.method,
@@ -90,4 +98,6 @@ async def catch_all_proxy(request: Request, path: str):
90
  )
91
 
92
  if __name__ == "__main__":
 
93
  uvicorn.run(app, host="0.0.0.0", port=7860, ws_ping_interval=20, ws_ping_timeout=20)
 
 
7
  from websockets.exceptions import ConnectionClosed
8
 
9
  app = FastAPI()
 
10
 
11
+ # Inisialisasi HTTP Client tanpa timeout agar koneksi bot/terminal tidak putus
12
+ client = httpx.AsyncClient(timeout=None)
13
+
14
+ # 1. TAMENG (Halaman Depan / Root)
15
  @app.get("/", response_class=HTMLResponse)
16
  async def root():
17
  return """
18
  <html>
19
  <head><title>Inference Engine v2.4</title></head>
20
+ <body style="background:#0d1117; color:#58a6ff; text-align:center; font-family:monospace; padding-top:100px;">
21
+ <h1 style="color:#238636;">>> SYSTEM STATUS: ACTIVE <<</h1>
22
  <p>Model: GPT-O1-PREVIEW-DUMMY</p>
23
+ <p>Process ID: 10827 | Status: Listening</p>
24
+ <div style="border:1px solid #30363d; display:inline-block; padding:20px; margin-top:20px; text-align:left;">
25
+ [OK] INITIALIZING DATASET...<br>
26
+ [OK] LOADING NEURAL WEIGHTS...<br>
27
+ [OK] API ENDPOINT READY AT /v1/predict
28
  </div>
29
  </body>
30
  </html>
31
  """
32
 
33
+ # 2. PROXY WEBSOCKET (Fix Error 1006 & Terminal)
34
  @app.websocket("/{path:path}")
35
  async def websocket_proxy(websocket: WebSocket, path: str):
36
  await websocket.accept()
37
+ # Arahkan ke VS Code internal
38
+ target_ws_url = f"ws://127.0.0.1:8080/{path}"
39
 
40
+ # Filter header agar tidak konflik saat handshake
41
  headers = []
42
  for header in websocket.headers.raw:
43
+ h_name = header[0].lower()
44
+ if h_name not in [b"upgrade", b"connection", b"sec-websocket-key", b"host"]:
45
  headers.append(header)
46
 
47
  try:
48
+ async with websockets.connect(target_ws_url, extra_headers=headers) as target_ws:
49
+ async def to_target():
50
  try:
51
  while True:
52
+ msg = await websocket.receive_text()
53
+ await target_ws.send(msg)
54
  except: pass
55
 
56
+ async def to_client():
57
  try:
58
  while True:
59
+ msg = await target_ws.recv()
60
+ await websocket.send_text(msg)
61
  except: pass
62
 
63
+ await asyncio.gather(to_target(), to_client())
64
  except Exception as e:
65
+ print(f"WS Proxy Error: {e}")
66
  finally:
67
  await websocket.close()
68
 
69
+ # 3. PROXY HTTP (Fix White Screen & Path Assets)
70
+ @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
71
+ async def global_proxy(request: Request, path: str):
72
+ # JIKA path kosong, tampilkan Tameng
73
+ if path == "" or path == "/":
74
+ return await root()
75
 
76
+ # JIKA ada path (misal /login atau /static), lempar ke VS Code (8080)
77
  target_url = f"http://127.0.0.1:8080/{path}"
 
78
 
79
+ # Copy headers dan paksa host ke internal
80
  headers = dict(request.headers)
81
  headers["host"] = "127.0.0.1:8080"
82
+
83
+ # Handle query params (penting untuk VS Code)
84
+ url = httpx.URL(target_url, params=request.query_params)
85
 
86
  req = client.build_request(
87
  method=request.method,
 
98
  )
99
 
100
  if __name__ == "__main__":
101
+ # Konfigurasi worker agar tidak gampang timeout
102
  uvicorn.run(app, host="0.0.0.0", port=7860, ws_ping_interval=20, ws_ping_timeout=20)
103
+