CounselingLog / db_sync.py
devorah-ai-2016's picture
Upload db_sync.py
56dd3d3 verified
Raw History Blame Contribute Delete
2.42 kB
import os
import shutil
from huggingface_hub import hf_hub_download, HfApi
REPO_ID = "devorah-ai-2016/ClientCenter"
def get_hf_token():
# 1. Check environment variable (set on HF spaces)
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
if token:
return token.strip()
# 2. Check local token files (for local testing)
token_candidates = [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "huggingfacetoken.txt"),
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "huggingfacetoken.txt"),
"/Users/devorah/connect/Beecarewebsite/huggingfacetoken.txt",
os.path.expanduser("~/.cache/huggingface/token")
]
for path in token_candidates:
if os.path.exists(path):
try:
with open(path, "r") as f:
t = f.read().strip()
if t:
return t
except Exception:
pass
return None
def download_db(db_path):
token = get_hf_token()
if not token:
print("HF_TOKEN not found, skipping download.")
return False
try:
os.makedirs(os.path.dirname(db_path), exist_ok=True)
# Download from HF space (repo_type="space")
downloaded_path = hf_hub_download(
repo_id=REPO_ID,
filename="data/clients.db",
repo_type="space",
token=token
)
# Copy to the local path
shutil.copy(downloaded_path, db_path)
print(f"Downloaded clients.db from {REPO_ID} to {db_path}")
return True
except Exception as e:
print(f"Failed to download database: {e}")
return False
def upload_db(db_path):
token = get_hf_token()
if not token:
print("HF_TOKEN not found, skipping upload.")
return False
try:
if not os.path.exists(db_path):
print(f"Local database {db_path} does not exist. Cannot upload.")
return False
api = HfApi()
api.upload_file(
path_or_fileobj=db_path,
path_in_repo="data/clients.db",
repo_id=REPO_ID,
repo_type="space",
token=token
)
print(f"Uploaded clients.db to {REPO_ID}")
return True
except Exception as e:
print(f"Failed to upload database: {e}")
return False