File size: 3,181 Bytes
bcfb8cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Hugging Face Docker Space entry point: restore, initialize, serve, back up."""
import logging
import os
from pathlib import Path
import signal

from hf_backup import BackupError, DatasetBackup, HubDataset

LOG = logging.getLogger(__name__)


def settings(environ=None):
    env = os.environ if environ is None else environ
    token = env.get('hf_token') or env.get('HF_TOKEN')
    repo = env.get('HF_DATASET_REPO') or (env.get('SPACE_ID', '') + '-data' if env.get('SPACE_ID') else '')
    if not token:
        raise BackupError('Add hf_token (or HF_TOKEN) as a Space Secret with write access to your private dataset.')
    if not repo or repo.count('/') != 1:
        raise BackupError('Set HF_DATASET_REPO to owner/dataset-name, or run inside a Space with SPACE_ID.')
    return token, repo


def build_space_app(data_dir, backend):
    from app import create_app
    backup = DatasetBackup(data_dir, backend)
    backup.restore()
    app = create_app({'DATABASE': str(Path(data_dir) / 'mom.sqlite3'), 'HF_SPACE': True,
                      'SESSION_COOKIE_SECURE': True, 'SESSION_COOKIE_SAMESITE': 'None',
                      'SESSION_COOKIE_PARTITIONED': True})
    app.extensions['dataset_backup'] = backup
    return app, backup


def main():
    from filelock import FileLock, Timeout
    from waitress import create_server
    logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
    # Keep third-party request logs out of the public Space logs.
    for logger in ('httpx', 'httpx2', 'huggingface_hub'):
        logging.getLogger(logger).setLevel(logging.ERROR)
    try:
        token, repo = settings()
        directory = Path(os.environ.get('MOM_DATA_DIR', Path(__file__).resolve().parent / 'data'))
        directory.mkdir(parents=True, exist_ok=True)
        # One process owns the restore/sync lifecycle. This is not a multi-worker service.
        with FileLock(str(directory / '.space.lock'), timeout=0):
            app, backup = build_space_app(directory, HubDataset(repo, token))
            server = create_server(app, host='0.0.0.0', port=int(os.environ.get('PORT', '7860')), threads=4)
            def shutdown(signum, frame):
                raise SystemExit(0)
            signal.signal(signal.SIGTERM, shutdown)
            signal.signal(signal.SIGINT, shutdown)
            backup.start()
            LOG.info('MOM is ready. Health endpoint: /health. Dataset backup interval: 300 seconds.')
            try:
                server.run()
            finally:
                server.close()
                server.task_dispatcher.shutdown(cancel_pending=False, timeout=15)
                backup.stop(flush=True)
    except BackupError as error:
        LOG.error('%s', error)
        raise SystemExit(1) from None
    except Timeout:
        LOG.error('Another Space server is already using this data folder.')
        raise SystemExit(1) from None
    except Exception as error:
        LOG.error('Space startup stopped (%s). Check Secret permissions, dataset access and network availability. Existing data was preserved.', type(error).__name__)
        raise SystemExit(1) from None


if __name__ == '__main__':
    main()