Spaces:
Sleeping
Sleeping
| 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 | |