File size: 1,162 Bytes
fd8cbb1 | 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 | """
media_storage.py — uploads message media (images, voice notes) to a
Hugging Face dataset repo instead of the Space's own disk, keeping the
persistent disk free for the SQLite database only.
"""
import os
import time
from huggingface_hub import HfApi
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("Hf_token")
MEDIA_DATASET_REPO = os.environ.get("MEDIA_DATASET_REPO", "Brighton233j/Media-image-voice")
_api = HfApi(token=HF_TOKEN) if HF_TOKEN else None
def upload_media(file_bytes: bytes, filename: str, user_id: int) -> str:
"""Uploads a file to the media dataset repo and returns its public URL."""
if _api is None:
raise RuntimeError("HF_TOKEN is not configured — cannot upload media")
ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else "bin"
safe_name = f"user{user_id}_{int(time.time())}.{ext}"
path_in_repo = f"media/{safe_name}"
_api.upload_file(
path_or_fileobj=file_bytes,
path_in_repo=path_in_repo,
repo_id=MEDIA_DATASET_REPO,
repo_type="dataset",
)
return f"https://huggingface.co/datasets/{MEDIA_DATASET_REPO}/resolve/main/{path_in_repo}"
|