File size: 3,239 Bytes
7e22793
 
 
 
a5af344
 
 
7e22793
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35c2f39
 
 
 
b020c6c
 
 
 
35c2f39
 
 
 
 
 
 
 
 
 
b020c6c
 
 
 
 
 
35c2f39
 
b020c6c
35c2f39
 
 
 
 
b020c6c
35c2f39
 
 
 
b020c6c
35c2f39
 
 
 
 
 
b020c6c
35c2f39
 
 
 
b020c6c
 
 
 
 
35c2f39
 
 
 
 
 
7e22793
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from huggingface_hub import upload_file
import os
import os
import zipfile
import tempfile  # βœ… Add this!
app = FastAPI()

# CORS setup to allow requests from your frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Replace "*" with your frontend domain in production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
def health_check():
    return {"status": "βœ… FastAPI running on Hugging Face Spaces!"}





from datetime import datetime
import tempfile
import uuid

@app.post("/upload-zip")
async def upload_zip(file: UploadFile = File(...)):
    if not file.filename.endswith(".zip"):
        return {"error": "Please upload a .zip file"}

    # Save the ZIP to /tmp
    temp_zip_path = f"/tmp/{file.filename}"
    with open(temp_zip_path, "wb") as f:
        f.write(await file.read())

    # Create a unique subfolder name inside 'demo/'
    timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
    unique_id = uuid.uuid4().hex[:6]
    folder_name = f"upload_{timestamp}_{unique_id}"
    hf_folder_prefix = f"demo/{folder_name}"

    try:
        with tempfile.TemporaryDirectory() as extract_dir:
            # Extract zip
            with zipfile.ZipFile(temp_zip_path, 'r') as zip_ref:
                zip_ref.extractall(extract_dir)

            uploaded_files = []

            # Upload all extracted files
            for root_dir, _, files in os.walk(extract_dir):
                for name in files:
                    file_path = os.path.join(root_dir, name)
                    relative_path = os.path.relpath(file_path, extract_dir)
                    repo_path = f"{hf_folder_prefix}/{relative_path}".replace("\\", "/")

                    upload_file(
                        path_or_fileobj=file_path,
                        path_in_repo=repo_path,
                        repo_id="rahul7star/ohamlab",
                        repo_type="model",
                        commit_message=f"Upload {relative_path} to {folder_name}",
                        token=True,
                    )
                    uploaded_files.append(repo_path)

        return {
            "message": f"βœ… Uploaded {len(uploaded_files)} files",
            "folder": folder_name,
            "files": uploaded_files,
        }

    except Exception as e:
        return {"error": f"❌ Failed to process zip: {str(e)}"}

    

@app.post("/upload")
async def upload_image(file: UploadFile = File(...)):
    filename = file.filename
    contents = await file.read()

    # Save temporarily
    temp_path = f"/tmp/{filename}"
    with open(temp_path, "wb") as f:
        f.write(contents)

    try:
        upload_file(
            path_or_fileobj=temp_path,
            path_in_repo=f"demo/{filename}",
            repo_id="rahul7star/ohamlab",
            repo_type="model",
            commit_message=f"Upload {filename} to demo folder",
            token=True,  # uses HF_TOKEN from Space secrets
        )
        return {"message": f"βœ… {filename} uploaded successfully!"}
    except Exception as e:
        return {"error": f"❌ Upload failed: {str(e)}"}