Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,18 @@
|
|
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,29 +618,88 @@ HTML_CONTENT = """
|
|
612 |
async def index():
|
613 |
return HTML_CONTENT
|
614 |
|
615 |
-
@app.post("/
|
616 |
-
async def
|
617 |
-
|
618 |
-
|
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 |
-
|
|
|
|
|
|
|
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 |
-
|
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}'
|
@@ -738,7 +803,8 @@ async def upload_file(upload_url: str, file_content: bytes, content_type: str) -
|
|
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 |
-
|
|
|
742 |
try:
|
743 |
success = await upload_file(upload_url, file_content, content_type)
|
744 |
if success:
|
@@ -749,5 +815,6 @@ async def retry_upload(upload_url: str, file_content: bytes, content_type: str,
|
|
749 |
|
750 |
await asyncio.sleep(delay)
|
751 |
delay = min(delay * 2, 60) # Exponential backoff, capped at 60 seconds
|
|
|
752 |
|
753 |
return False
|
|
|
1 |
+
from fastapi import FastAPI, File, UploadFile, Request, Form
|
2 |
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
|
3 |
+
from fastapi.staticfiles import StaticFiles
|
4 |
import requests
|
|
|
5 |
import asyncio
|
6 |
from typing import Dict
|
7 |
+
import os
|
8 |
+
import shutil
|
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 |
async def index():
|
619 |
return HTML_CONTENT
|
620 |
|
621 |
+
@app.post("/upload_chunk")
|
622 |
+
async def upload_chunk(
|
623 |
+
fileId: str = Form(...),
|
624 |
+
fileName: str = Form(...),
|
625 |
+
totalChunks: int = Form(..., gt=0),
|
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 |
+
# Get the content type based on the file extension
|
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 |
+
upload_success = await retry_upload(upload_result['upload_url'], file_content, content_type)
|
|
|
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 |
+
import mimetypes
|
701 |
+
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
702 |
+
|
703 |
@app.get("/rbxg/{path:path}")
|
704 |
async def handle_video_stream(path: str, request: Request):
|
705 |
original_url = f'https://replicate.delivery/pbxt/{path}'
|
|
|
803 |
return False
|
804 |
|
805 |
async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
|
806 |
+
retries = 0
|
807 |
+
while retries < max_retries:
|
808 |
try:
|
809 |
success = await upload_file(upload_url, file_content, content_type)
|
810 |
if success:
|
|
|
815 |
|
816 |
await asyncio.sleep(delay)
|
817 |
delay = min(delay * 2, 60) # Exponential backoff, capped at 60 seconds
|
818 |
+
retries += 1
|
819 |
|
820 |
return False
|