Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,18 +1,12 @@
|
|
1 |
-
from fastapi import FastAPI, File, UploadFile, Request
|
2 |
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
|
3 |
import requests
|
|
|
4 |
import asyncio
|
5 |
from typing import Dict
|
6 |
-
import os
|
7 |
-
import shutil
|
8 |
-
import mimetypes
|
9 |
|
10 |
app = FastAPI()
|
11 |
|
12 |
-
# Directory to store temporary chunks and final files
|
13 |
-
UPLOAD_DIR = "uploads"
|
14 |
-
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
15 |
-
|
16 |
HTML_CONTENT = """
|
17 |
<!DOCTYPE html>
|
18 |
<html lang="en">
|
@@ -618,87 +612,29 @@ HTML_CONTENT = """
|
|
618 |
async def index():
|
619 |
return HTML_CONTENT
|
620 |
|
621 |
-
@app.post("/
|
622 |
-
async def
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
chunkIndex: int = Form(..., ge=0),
|
627 |
-
chunkSize: int = Form(..., gt=0),
|
628 |
-
chunkData: UploadFile = File(...)
|
629 |
-
):
|
630 |
-
"""
|
631 |
-
Endpoint to handle each chunk upload.
|
632 |
-
"""
|
633 |
-
# Create a temporary directory based on fileId to store chunks
|
634 |
-
temp_dir = os.path.join(UPLOAD_DIR, fileId)
|
635 |
-
os.makedirs(temp_dir, exist_ok=True)
|
636 |
-
|
637 |
-
chunk_file_path = os.path.join(temp_dir, f"chunk_{chunkIndex}")
|
638 |
-
# Save the chunk to the temporary directory
|
639 |
-
with open(chunk_file_path, "wb") as f:
|
640 |
-
content = await chunkData.read()
|
641 |
-
f.write(content)
|
642 |
-
|
643 |
-
return {"status": "chunk received"}
|
644 |
-
|
645 |
-
@app.post("/finalize_upload")
|
646 |
-
async def finalize_upload(data: Dict):
|
647 |
-
fileId = data.get('fileId')
|
648 |
-
fileName = data.get('fileName')
|
649 |
-
|
650 |
-
temp_dir = os.path.join(UPLOAD_DIR, fileId)
|
651 |
-
if not os.path.exists(temp_dir):
|
652 |
-
return JSONResponse(content={"error": "Upload session does not exist"}, status_code=400)
|
653 |
-
|
654 |
-
# Get list of chunk files and sort them
|
655 |
-
chunk_files = [os.path.join(temp_dir, f) for f in os.listdir(temp_dir) if f.startswith('chunk_')]
|
656 |
-
if not chunk_files:
|
657 |
-
return JSONResponse(content={"error": "No chunks found for this file"}, status_code=400)
|
658 |
-
|
659 |
-
chunk_files.sort(key=lambda x: int(os.path.basename(x).split("_")[-1]))
|
660 |
-
|
661 |
-
# Combine chunks into the final file
|
662 |
-
final_file_path = os.path.join(temp_dir, fileName)
|
663 |
-
with open(final_file_path, "wb") as outfile:
|
664 |
-
for chunk_file in chunk_files:
|
665 |
-
with open(chunk_file, "rb") as infile:
|
666 |
-
outfile.write(infile.read())
|
667 |
-
|
668 |
-
# Proceed with your existing upload logic using 'final_file_path'
|
669 |
-
# For example, read the file and upload to external service
|
670 |
-
|
671 |
-
# Read the combined file content
|
672 |
-
with open(final_file_path, "rb") as f:
|
673 |
-
file_content = f.read()
|
674 |
-
|
675 |
-
# Obtain cookies and initiate upload as before
|
676 |
cookies = await get_cookies()
|
677 |
if 'csrftoken' not in cookies or 'sessionid' not in cookies:
|
678 |
return JSONResponse(content={"error": "Failed to obtain necessary cookies"}, status_code=500)
|
679 |
|
680 |
-
|
681 |
-
content_type = get_content_type(fileName)
|
682 |
-
|
683 |
-
upload_result = await initiate_upload(cookies, fileName, content_type)
|
684 |
if not upload_result or 'upload_url' not in upload_result:
|
685 |
return JSONResponse(content={"error": "Failed to initiate upload"}, status_code=500)
|
686 |
|
687 |
-
|
|
|
688 |
if not upload_success:
|
689 |
return JSONResponse(content={"error": "File upload failed after multiple attempts"}, status_code=500)
|
690 |
|
691 |
original_url = upload_result['serving_url']
|
692 |
mirrored_url = f"/rbxg/{original_url.split('/pbxt/')[1]}"
|
693 |
|
694 |
-
# Optionally, remove the temporary directory
|
695 |
-
shutil.rmtree(temp_dir)
|
696 |
-
|
697 |
return JSONResponse(content={"url": mirrored_url})
|
698 |
|
699 |
-
def get_content_type(filename: str) -> str:
|
700 |
-
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
701 |
-
|
702 |
@app.get("/rbxg/{path:path}")
|
703 |
async def handle_video_stream(path: str, request: Request):
|
704 |
original_url = f'https://replicate.delivery/pbxt/{path}'
|
@@ -737,12 +673,25 @@ async def embed_video(url: str, thumbnail: str):
|
|
737 |
<meta property="og:image:width" content="1280">
|
738 |
<meta property="og:image:height" content="720">
|
739 |
<meta property="og:image:type" content="image/png">
|
|
|
|
|
|
|
|
|
|
|
740 |
</head>
|
741 |
<body>
|
742 |
-
<
|
|
|
743 |
<source src="{url}" type="video/mp4">
|
744 |
Your browser does not support the video tag.
|
745 |
</video>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
746 |
</body>
|
747 |
</html>
|
748 |
'''
|
@@ -768,12 +717,17 @@ async def initiate_upload(cookies: Dict[str, str], filename: str, content_type:
|
|
768 |
'Origin': 'https://replicate.com',
|
769 |
'Accept': '*/*',
|
770 |
'Accept-Language': 'en-US,en;q=0.5',
|
771 |
-
'Accept-Encoding': 'identity'
|
|
|
|
|
|
|
|
|
|
|
772 |
})
|
773 |
return response.json()
|
774 |
except Exception as e:
|
775 |
print(f'Error initiating upload: {e}')
|
776 |
-
|
777 |
|
778 |
async def upload_file(upload_url: str, file_content: bytes, content_type: str) -> bool:
|
779 |
try:
|
@@ -784,8 +738,7 @@ async def upload_file(upload_url: str, file_content: bytes, content_type: str) -
|
|
784 |
return False
|
785 |
|
786 |
async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
|
787 |
-
|
788 |
-
while retries < max_retries:
|
789 |
try:
|
790 |
success = await upload_file(upload_url, file_content, content_type)
|
791 |
if success:
|
@@ -796,6 +749,5 @@ async def retry_upload(upload_url: str, file_content: bytes, content_type: str,
|
|
796 |
|
797 |
await asyncio.sleep(delay)
|
798 |
delay = min(delay * 2, 60) # Exponential backoff, capped at 60 seconds
|
799 |
-
retries += 1
|
800 |
|
801 |
return False
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile, Request
|
2 |
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
|
3 |
import requests
|
4 |
+
import time
|
5 |
import asyncio
|
6 |
from typing import Dict
|
|
|
|
|
|
|
7 |
|
8 |
app = FastAPI()
|
9 |
|
|
|
|
|
|
|
|
|
10 |
HTML_CONTENT = """
|
11 |
<!DOCTYPE html>
|
12 |
<html lang="en">
|
|
|
612 |
async def index():
|
613 |
return HTML_CONTENT
|
614 |
|
615 |
+
@app.post("/upload")
|
616 |
+
async def handle_upload(file: UploadFile = File(...)):
|
617 |
+
if not file.filename:
|
618 |
+
return JSONResponse(content={"error": "No file selected."}, status_code=400)
|
619 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
620 |
cookies = await get_cookies()
|
621 |
if 'csrftoken' not in cookies or 'sessionid' not in cookies:
|
622 |
return JSONResponse(content={"error": "Failed to obtain necessary cookies"}, status_code=500)
|
623 |
|
624 |
+
upload_result = await initiate_upload(cookies, file.filename, file.content_type)
|
|
|
|
|
|
|
625 |
if not upload_result or 'upload_url' not in upload_result:
|
626 |
return JSONResponse(content={"error": "Failed to initiate upload"}, status_code=500)
|
627 |
|
628 |
+
file_content = await file.read()
|
629 |
+
upload_success = await retry_upload(upload_result['upload_url'], file_content, file.content_type)
|
630 |
if not upload_success:
|
631 |
return JSONResponse(content={"error": "File upload failed after multiple attempts"}, status_code=500)
|
632 |
|
633 |
original_url = upload_result['serving_url']
|
634 |
mirrored_url = f"/rbxg/{original_url.split('/pbxt/')[1]}"
|
635 |
|
|
|
|
|
|
|
636 |
return JSONResponse(content={"url": mirrored_url})
|
637 |
|
|
|
|
|
|
|
638 |
@app.get("/rbxg/{path:path}")
|
639 |
async def handle_video_stream(path: str, request: Request):
|
640 |
original_url = f'https://replicate.delivery/pbxt/{path}'
|
|
|
673 |
<meta property="og:image:width" content="1280">
|
674 |
<meta property="og:image:height" content="720">
|
675 |
<meta property="og:image:type" content="image/png">
|
676 |
+
<style>
|
677 |
+
body, html {{ margin: 0; padding: 0; height: 100%; background: #000; }}
|
678 |
+
#thumbnail {{ width: 100%; height: 100%; object-fit: contain; cursor: pointer; }}
|
679 |
+
#video {{ display: none; width: 100%; height: 100%; object-fit: contain; }}
|
680 |
+
</style>
|
681 |
</head>
|
682 |
<body>
|
683 |
+
<img id="thumbnail" src="{thumbnail}" onclick="playVideo()">
|
684 |
+
<video id="video" controls autoplay>
|
685 |
<source src="{url}" type="video/mp4">
|
686 |
Your browser does not support the video tag.
|
687 |
</video>
|
688 |
+
<script>
|
689 |
+
function playVideo() {{
|
690 |
+
document.getElementById('thumbnail').style.display = 'none';
|
691 |
+
document.getElementById('video').style.display = 'block';
|
692 |
+
document.getElementById('video').play();
|
693 |
+
}}
|
694 |
+
</script>
|
695 |
</body>
|
696 |
</html>
|
697 |
'''
|
|
|
717 |
'Origin': 'https://replicate.com',
|
718 |
'Accept': '*/*',
|
719 |
'Accept-Language': 'en-US,en;q=0.5',
|
720 |
+
'Accept-Encoding': 'identity',
|
721 |
+
'Sec-Fetch-Dest': 'empty',
|
722 |
+
'Sec-Fetch-Mode': 'cors',
|
723 |
+
'Sec-Fetch-Site': 'same-origin',
|
724 |
+
'Sec-GPC': '1',
|
725 |
+
'Priority': 'u=1, i'
|
726 |
})
|
727 |
return response.json()
|
728 |
except Exception as e:
|
729 |
print(f'Error initiating upload: {e}')
|
730 |
+
raise
|
731 |
|
732 |
async def upload_file(upload_url: str, file_content: bytes, content_type: str) -> bool:
|
733 |
try:
|
|
|
738 |
return False
|
739 |
|
740 |
async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
|
741 |
+
while True:
|
|
|
742 |
try:
|
743 |
success = await upload_file(upload_url, file_content, content_type)
|
744 |
if success:
|
|
|
749 |
|
750 |
await asyncio.sleep(delay)
|
751 |
delay = min(delay * 2, 60) # Exponential backoff, capped at 60 seconds
|
|
|
752 |
|
753 |
return False
|