Spaces:
Paused
Paused
Download monitor.py from adityaxess/deepseek-proxy: direct link, hf CLI and curl.
- Browser
- Download file 5.65 kB
-
https://huggingface.co/spaces/adityaxess/deepseek-proxy/resolve/main/monitor.py
- Command line
-
hf download hf://spaces/adityaxess/deepseek-proxy/monitor.py
-
curl -L -o monitor.py https://huggingface.co/spaces/adityaxess/deepseek-proxy/resolve/main/monitor.py
5.65 kB
| import asyncio | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import urllib.request | |
| import websockets | |
| CDP_PORT = 9222 | |
| JSONL_LOG = "/home/adi/deepseek/captured_requests.jsonl" | |
| HUMAN_LOG = "/home/adi/deepseek/human_readable_requests.txt" | |
| print(f"Starting CDP Monitor script...") | |
| print(f"Log files: {JSONL_LOG} and {HUMAN_LOG}") | |
| # Ensure clean log files | |
| with open(JSONL_LOG, "w") as f: | |
| f.write("") | |
| with open(HUMAN_LOG, "w") as f: | |
| f.write("=== NETWORK MONITOR STARTED ===\n") | |
| request_store = {} | |
| req_counter = 0 | |
| async def get_browser_ws_url(): | |
| url = f"http://127.0.0.1:{CDP_PORT}/json/version" | |
| for _ in range(30): | |
| try: | |
| req = urllib.request.urlopen(url) | |
| data = json.loads(req.read().decode('utf-8')) | |
| return data["webSocketDebuggerUrl"] | |
| except Exception: | |
| await asyncio.sleep(1) | |
| raise RuntimeError(f"Could not connect to Chrome DevTools on port {CDP_PORT}") | |
| async def handle_cdp_events(ws): | |
| global req_counter | |
| # Enable Target auto-attach | |
| attach_cmd = { | |
| "id": 1, | |
| "method": "Target.setAutoAttach", | |
| "params": { | |
| "autoAttach": True, | |
| "waitForDebuggerOnStart": False, | |
| "flatten": True | |
| } | |
| } | |
| await ws.send(json.dumps(attach_cmd)) | |
| # Store active sessions | |
| sessions = set() | |
| async for msg_str in ws: | |
| msg = json.loads(msg_str) | |
| method = msg.get("method", "") | |
| session_id = msg.get("sessionId") | |
| params = msg.get("params", {}) | |
| # Handle new target attachment | |
| if method == "Target.attachedToTarget": | |
| sub_session_id = params.get("sessionId") | |
| target_info = params.get("targetInfo", {}) | |
| target_type = target_info.get("type") | |
| if sub_session_id and target_type in ("page", "iframe"): | |
| sessions.add(sub_session_id) | |
| # Enable Network for this session | |
| cmd_net = { | |
| "id": 1000 + len(sessions), | |
| "sessionId": sub_session_id, | |
| "method": "Network.enable", | |
| "params": {"maxPostDataSize": 1048576} # 1MB post data max | |
| } | |
| await ws.send(json.dumps(cmd_net)) | |
| elif method == "Network.requestWillBeSent": | |
| req_counter += 1 | |
| request_id = params.get("requestId") | |
| req = params.get("request", {}) | |
| url = req.get("url", "") | |
| req_type = params.get("type", "") | |
| method_str = req.get("method", "") | |
| post_data = req.get("postData", "") | |
| headers = req.get("headers", {}) | |
| timestamp = time.strftime("%Y-%m-%d %H:%M:%S") | |
| # Try to parse postData JSON if present | |
| post_json = None | |
| if post_data: | |
| try: | |
| post_json = json.loads(post_data) | |
| except Exception: | |
| pass | |
| entry = { | |
| "id": req_counter, | |
| "timestamp": timestamp, | |
| "requestId": request_id, | |
| "url": url, | |
| "method": method_str, | |
| "type": req_type, | |
| "headers": headers, | |
| "postData": post_data, | |
| "postJson": post_json | |
| } | |
| # Write to JSONL | |
| with open(JSONL_LOG, "a") as f: | |
| f.write(json.dumps(entry) + "\n") | |
| # Filter & print interesting requests (API / fetch / XHR / POST / websocket) | |
| is_api = any(kw in url for kw in ["/api/", "chat", "completion", "conversation", "v0", "v1", "model"]) or method_str in ["POST", "PUT", "DELETE"] | |
| if is_api and req_type in ["Fetch", "XHR", "Ping", "WebSocket"]: | |
| summary_lines = [] | |
| summary_lines.append(f"\n--- [REQUEST #{req_counter}] {timestamp} ---") | |
| summary_lines.append(f"Method: {method_str} | Type: {req_type}") | |
| summary_lines.append(f"URL: {url}") | |
| if post_json: | |
| summary_lines.append("Payload (Parsed JSON):") | |
| summary_lines.append(json.dumps(post_json, indent=2)) | |
| elif post_data: | |
| summary_lines.append(f"Payload (Raw): {post_data[:500]}") | |
| formatted_text = "\n".join(summary_lines) + "\n" | |
| print(formatted_text, flush=True) | |
| with open(HUMAN_LOG, "a") as f: | |
| f.write(formatted_text) | |
| elif method == "Network.responseReceived": | |
| resp = params.get("response", {}) | |
| url = resp.get("url", "") | |
| status = resp.get("status", 0) | |
| req_type = params.get("type", "") | |
| if any(kw in url for kw in ["/api/", "chat", "completion", "conversation"]) and req_type in ["Fetch", "XHR"]: | |
| log_text = f"[RESPONSE] Status: {status} | URL: {url}\n" | |
| print(log_text, flush=True) | |
| with open(HUMAN_LOG, "a") as f: | |
| f.write(log_text) | |
| async def main(): | |
| print(f"Connecting to Chrome via CDP port {CDP_PORT}...") | |
| ws_url = await get_browser_ws_url() | |
| print(f"Connected to browser WebSocket: {ws_url}") | |
| async with websockets.connect(ws_url, max_size=None) as ws: | |
| print("CDP Network Monitor active. Listening for requests...") | |
| await handle_cdp_events(ws) | |
| if __name__ == "__main__": | |
| try: | |
| asyncio.run(main()) | |
| except KeyboardInterrupt: | |
| print("Monitor stopped.") | |
| except Exception as e: | |
| print(f"Monitor error: {e}") | |