albumup commited on
Commit
2218121
·
verified ·
1 Parent(s): 991d698

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -71
app.py CHANGED
@@ -1,24 +1,38 @@
1
  from fastapi import FastAPI, File, UploadFile, Request
2
- from fastapi.responses import HTMLResponse, RedirectResponse, StreamingResponse
3
- import requests
4
- import asyncio
5
  import os
 
 
 
 
6
 
7
  app = FastAPI()
8
 
 
 
 
 
 
 
 
 
 
9
  HTML_CONTENT = """
10
  <!DOCTYPE html>
11
  <html lang="en">
12
  <head>
13
  <meta charset="UTF-8">
14
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
15
- <title>File Upload</title>
16
  </head>
17
  <body>
18
- <h1>Upload File</h1>
19
- <form action="/upload" method="post" enctype="multipart/form-data">
20
- <input type="file" name="file" accept="*/*" required>
21
- <button type="submit">Upload</button>
 
22
  </form>
23
  </body>
24
  </html>
@@ -28,76 +42,95 @@ HTML_CONTENT = """
28
  async def index():
29
  return HTML_CONTENT
30
 
31
- @app.post("/upload")
32
- async def handle_upload(request: Request, file: UploadFile = File(...)):
33
- if not file:
34
- return {"error": "No file uploaded"}, 400
35
-
36
- cookies = await get_cookies()
37
- if 'csrftoken' not in cookies or 'sessionid' not in cookies:
38
- return {"error": "Failed to get cookies"}, 500
39
-
40
- upload_result = await initiate_upload(cookies, file.filename, file.content_type)
41
- if not upload_result or 'upload_url' not in upload_result:
42
- return {"error": "Failed to initiate upload"}, 500
43
-
44
- file_content = await file.read()
45
- upload_success = await retry_upload(upload_result['upload_url'], file_content, file.content_type)
46
- if not upload_success:
47
- return {"error": "Upload failed"}, 500
48
-
49
- base_url = str(request.base_url).rstrip('/')
50
- redirect_url = f"{base_url}/upload/{upload_result['serving_url'].split('/pbxt/')[1]}"
51
- return RedirectResponse(url=redirect_url, status_code=303)
52
-
53
- @app.get("/upload/{path:path}")
54
- async def handle_stream(path: str, request: Request):
55
- original_url = f'https://replicate.delivery/pbxt/{path}'
56
- range_header = request.headers.get('Range')
57
- headers = {'Range': range_header} if range_header else {}
58
 
59
- response = requests.get(original_url, headers=headers, stream=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- def generate():
62
- for chunk in response.iter_content(chunk_size=8192):
63
- yield chunk
 
 
 
64
 
65
- headers = dict(response.headers)
66
- headers['Access-Control-Allow-Origin'] = '*'
 
 
 
67
 
68
- return StreamingResponse(generate(), headers=headers, status_code=response.status_code)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- async def get_cookies():
71
- try:
72
- response = requests.get('https://replicate.com/levelsio/neon-tokyo', headers={
73
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
74
- })
75
- return dict(response.cookies)
76
- except Exception:
77
- return {}
 
78
 
79
- async def initiate_upload(cookies, filename, content_type):
80
- url = f"https://replicate.com/api/upload/{filename}?content_type={content_type}"
81
- headers = {
82
- 'X-CSRFToken': cookies['csrftoken'],
83
- 'Referer': 'https://replicate.com/levelsio/neon-tokyo',
84
- 'Origin': 'https://replicate.com'
85
- }
86
- response = requests.post(url, cookies=cookies, headers=headers)
87
- return response.json()
88
 
89
- async def retry_upload(upload_url, file_content, content_type, max_retries=5):
90
- delay = 1
91
- for _ in range(max_retries):
92
- try:
93
- response = requests.put(upload_url, data=file_content, headers={'Content-Type': content_type})
94
- if response.status_code == 200:
95
- return True
96
- except Exception:
97
- pass
98
- await asyncio.sleep(delay)
99
- delay *= 2
100
- return False
 
101
 
102
  if __name__ == "__main__":
103
  import uvicorn
 
1
  from fastapi import FastAPI, File, UploadFile, Request
2
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, FileResponse
3
+ from fastapi.staticfiles import StaticFiles
4
+ import shutil
5
  import os
6
+ import uuid
7
+ import zipfile
8
+ from typing import List
9
+ import json
10
 
11
  app = FastAPI()
12
 
13
+ # Create directories if they don't exist
14
+ UPLOAD_DIR = "uploads"
15
+ ALBUM_DIR = "albums"
16
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
17
+ os.makedirs(ALBUM_DIR, exist_ok=True)
18
+
19
+ # Serve static files
20
+ app.mount("/static", StaticFiles(directory=UPLOAD_DIR), name="static")
21
+
22
  HTML_CONTENT = """
23
  <!DOCTYPE html>
24
  <html lang="en">
25
  <head>
26
  <meta charset="UTF-8">
27
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
28
+ <title>Album Upload</title>
29
  </head>
30
  <body>
31
+ <h1>Create Album</h1>
32
+ <form action="/create-album" method="post" enctype="multipart/form-data">
33
+ <input type="text" name="album_name" placeholder="Album Name" required><br><br>
34
+ <input type="file" name="files" accept="*/*" multiple required><br><br>
35
+ <button type="submit">Create Album</button>
36
  </form>
37
  </body>
38
  </html>
 
42
  async def index():
43
  return HTML_CONTENT
44
 
45
+ @app.post("/create-album")
46
+ async def create_album(album_name: str, files: List[UploadFile]):
47
+ if not files:
48
+ return JSONResponse({"error": "No files uploaded"}, status_code=400)
49
+
50
+ # Create unique album ID
51
+ album_id = str(uuid.uuid4())
52
+ album_path = os.path.join(ALBUM_DIR, album_id)
53
+ os.makedirs(album_path, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ # Save album metadata
56
+ album_info = {
57
+ "album_name": album_name,
58
+ "files": []
59
+ }
60
+
61
+ # Save uploaded files
62
+ for file in files:
63
+ file_path = os.path.join(album_path, file.filename)
64
+ with open(file_path, "wb") as buffer:
65
+ shutil.copyfileobj(file.file, buffer)
66
+ album_info["files"].append(file.filename)
67
+
68
+ # Save album metadata
69
+ with open(os.path.join(album_path, "album_info.json"), "w") as f:
70
+ json.dump(album_info, f)
71
 
72
+ album_url = f"/album/{album_id}"
73
+ return JSONResponse({
74
+ "message": "Album created successfully",
75
+ "album_url": album_url,
76
+ "share_url": f"/share/{album_id}"
77
+ })
78
 
79
+ @app.get("/album/{album_id}")
80
+ async def view_album(album_id: str):
81
+ album_path = os.path.join(ALBUM_DIR, album_id)
82
+ if not os.path.exists(album_path):
83
+ return JSONResponse({"error": "Album not found"}, status_code=404)
84
 
85
+ with open(os.path.join(album_path, "album_info.json")) as f:
86
+ album_info = json.load(f)
87
+
88
+ return HTMLResponse(f"""
89
+ <html>
90
+ <head><title>{album_info['album_name']}</title></head>
91
+ <body>
92
+ <h1>{album_info['album_name']}</h1>
93
+ <div>
94
+ <h3>Files:</h3>
95
+ <ul>
96
+ {"".join(f'<li><a href="/download/{album_id}/{file}">{file}</a></li>' for file in album_info['files'])}
97
+ </ul>
98
+ <a href="/download/{album_id}/all">Download All Files (ZIP)</a>
99
+ </div>
100
+ </body>
101
+ </html>
102
+ """)
103
 
104
+ @app.get("/share/{album_id}")
105
+ async def share_album(album_id: str, request: Request):
106
+ album_path = os.path.join(ALBUM_DIR, album_id)
107
+ if not os.path.exists(album_path):
108
+ return JSONResponse({"error": "Album not found"}, status_code=404)
109
+
110
+ base_url = str(request.base_url).rstrip('/')
111
+ share_url = f"{base_url}/album/{album_id}"
112
+ return JSONResponse({"share_url": share_url})
113
 
114
+ @app.get("/download/{album_id}/{filename}")
115
+ async def download_file(album_id: str, filename: str):
116
+ file_path = os.path.join(ALBUM_DIR, album_id, filename)
117
+ if not os.path.exists(file_path):
118
+ return JSONResponse({"error": "File not found"}, status_code=404)
119
+ return FileResponse(file_path, filename=filename)
 
 
 
120
 
121
+ @app.get("/download/{album_id}/all")
122
+ async def download_all(album_id: str):
123
+ album_path = os.path.join(ALBUM_DIR, album_id)
124
+ if not os.path.exists(album_path):
125
+ return JSONResponse({"error": "Album not found"}, status_code=404)
126
+
127
+ zip_path = os.path.join(album_path, "album.zip")
128
+ with zipfile.ZipFile(zip_path, 'w') as zipf:
129
+ for file in os.listdir(album_path):
130
+ if file != "album.zip" and file != "album_info.json":
131
+ zipf.write(os.path.join(album_path, file), file)
132
+
133
+ return FileResponse(zip_path, filename=f"album_{album_id}.zip")
134
 
135
  if __name__ == "__main__":
136
  import uvicorn