Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
@@ -1,38 +1,51 @@
|
|
1 |
from fastapi import FastAPI, Request, Header, HTTPException
|
2 |
from fastapi.responses import JSONResponse, Response
|
3 |
import httpx
|
|
|
4 |
|
5 |
app = FastAPI()
|
6 |
|
7 |
-
# Your internal real API key
|
8 |
-
REAL_API_KEY = "sk-
|
9 |
-
BASE_URL = "https://
|
10 |
|
11 |
-
# Public token users must
|
12 |
PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
@app.api_route("/{path:path}", methods=["GET", "POST"])
|
15 |
async def proxy(request: Request, path: str, authorization: str = Header(None)):
|
16 |
-
# Validate
|
17 |
if not authorization or not authorization.startswith("Bearer "):
|
18 |
raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.")
|
19 |
-
|
20 |
token = authorization.replace("Bearer ", "").strip()
|
21 |
|
22 |
if token != PUBLIC_AUTH_TOKEN:
|
23 |
raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
|
24 |
|
25 |
-
#
|
26 |
target_url = f"{BASE_URL}/{path}"
|
27 |
|
28 |
-
#
|
29 |
headers = dict(request.headers)
|
30 |
headers["Authorization"] = f"Bearer {REAL_API_KEY}"
|
31 |
headers.pop("host", None)
|
32 |
|
33 |
-
#
|
34 |
body = await request.body()
|
35 |
|
|
|
36 |
async with httpx.AsyncClient() as client:
|
37 |
try:
|
38 |
response = await client.request(
|
@@ -40,17 +53,17 @@ async def proxy(request: Request, path: str, authorization: str = Header(None)):
|
|
40 |
url=target_url,
|
41 |
content=body,
|
42 |
headers=headers,
|
43 |
-
timeout=60
|
44 |
)
|
45 |
except httpx.RequestError as e:
|
46 |
raise HTTPException(status_code=502, detail=f"Request to backend failed: {e}")
|
47 |
|
48 |
-
#
|
49 |
-
print("
|
50 |
-
print("TypeGPT
|
51 |
-
print("TypeGPT Response
|
52 |
|
53 |
-
# Try to return JSON
|
54 |
try:
|
55 |
return JSONResponse(content=response.json(), status_code=response.status_code)
|
56 |
except Exception:
|
|
|
1 |
from fastapi import FastAPI, Request, Header, HTTPException
|
2 |
from fastapi.responses import JSONResponse, Response
|
3 |
import httpx
|
4 |
+
import socket
|
5 |
|
6 |
app = FastAPI()
|
7 |
|
8 |
+
# Your internal real API key (DO NOT expose this to users)
|
9 |
+
REAL_API_KEY = "sk-qO9N6kQEEULMWtF4YGVlTTSjIPllEm1h1wfEBzSmnSbxiXwe"
|
10 |
+
BASE_URL = "https://fast.typegpt.net"
|
11 |
|
12 |
+
# Public token that users must use
|
13 |
PUBLIC_AUTH_TOKEN = "TypeGPT-Free4ALL"
|
14 |
|
15 |
+
# Print server IP address on startup
|
16 |
+
@app.on_event("startup")
|
17 |
+
async def startup_event():
|
18 |
+
try:
|
19 |
+
hostname = socket.gethostname()
|
20 |
+
server_ip = socket.gethostbyname(hostname)
|
21 |
+
print(f"===== Server Started =====")
|
22 |
+
print(f"📡 Server IP: {server_ip}")
|
23 |
+
except Exception as e:
|
24 |
+
print(f"⚠️ Could not get server IP: {e}")
|
25 |
+
|
26 |
@app.api_route("/{path:path}", methods=["GET", "POST"])
|
27 |
async def proxy(request: Request, path: str, authorization: str = Header(None)):
|
28 |
+
# Validate Authorization token
|
29 |
if not authorization or not authorization.startswith("Bearer "):
|
30 |
raise HTTPException(status_code=401, detail="Missing or malformed Authorization header.")
|
31 |
+
|
32 |
token = authorization.replace("Bearer ", "").strip()
|
33 |
|
34 |
if token != PUBLIC_AUTH_TOKEN:
|
35 |
raise HTTPException(status_code=401, detail="Invalid Authorization token. Use 'TypeGPT-Free4ALL'.")
|
36 |
|
37 |
+
# Prepare the backend target URL
|
38 |
target_url = f"{BASE_URL}/{path}"
|
39 |
|
40 |
+
# Clone headers, replace Authorization
|
41 |
headers = dict(request.headers)
|
42 |
headers["Authorization"] = f"Bearer {REAL_API_KEY}"
|
43 |
headers.pop("host", None)
|
44 |
|
45 |
+
# Read request body
|
46 |
body = await request.body()
|
47 |
|
48 |
+
# Forward request to backend
|
49 |
async with httpx.AsyncClient() as client:
|
50 |
try:
|
51 |
response = await client.request(
|
|
|
53 |
url=target_url,
|
54 |
content=body,
|
55 |
headers=headers,
|
56 |
+
timeout=60
|
57 |
)
|
58 |
except httpx.RequestError as e:
|
59 |
raise HTTPException(status_code=502, detail=f"Request to backend failed: {e}")
|
60 |
|
61 |
+
# Debug log
|
62 |
+
print(f"🔄 Forwarded to: {target_url}")
|
63 |
+
print(f"↩️ TypeGPT Status: {response.status_code}")
|
64 |
+
print(f"🧾 TypeGPT Response (first 200 chars): {response.text[:200]}")
|
65 |
|
66 |
+
# Try to return JSON or fallback
|
67 |
try:
|
68 |
return JSONResponse(content=response.json(), status_code=response.status_code)
|
69 |
except Exception:
|