Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 4 |
+
from internetarchive import upload
|
| 5 |
+
|
| 6 |
+
# Load keys from environment variables
|
| 7 |
+
IA_ACCESS_KEY = os.getenv("YXzY5OrREXLL6XBh")
|
| 8 |
+
IA_SECRET_KEY = os.getenv("m2XnL3X7xCB1pNGE")
|
| 9 |
+
|
| 10 |
+
if not IA_ACCESS_KEY or not IA_SECRET_KEY:
|
| 11 |
+
raise RuntimeError("Internet Archive keys not set in environment variables")
|
| 12 |
+
|
| 13 |
+
app = FastAPI(title="Internet Archive Image Upload API")
|
| 14 |
+
|
| 15 |
+
@app.post("/upload")
|
| 16 |
+
async def upload_image(file: UploadFile = File(...)):
|
| 17 |
+
if not file.content_type.startswith("image/"):
|
| 18 |
+
raise HTTPException(status_code=400, detail="Only image files allowed")
|
| 19 |
+
|
| 20 |
+
# Save file temporarily
|
| 21 |
+
temp_filename = f"/tmp/{uuid.uuid4()}_{file.filename}"
|
| 22 |
+
with open(temp_filename, "wb") as f:
|
| 23 |
+
f.write(await file.read())
|
| 24 |
+
|
| 25 |
+
# Unique identifier for IA
|
| 26 |
+
identifier = f"img-upload-{uuid.uuid4()}"
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
upload(
|
| 30 |
+
identifier=identifier,
|
| 31 |
+
files=temp_filename,
|
| 32 |
+
access_key=IA_ACCESS_KEY,
|
| 33 |
+
secret_key=IA_SECRET_KEY,
|
| 34 |
+
metadata={
|
| 35 |
+
"mediatype": "image",
|
| 36 |
+
"title": file.filename
|
| 37 |
+
}
|
| 38 |
+
)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 41 |
+
finally:
|
| 42 |
+
os.remove(temp_filename)
|
| 43 |
+
|
| 44 |
+
# Direct download URL
|
| 45 |
+
url = f"https://archive.org/download/{identifier}/{file.filename}"
|
| 46 |
+
|
| 47 |
+
return {
|
| 48 |
+
"success": True,
|
| 49 |
+
"identifier": identifier,
|
| 50 |
+
"filename": file.filename,
|
| 51 |
+
"url": url
|
| 52 |
+
}
|