Spaces:
Sleeping
Sleeping
File size: 1,569 Bytes
67c8aca | 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 | import os
from huggingface_hub import HfApi
from dotenv import load_dotenv
load_dotenv()
def sync_db_to_hf():
"""
Syncs the local SQLite database to a Hugging Face repository.
This is useful for persisting data on ephemeral Hugging Face Spaces.
"""
token = os.getenv("HF_TOKEN")
repo_id = os.getenv("HF_REPO_ID") # e.g., "username/space-name"
# Hugging Face Spaces automatically provide SPACE_ID
if not repo_id:
repo_id = os.getenv("SPACE_ID")
if not token or not repo_id:
print("HF_Sync: Missing HF_TOKEN or HF_REPO_ID. Skipping sync.")
return False
# Get the db path from database.py logic
# We'll just use the constant path if it exists
db_path = "/app/data/loan_db.db"
# Fallback to local if not in docker
if not os.path.exists("/app/data"):
db_path = "./loan_db_v3.db"
if not os.path.exists(db_path):
print(f"HF_Sync: Database file not found at {db_path}. Skipping.")
return False
try:
api = HfApi(token=token)
print(f"HF_Sync: Uploading {db_path} to {repo_id}...")
api.upload_file(
path_or_fileobj=db_path,
path_in_repo="data/loan_db_backup.db",
repo_id=repo_id,
repo_type="space" # Assuming it's a space, but could be 'dataset'
)
print("HF_Sync: Database successfully synced to Hugging Face Space.")
return True
except Exception as e:
print(f"HF_Sync: Error during synchronization: {e}")
return False
|