Messenger_back_database / media_storage.py
Nrighton233j
Add media upload (HF dataset storage), voice transcription, media-aware messaging
fd8cbb1
Raw
History Blame Contribute Delete
1.16 kB
"""
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}"