Spaces:
Sleeping
Sleeping
Download hf_backup.py from kishankrish19/Vision: direct link, hf CLI and curl.
- Browser
- Download file 14.5 kB
-
https://huggingface.co/spaces/kishankrish19/Vision/resolve/main/hf_backup.py
- Command line
-
hf download hf://spaces/kishankrish19/Vision/hf_backup.py
-
curl -L -o hf_backup.py https://huggingface.co/spaces/kishankrish19/Vision/resolve/main/hf_backup.py
14.5 kB
| """Consistent SQLite snapshots and private Hugging Face dataset persistence. | |
| Only space_server starts the worker. Local app.py stays entirely offline. | |
| The database and the original workbooks it references travel in one commit. | |
| """ | |
| from contextlib import closing | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import json | |
| import logging | |
| from pathlib import Path | |
| import re | |
| import shutil | |
| import sqlite3 | |
| import tempfile | |
| import threading | |
| import zipfile | |
| LOG = logging.getLogger(__name__) | |
| ARCHIVE_NAME = 'mom-state.zip' | |
| INTERVAL_SECONDS = 300 | |
| MAX_ARCHIVE_BYTES = 512 * 1024 * 1024 | |
| class BackupError(RuntimeError): | |
| """An actionable, credential-free configuration or persistence error.""" | |
| def utc_now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def sha256(path): | |
| with Path(path).open('rb') as handle: | |
| return hashlib.file_digest(handle, 'sha256').hexdigest() | |
| def read_database(path): | |
| return sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True, timeout=20) | |
| def referenced_imports(connection): | |
| names = set() | |
| for (source,) in connection.execute("SELECT source_file FROM meetings WHERE source_file LIKE 'upload:%'"): | |
| name = source.removeprefix('upload:') | |
| if not re.fullmatch(r'[a-f0-9]{32}\.xlsx', name): | |
| raise BackupError('The database contains an invalid imported workbook reference.') | |
| names.add('imports/' + name) | |
| return names | |
| def content_fingerprint(database, file_hashes): | |
| # Logical content avoids treating WAL checkpoint/header changes as user edits. | |
| digest = hashlib.sha256() | |
| with closing(read_database(database)) as connection: | |
| for statement in connection.iterdump(): | |
| digest.update(statement.encode('utf-8')) | |
| digest.update(b'\n') | |
| extras = {name: value for name, value in file_hashes.items() if name != 'mom.sqlite3'} | |
| digest.update(json.dumps(extras, sort_keys=True).encode('utf-8')) | |
| return digest.hexdigest() | |
| def snapshot(data_dir, staging): | |
| data_dir, staging = Path(data_dir), Path(staging) | |
| database = staging / 'mom.sqlite3' | |
| with closing(read_database(data_dir / 'mom.sqlite3')) as source: | |
| with closing(sqlite3.connect(database)) as target: | |
| source.backup(target) | |
| names = referenced_imports(target) | |
| if (data_dir / '.secret_key').is_file(): | |
| names.add('.secret_key') | |
| for name in names: | |
| target = staging / name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| # Missing referenced workbooks must fail the backup, never silently drop them. | |
| shutil.copyfile(data_dir / name, target) | |
| names.add('mom.sqlite3') | |
| hashes = {name: sha256(staging / name) for name in sorted(names)} | |
| manifest = dict(version=1, created_at=utc_now(), files=hashes, | |
| fingerprint=content_fingerprint(database, hashes)) | |
| manifest_json = json.dumps(manifest, sort_keys=True) | |
| if len(names) + 1 > 2000 or sum((staging / name).stat().st_size for name in names) + len(manifest_json.encode('utf-8')) > MAX_ARCHIVE_BYTES: | |
| raise BackupError('The snapshot exceeds the supported restore size; no incomplete backup was uploaded.') | |
| archive = staging / ARCHIVE_NAME | |
| with zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED) as output: | |
| output.writestr('manifest.json', manifest_json) | |
| for name in sorted(names): | |
| output.write(staging / name, name) | |
| return archive, manifest | |
| def validate_archive(archive, staging): | |
| """Validate everything in staging before touching any live data.""" | |
| staging = Path(staging) | |
| with zipfile.ZipFile(archive) as source: | |
| entries = source.infolist() | |
| names = {entry.filename for entry in entries} | |
| if len(entries) != len(names) or len(entries) > 2000: | |
| raise BackupError('Invalid backup file list.') | |
| if sum(entry.file_size for entry in entries) > MAX_ARCHIVE_BYTES: | |
| raise BackupError('The backup exceeds the supported restore size.') | |
| allowed = lambda name: name in {'mom.sqlite3', '.secret_key', 'manifest.json'} or bool( | |
| re.fullmatch(r'imports/[a-f0-9]{32}\.xlsx', name)) | |
| if not all(allowed(name) for name in names): | |
| raise BackupError('The backup contains an unexpected file path.') | |
| if not {'mom.sqlite3', 'manifest.json'} <= names: | |
| raise BackupError('The backup is missing its database or manifest.') | |
| manifest = json.loads(source.read('manifest.json')) | |
| if manifest.get('version') != 1 or set(manifest.get('files', {})) != names - {'manifest.json'}: | |
| raise BackupError('Unsupported or incomplete backup manifest.') | |
| for name, expected_hash in manifest['files'].items(): | |
| target = staging / name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| with source.open(name) as src, target.open('wb') as dst: | |
| shutil.copyfileobj(src, dst) | |
| if sha256(target) != expected_hash: | |
| raise BackupError('The backup failed checksum validation.') | |
| database = staging / 'mom.sqlite3' | |
| with closing(read_database(database)) as connection: | |
| if connection.execute('PRAGMA quick_check').fetchall() != [('ok',)]: | |
| raise BackupError('The saved database failed its integrity check.') | |
| tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='table'")} | |
| if not {'users', 'meetings', 'actions', 'updates', 'metadata'} <= tables: | |
| raise BackupError('The backup is not a MOM database.') | |
| if not referenced_imports(connection) <= names: | |
| raise BackupError('A workbook required by this backup is missing.') | |
| if content_fingerprint(database, manifest['files']) != manifest.get('fingerprint'): | |
| raise BackupError('The backup content does not match its manifest.') | |
| return manifest | |
| class HubDataset: | |
| """One Space per dataset, with optimistic commit checks against other writers.""" | |
| def __init__(self, repo_id, token): | |
| from huggingface_hub import HfApi | |
| self.repo_id = repo_id | |
| self.api = HfApi(token=token) | |
| self.revision = None | |
| self.uncertain_fingerprint = None | |
| def require_private(info): | |
| if not info.private: | |
| raise BackupError('HF_DATASET_REPO must be a private dataset. No data was uploaded.') | |
| if not info.sha: | |
| raise BackupError('The dataset has no initial commit. Add a README to it and restart.') | |
| def prepare(self): | |
| from huggingface_hub.errors import RepositoryNotFoundError | |
| try: | |
| info = self.api.repo_info(self.repo_id, repo_type='dataset') | |
| except RepositoryNotFoundError: | |
| self.api.create_repo(self.repo_id, repo_type='dataset', private=True, exist_ok=True) | |
| info = self.api.repo_info(self.repo_id, repo_type='dataset') | |
| self.require_private(info) | |
| self.api.auth_check(self.repo_id, repo_type='dataset', write=True) | |
| self.revision = info.sha | |
| if ARCHIVE_NAME not in {file.rfilename for file in info.siblings or []}: | |
| return None | |
| return self.download(info.sha) | |
| def download(self, revision): | |
| return Path(self.api.hf_hub_download(self.repo_id, ARCHIVE_NAME, repo_type='dataset', | |
| revision=revision, force_download=True)) | |
| def publish(self, archive, fingerprint): | |
| from huggingface_hub import CommitOperationAdd | |
| info = self.api.repo_info(self.repo_id, repo_type='dataset') | |
| self.require_private(info) | |
| if info.sha != self.revision: | |
| # A connection may fail after the server committed successfully. | |
| # Adopt that revision only if it contains our exact attempted snapshot. | |
| if self.uncertain_fingerprint: | |
| with zipfile.ZipFile(self.download(info.sha)) as saved: | |
| remote = json.loads(saved.read('manifest.json')) | |
| if remote.get('fingerprint') == self.uncertain_fingerprint: | |
| self.revision = info.sha | |
| if fingerprint == self.uncertain_fingerprint: | |
| self.uncertain_fingerprint = None | |
| return | |
| if info.sha != self.revision: | |
| raise BackupError('Dataset changed elsewhere. Use only one running Space per dataset.') | |
| self.uncertain_fingerprint = fingerprint | |
| result = self.api.create_commit( | |
| repo_id=self.repo_id, repo_type='dataset', revision='main', parent_commit=self.revision, | |
| operations=[CommitOperationAdd(path_in_repo=ARCHIVE_NAME, path_or_fileobj=str(archive))], | |
| commit_message='Save MOM data snapshot') | |
| self.revision = result.oid | |
| self.uncertain_fingerprint = None | |
| class DatasetBackup: | |
| def __init__(self, data_dir, backend, interval=INTERVAL_SECONDS): | |
| self.data_dir = Path(data_dir) | |
| self.backend = backend | |
| self.interval = interval | |
| self.last_fingerprint = None | |
| self.last_success = None | |
| self.last_check = None | |
| self.error = None | |
| self.restored = False | |
| self._stop = threading.Event() | |
| self._lock = threading.Lock() | |
| self._thread = None | |
| def marker(self): | |
| return self.data_dir / '.hf-backup.json' | |
| def _save_marker(self): | |
| temporary = self.marker.with_suffix('.tmp') | |
| temporary.write_text(json.dumps(dict(repo=self.backend.repo_id, revision=self.backend.revision, | |
| fingerprint=self.last_fingerprint, last_success=self.last_success)), | |
| encoding='utf-8') | |
| temporary.replace(self.marker) | |
| def restore(self): | |
| """Must run before Flask opens or seeds the database. Network errors propagate.""" | |
| self.data_dir.mkdir(parents=True, exist_ok=True) | |
| archive = self.backend.prepare() | |
| marker = json.loads(self.marker.read_text(encoding='utf-8')) if self.marker.exists() else {} | |
| if marker and marker.get('repo') != self.backend.repo_id: | |
| raise BackupError('This data folder belongs to another dataset. Use a separate MOM_DATA_DIR.') | |
| if archive is None: | |
| if marker.get('fingerprint'): | |
| raise BackupError('The previous remote backup is missing. Restore it before starting.') | |
| return | |
| with tempfile.TemporaryDirectory(prefix='mom-restore-', dir=self.data_dir) as folder: | |
| staging = Path(folder) | |
| manifest = validate_archive(archive, staging) | |
| if (self.data_dir / 'mom.sqlite3').exists(): | |
| # Keep pending local edits only when they descend from the same remote revision. | |
| known_revision = marker.get('revision') == self.backend.revision | |
| if not known_revision: | |
| with tempfile.TemporaryDirectory(prefix='mom-compare-', dir=self.data_dir) as compare: | |
| _, local = snapshot(self.data_dir, compare) | |
| if local['fingerprint'] != manifest['fingerprint']: | |
| raise BackupError('Local and dataset databases differ. Preserve both and choose a fresh data folder or dataset.') | |
| else: | |
| if any((self.data_dir / ('mom.sqlite3' + suffix)).exists() for suffix in ('-wal', '-shm')): | |
| raise BackupError('Orphaned SQLite recovery files found. Preserve them before restoring.') | |
| for name in manifest['files']: | |
| if name == 'mom.sqlite3': | |
| continue | |
| target = self.data_dir / name | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| (staging / name).replace(target) | |
| # Publish database last, after every dependent workbook is in place. | |
| (staging / 'mom.sqlite3').replace(self.data_dir / 'mom.sqlite3') | |
| self.restored = True | |
| self.last_fingerprint = manifest['fingerprint'] | |
| self.last_success = manifest['created_at'] | |
| self._save_marker() | |
| def sync_once(self): | |
| with self._lock: | |
| try: | |
| with tempfile.TemporaryDirectory(prefix='mom-backup-', dir=self.data_dir) as folder: | |
| archive, manifest = snapshot(self.data_dir, folder) | |
| self.last_check = utc_now() | |
| if manifest['fingerprint'] == self.last_fingerprint: | |
| self.error = None | |
| return False | |
| self.backend.publish(archive, manifest['fingerprint']) | |
| # Never mark newer writes, made during upload, as backed up. | |
| self.last_fingerprint = manifest['fingerprint'] | |
| self.last_success = utc_now() | |
| self._save_marker() | |
| self.error = None | |
| LOG.info('MOM dataset backup saved successfully.') | |
| return True | |
| except Exception as error: | |
| # Do not emit SDK exception text: it may contain request URLs or credentials. | |
| self.error = 'backup_failed' | |
| LOG.error('MOM backup failed (%s); pending data will be retried on the next interval.', type(error).__name__) | |
| return False | |
| def start(self): | |
| if self._thread is not None: | |
| raise RuntimeError('Backup worker already started') | |
| def run(): | |
| while not self._stop.wait(self.interval): | |
| self.sync_once() | |
| self._thread = threading.Thread(target=run, name='mom-dataset-backup', daemon=True) | |
| self._thread.start() | |
| def stop(self, flush=True): | |
| self._stop.set() | |
| if self._thread: | |
| self._thread.join(timeout=20) | |
| if self._thread.is_alive(): | |
| LOG.warning('Backup still in progress at shutdown; final flush could not start.') | |
| return | |
| if flush: | |
| self.sync_once() | |
| def status(self): | |
| return dict(enabled=True, state='degraded' if self.error else ('ok' if self.last_success else 'pending'), | |
| interval_seconds=self.interval, last_success_at=self.last_success, | |
| last_checked_at=self.last_check, restored_on_startup=self.restored, | |
| error=self.error, worker_running=bool(self._thread and self._thread.is_alive())) | |