Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 2 |
+
from huggingface_hub import HfApi, login
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
app = FastAPI()
|
| 6 |
+
|
| 7 |
+
# Replace with your Hugging Face token or set it as an environment variable
|
| 8 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 9 |
+
REPO_ID = os.getenv("HF_REPO_ID") # Replace with your model repo ID
|
| 10 |
+
|
| 11 |
+
# Log in to Hugging Face once during app startup
|
| 12 |
+
@app.on_event("startup")
|
| 13 |
+
async def startup_event():
|
| 14 |
+
login(token=HF_TOKEN)
|
| 15 |
+
|
| 16 |
+
@app.post("/upload/")
|
| 17 |
+
async def upload_file(file: UploadFile = File(...)):
|
| 18 |
+
try:
|
| 19 |
+
# Initialize Hugging Face API
|
| 20 |
+
api = HfApi()
|
| 21 |
+
|
| 22 |
+
# Save the uploaded file temporarily
|
| 23 |
+
temp_file_path = f"/tmp/{file.filename}"
|
| 24 |
+
with open(temp_file_path, "wb") as temp_file:
|
| 25 |
+
temp_file.write(await file.read())
|
| 26 |
+
|
| 27 |
+
# Upload the file to the Hugging Face model repository
|
| 28 |
+
api.upload_file(
|
| 29 |
+
path_or_fileobj=temp_file_path,
|
| 30 |
+
path_in_repo=file.filename, # File will be uploaded with its original name
|
| 31 |
+
repo_id=REPO_ID,
|
| 32 |
+
repo_type="model",
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# Clean up temporary file
|
| 36 |
+
os.remove(temp_file_path)
|
| 37 |
+
|
| 38 |
+
return {"message": f"File '{file.filename}' uploaded successfully to {REPO_ID}"}
|
| 39 |
+
except Exception as e:
|
| 40 |
+
raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
|
| 41 |
+
|
| 42 |
+
@app.get("/")
|
| 43 |
+
async def root():
|
| 44 |
+
return {"message": "Welcome to the Hugging Face File Upload API"}
|