coollsd commited on
Commit
6d7bfa0
1 Parent(s): b41693c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -0
app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Request, Response
2
+ from fastapi.responses import HTMLResponse, RedirectResponse
3
+ import requests
4
+ from urllib.parse import urljoin
5
+ import time
6
+ from typing import Dict
7
+
8
+ app = FastAPI()
9
+
10
+ HTML_CONTENT = """
11
+ <!DOCTYPE html>
12
+ <html lang="en">
13
+ <head>
14
+ <meta charset="UTF-8">
15
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
16
+ <title>File Upload</title>
17
+ </head>
18
+ <body>
19
+ <h1>Upload File</h1>
20
+ <form action="/upload" method="post" enctype="multipart/form-data">
21
+ <input type="file" name="file" accept="*/*" required>
22
+ <button type="submit">Upload</button>
23
+ </form>
24
+ </body>
25
+ </html>
26
+ """
27
+
28
+ @app.get("/", response_class=HTMLResponse)
29
+ async def index():
30
+ return HTML_CONTENT
31
+
32
+ @app.post("/upload")
33
+ async def handle_upload(file: UploadFile = File(...)):
34
+ if not file.filename:
35
+ return {"error": "No file selected."}, 400
36
+
37
+ cookies = await get_cookies()
38
+ if 'csrftoken' not in cookies or 'sessionid' not in cookies:
39
+ return {"error": "Failed to obtain necessary cookies"}, 500
40
+
41
+ upload_result = await initiate_upload(cookies, file.filename, file.content_type)
42
+ if not upload_result or 'upload_url' not in upload_result:
43
+ return {"error": "Failed to initiate upload"}, 500
44
+
45
+ file_content = await file.read()
46
+ upload_success = await retry_upload(upload_result['upload_url'], file_content, file.content_type)
47
+ if not upload_success:
48
+ return {"error": "File upload failed after multiple attempts"}, 500
49
+
50
+ original_url = upload_result['serving_url']
51
+ mirrored_url = f"/rbxg/{original_url.split('/pbxt/')[1]}"
52
+ return RedirectResponse(url=mirrored_url, status_code=302)
53
+
54
+ @app.get("/rbxg/{path:path}")
55
+ async def handle_video_stream(path: str, request: Request):
56
+ original_url = f'https://replicate.delivery/pbxt/{path}'
57
+ range_header = request.headers.get('Range')
58
+
59
+ headers = {'Range': range_header} if range_header else {}
60
+ response = requests.get(original_url, headers=headers, stream=True)
61
+
62
+ def generate():
63
+ for chunk in response.iter_content(chunk_size=8192):
64
+ yield chunk
65
+
66
+ headers = dict(response.headers)
67
+ headers['Access-Control-Allow-Origin'] = '*'
68
+
69
+ if response.status_code == 206:
70
+ headers['Content-Range'] = response.headers.get('Content-Range')
71
+
72
+ return Response(content=generate(), status_code=response.status_code, headers=headers)
73
+
74
+ async def get_cookies() -> Dict[str, str]:
75
+ try:
76
+ response = requests.get('https://replicate.com/levelsio/neon-tokyo', headers={
77
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
78
+ })
79
+ return dict(response.cookies)
80
+ except Exception as e:
81
+ print(f'Error fetching the page: {e}')
82
+ return {}
83
+
84
+ async def initiate_upload(cookies: Dict[str, str], filename: str, content_type: str) -> Dict:
85
+ url = f'https://replicate.com/api/upload/{filename}?content_type={content_type}'
86
+ try:
87
+ response = requests.post(url, cookies=cookies, headers={
88
+ 'X-CSRFToken': cookies.get('csrftoken'),
89
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
90
+ 'Referer': 'https://replicate.com/levelsio/neon-tokyo',
91
+ 'Origin': 'https://replicate.com',
92
+ 'Accept': '*/*',
93
+ 'Accept-Language': 'en-US,en;q=0.5',
94
+ 'Accept-Encoding': 'identity',
95
+ 'Sec-Fetch-Dest': 'empty',
96
+ 'Sec-Fetch-Mode': 'cors',
97
+ 'Sec-Fetch-Site': 'same-origin',
98
+ 'Sec-GPC': '1',
99
+ 'Priority': 'u=1, i'
100
+ })
101
+ print(f'Initiate upload response status: {response.status_code}')
102
+ print(f'Initiate upload response headers: {response.headers}')
103
+ print(f'Response body: {response.text}')
104
+ return response.json()
105
+ except Exception as e:
106
+ print(f'Error initiating upload: {e}')
107
+ raise
108
+
109
+ async def upload_file(upload_url: str, file_content: bytes, content_type: str) -> bool:
110
+ try:
111
+ response = requests.put(upload_url, data=file_content, headers={'Content-Type': content_type})
112
+ print(f'File upload response status: {response.status_code}')
113
+ print(f'File upload response headers: {response.headers}')
114
+ return response.status_code == 200
115
+ except Exception as e:
116
+ print(f'Error uploading file: {e}')
117
+ return False
118
+
119
+ async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
120
+ for attempt in range(1, max_retries + 1):
121
+ print(f'Upload attempt {attempt} of {max_retries}')
122
+ success = await upload_file(upload_url, file_content, content_type)
123
+ if success:
124
+ print('Upload successful')
125
+ return True
126
+ if attempt < max_retries:
127
+ print(f'Upload failed, retrying in {delay}s...')
128
+ time.sleep(delay)
129
+ delay *= 2 # Exponential backoff
130
+ print('Upload failed after all retry attempts')
131
+ return False