File size: 999 Bytes
af6d193
 
a125e15
 
af6d193
a125e15
af6d193
a125e15
af6d193
d3d30d9
af6d193
a125e15
af6d193
a125e15
dffffa1
af6d193
 
 
 
dffffa1
af6d193
 
dffffa1
af6d193
 
 
 
 
dffffa1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from fastapi import FastAPI, File, UploadFile
from huggingface_hub import HfApi
import os

# Initialize FastAPI app
app = FastAPI()
api = HfApi()

# Get repo_id and token from environment variables (secrets)
repo_id = os.getenv("HF_REPO_ID")  # Set in Space secrets (e.g., "username/my-model")
token = os.getenv("HF_TOKEN")      # Set in Space secrets

# --- FastAPI Endpoint ---
@app.post("/upload/")
async def upload_file(folder_name: str, file: UploadFile = File(...)):
    file_path = f"/tmp/temp_{file.filename}"
    with open(file_path, "wb") as f:
        f.write(await file.read())
    
    # Upload to Hugging Face with dynamic folder name provided by the user
    api.upload_file(
        path_or_fileobj=file_path,
        path_in_repo=f"{folder_name}/{file.filename}",  # Dynamic folder name
        repo_id=repo_id,
        repo_type="model",
        token=token
    )
    os.remove(file_path)
    return {"message": f"File uploaded as {file.filename} to {folder_name}/{file.filename}"}