Spaces:
Runtime error
Runtime error
Third commit
Browse files
main.py
CHANGED
|
@@ -8,27 +8,34 @@ from datetime import datetime
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
|
|
|
| 11 |
UPLOAD_DIR = "/tmp/uploads"
|
| 12 |
-
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 13 |
-
|
| 14 |
-
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 15 |
-
templates = Jinja2Templates(directory="templates")
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
@app.post("/upload")
|
| 19 |
async def upload_image(file: UploadFile = File(...)):
|
|
|
|
| 20 |
filename = datetime.now().strftime("%Y%m%d_%H%M%S_") + file.filename
|
| 21 |
file_path = os.path.join(UPLOAD_DIR, filename)
|
|
|
|
|
|
|
| 22 |
with open(file_path, "wb") as buffer:
|
| 23 |
shutil.copyfileobj(file.file, buffer)
|
|
|
|
| 24 |
return {"message": "Image uploaded", "filename": filename}
|
| 25 |
|
| 26 |
-
|
| 27 |
@app.get("/gallery", response_class=HTMLResponse)
|
| 28 |
async def show_gallery(request: Request):
|
|
|
|
| 29 |
images = os.listdir(UPLOAD_DIR)
|
| 30 |
images.sort(reverse=True) # Newest first
|
| 31 |
-
recent_images = images[:5] # Only the latest 5
|
|
|
|
|
|
|
| 32 |
return templates.TemplateResponse("gallery.html", {"request": request, "images": recent_images})
|
| 33 |
|
| 34 |
@app.get("/")
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
# Temporary directory for uploaded images
|
| 12 |
UPLOAD_DIR = "/tmp/uploads"
|
| 13 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True) # Ensure the directory is created
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Mount static directory to serve images from the upload folder
|
| 16 |
+
app.mount("/static", StaticFiles(directory=UPLOAD_DIR), name="static")
|
| 17 |
+
templates = Jinja2Templates(directory="app/templates")
|
| 18 |
|
| 19 |
@app.post("/upload")
|
| 20 |
async def upload_image(file: UploadFile = File(...)):
|
| 21 |
+
# Create a unique filename with timestamp to avoid overwriting
|
| 22 |
filename = datetime.now().strftime("%Y%m%d_%H%M%S_") + file.filename
|
| 23 |
file_path = os.path.join(UPLOAD_DIR, filename)
|
| 24 |
+
|
| 25 |
+
# Save the file to the temporary directory
|
| 26 |
with open(file_path, "wb") as buffer:
|
| 27 |
shutil.copyfileobj(file.file, buffer)
|
| 28 |
+
|
| 29 |
return {"message": "Image uploaded", "filename": filename}
|
| 30 |
|
|
|
|
| 31 |
@app.get("/gallery", response_class=HTMLResponse)
|
| 32 |
async def show_gallery(request: Request):
|
| 33 |
+
# List files in the upload directory and sort by the latest
|
| 34 |
images = os.listdir(UPLOAD_DIR)
|
| 35 |
images.sort(reverse=True) # Newest first
|
| 36 |
+
recent_images = images[:5] # Only show the latest 5 images
|
| 37 |
+
|
| 38 |
+
# Render the gallery template
|
| 39 |
return templates.TemplateResponse("gallery.html", {"request": request, "images": recent_images})
|
| 40 |
|
| 41 |
@app.get("/")
|