Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, BackgroundTasks
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
import shutil
|
| 4 |
+
import os
|
| 5 |
+
import uuid
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
TEMP_DIR = Path("/tmp/uploads")
|
| 11 |
+
TEMP_DIR.mkdir(parents=True, exist_ok=True)
|
| 12 |
+
|
| 13 |
+
# Background cleanup: delete files older than 1 hour
|
| 14 |
+
def cleanup_old_files():
|
| 15 |
+
now = time.time()
|
| 16 |
+
for f in TEMP_DIR.iterdir():
|
| 17 |
+
if now - f.stat().st_mtime > 3600:
|
| 18 |
+
try:
|
| 19 |
+
f.unlink()
|
| 20 |
+
except Exception:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
@app.get("/", response_class=HTMLResponse)
|
| 24 |
+
async def main():
|
| 25 |
+
html_path = Path(__file__).parent / "static" / "index.html"
|
| 26 |
+
return html_path.read_text()
|
| 27 |
+
|
| 28 |
+
@app.post("/upload")
|
| 29 |
+
async def upload_temp_file(
|
| 30 |
+
background_tasks: BackgroundTasks,
|
| 31 |
+
file: UploadFile = File(...),
|
| 32 |
+
):
|
| 33 |
+
# schedule cleanup
|
| 34 |
+
background_tasks.add_task(cleanup_old_files)
|
| 35 |
+
|
| 36 |
+
unique_name = f"{uuid.uuid4()}_{file.filename}"
|
| 37 |
+
dest_path = TEMP_DIR / unique_name
|
| 38 |
+
|
| 39 |
+
with dest_path.open("wb") as buf:
|
| 40 |
+
shutil.copyfileobj(file.file, buf)
|
| 41 |
+
|
| 42 |
+
return {"filename": unique_name, "url": f"/files/{unique_name}"}
|
| 43 |
+
|
| 44 |
+
@app.get("/files/{filename}")
|
| 45 |
+
async def serve_file(filename: str):
|
| 46 |
+
file_path = TEMP_DIR / filename
|
| 47 |
+
if not file_path.exists():
|
| 48 |
+
return {"error": "File not found"}
|
| 49 |
+
return FileResponse(str(file_path))
|