Create storage.py
Browse files- storage.py +56 -0
storage.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from huggingface_hub import HfApi, create_bucket, list_bucket_tree
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # 在 Space Secrets 中设置
|
| 6 |
+
BUCKET_ID = os.environ.get("HF_BUCKET_ID", "your-username/learning-platform-data")
|
| 7 |
+
|
| 8 |
+
api = HfApi(token=HF_TOKEN)
|
| 9 |
+
|
| 10 |
+
def ensure_bucket():
|
| 11 |
+
"""确保 Bucket 存在"""
|
| 12 |
+
try:
|
| 13 |
+
create_bucket(BUCKET_ID, private=True)
|
| 14 |
+
except Exception:
|
| 15 |
+
pass # 已存在
|
| 16 |
+
|
| 17 |
+
def upload_file(file_bytes: bytes, filename: str, username: str, content_type: str) -> str:
|
| 18 |
+
"""上传文件到 Bucket,返回存储路径"""
|
| 19 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 20 |
+
safe_name = f"{timestamp}_{filename}"
|
| 21 |
+
bucket_path = f"users/{username}/{safe_name}"
|
| 22 |
+
|
| 23 |
+
from huggingface_hub import batch_bucket_files
|
| 24 |
+
import tempfile
|
| 25 |
+
|
| 26 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=f"_{filename}") as tmp:
|
| 27 |
+
tmp.write(file_bytes)
|
| 28 |
+
tmp_path = tmp.name
|
| 29 |
+
|
| 30 |
+
batch_bucket_files(
|
| 31 |
+
BUCKET_ID,
|
| 32 |
+
add=[(tmp_path, bucket_path)]
|
| 33 |
+
)
|
| 34 |
+
os.unlink(tmp_path)
|
| 35 |
+
return bucket_path
|
| 36 |
+
|
| 37 |
+
def list_user_files(username: str) -> list:
|
| 38 |
+
"""列出用户的所有文件"""
|
| 39 |
+
try:
|
| 40 |
+
tree = list_bucket_tree(BUCKET_ID, prefix=f"users/{username}/")
|
| 41 |
+
return [item.rfilename for item in tree if hasattr(item, 'rfilename')]
|
| 42 |
+
except Exception:
|
| 43 |
+
return []
|
| 44 |
+
|
| 45 |
+
def download_file(bucket_path: str) -> str:
|
| 46 |
+
"""下载文件到本地临时路径,返回本地路径"""
|
| 47 |
+
from huggingface_hub import hf_hub_download
|
| 48 |
+
return hf_hub_download(
|
| 49 |
+
repo_id=BUCKET_ID.replace("/", "_"),
|
| 50 |
+
filename=bucket_path,
|
| 51 |
+
repo_type="bucket"
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def get_file_url(bucket_path: str) -> str:
|
| 55 |
+
"""获取文件的下载 URL"""
|
| 56 |
+
return f"https://huggingface.co/buckets/{BUCKET_ID}/resolve/main/{bucket_path}"
|