Spaces:
Sleeping
Sleeping
Download deploy.py from Win786/careercompass: direct link, hf CLI and curl.
- Browser
- Download file 8.67 kB
-
https://huggingface.co/spaces/Win786/careercompass/resolve/main/deploy.py
- Command line
-
hf download hf://spaces/Win786/careercompass/deploy.py
-
curl -L -o deploy.py https://huggingface.co/spaces/Win786/careercompass/resolve/main/deploy.py
8.67 kB
| #!/usr/bin/env python3 | |
| """Single-container FalkorDB + Gradio supervisor for CPU-only Spaces. | |
| --prepare: fetch/verify pinned public sources, no database. | |
| --build: load and save an image seed, no UI. | |
| Default: restore seed, initialize if needed, give UI read-only credentials, | |
| and stop both children on SIGTERM/SIGINT or if either process fails. | |
| """ | |
| import argparse | |
| import hashlib | |
| import importlib.util | |
| import json | |
| import os | |
| from pathlib import Path | |
| import secrets | |
| import shutil | |
| import signal | |
| import subprocess | |
| import sys | |
| import time | |
| from urllib.request import Request, urlopen | |
| from redis.exceptions import RedisError | |
| from falkordb import FalkorDB | |
| import falkordb_ingest as ingest | |
| ROOT = Path(__file__).resolve().parent | |
| GRAPH = 'careercompass_onet_31_0' | |
| def sources(folder): | |
| """Never accept a corrupt download or silently change a pinned release.""" | |
| folder.mkdir(parents=True, exist_ok=True) | |
| records = json.loads((ROOT / 'sources.json').read_text())['files'] | |
| vendor = ROOT / 'vendor' | |
| for item in records: | |
| path = folder / item['name'] | |
| if not path.exists(): | |
| vendored = vendor / item['name'] | |
| if vendored.is_file() and hashlib.sha256(vendored.read_bytes()).hexdigest() == item['sha256']: | |
| print('Using vendored source:', item['name'], flush=True) | |
| shutil.copyfile(vendored, path) | |
| continue | |
| print('Downloading official source:', item['name'], flush=True) | |
| last = None | |
| for attempt in range(3): | |
| try: | |
| req = Request(item['url'], headers={ | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36', | |
| 'Accept': '*/*', | |
| }) | |
| with urlopen(req, timeout=45) as response: | |
| data = response.read(30 * 1024 * 1024 + 1) | |
| if len(data) > 30 * 1024 * 1024 or hashlib.sha256(data).hexdigest() != item['sha256']: | |
| raise ValueError('Source checksum mismatch: ' + item['name']) | |
| temporary = path.with_suffix(path.suffix + '.part') | |
| temporary.write_bytes(data) | |
| temporary.replace(path) | |
| break | |
| except OSError as exc: | |
| last = exc | |
| if attempt < 2: | |
| time.sleep(attempt + 1) | |
| else: | |
| if item.get('optional'): | |
| print('WARNING: optional source unavailable, continuing without it:', | |
| item['name'], flush=True) | |
| continue | |
| raise RuntimeError('Official source unavailable: ' + item['url']) from last | |
| if hashlib.sha256(path.read_bytes()).hexdigest() != item['sha256']: | |
| raise ValueError('Source checksum mismatch: ' + str(path)) | |
| print('Verified', len(records), 'official source files', flush=True) | |
| def fingerprint(): | |
| digest = hashlib.sha256() | |
| for name in ('sources.json', 'falkordb_ingest.py', 'schema.cypher', 'requirements.txt'): | |
| digest.update((ROOT / name).read_bytes()) | |
| return digest.hexdigest() | |
| def ready_graph(db, graph, source_dir): | |
| expected = fingerprint() | |
| ready = [] | |
| if db.connection.exists(GRAPH): | |
| ready = graph.ro_query('MATCH (d:Dataset {id:"onet-31.0"}) RETURN d.ready_fingerprint').result_set | |
| if ready != [[expected]]: | |
| print('Initializing graph from inspected sources', flush=True) | |
| sources(source_dir) | |
| model = ingest.build(ingest.inspect_all(source_dir)) | |
| wage_path = source_dir / 'oesm25nat.zip' | |
| if wage_path.is_file(): | |
| ingest.add_wages(model, wage_path) | |
| else: | |
| print('No wage file available; annual wages will be unavailable', flush=True) | |
| ingest.load(db, graph, model, ROOT / 'schema.cypher', 500) | |
| del model | |
| # Mark ready only after all batches and counts pass. | |
| verify_graph(graph) | |
| graph.query('MATCH (d:Dataset {id:"onet-31.0"}) SET d.ready_fingerprint=$value', params={'value': expected}) | |
| db.connection.save() | |
| print('Graph initialized and snapshot saved', flush=True) | |
| else: | |
| verify_graph(graph) | |
| print('Verified existing graph; ingestion skipped', flush=True) | |
| def verify_graph(graph): | |
| occupations = graph.ro_query('MATCH (o:Occupation) RETURN count(o),count(o.median_annual_wage)').result_set[0] | |
| edges = graph.ro_query('MATCH ()-[r]->() RETURN count(r)').result_set[0][0] | |
| if occupations[0] != 1016 or occupations[1] not in (0, 956) or edges != 242797: | |
| raise RuntimeError(f'Incomplete graph: occupations/wages={occupations}, relationships={edges}') | |
| def reader_credentials(db): | |
| password = secrets.token_urlsafe(32) | |
| db.connection.execute_command('ACL', 'SETUSER', 'careercompass_reader', 'reset', 'on', | |
| '>' + password, '~' + GRAPH, '-@all', | |
| '+graph.ro_query', '+ping', '+info', '+client|setinfo', '+client|setname') | |
| return 'careercompass_reader', password | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--prepare', action='store_true') | |
| parser.add_argument('--build', action='store_true') | |
| args = parser.parse_args() | |
| source_dir = Path(os.getenv('CC_SOURCE_DIR', str(ROOT / 'data'))).resolve() | |
| if args.prepare: | |
| sources(source_dir) | |
| return | |
| state = Path(os.getenv('CC_STATE_DIR', '/tmp/careercompass')).resolve() | |
| state.mkdir(parents=True, exist_ok=True) | |
| seed = ROOT / 'seed' / 'graph.rdb' | |
| if not (state / 'graph.rdb').exists() and seed.exists(): | |
| shutil.copyfile(seed, state / 'graph.rdb') | |
| spec = importlib.util.find_spec('redislite') | |
| if spec is None: | |
| raise RuntimeError('Install requirements.txt; the FalkorDB binary is missing') | |
| binary = Path(next(iter(spec.submodule_search_locations))) / 'bin' | |
| port = int(os.getenv('CC_DB_PORT', '6379')) | |
| stopping = False | |
| def stop(*_): | |
| nonlocal stopping | |
| stopping = True | |
| signal.signal(signal.SIGTERM, stop) | |
| signal.signal(signal.SIGINT, stop) | |
| children = [] | |
| db = None | |
| try: | |
| server = subprocess.Popen([str(binary / 'redis-server'), '--bind', '127.0.0.1', | |
| '--port', str(port), '--dir', str(state), '--dbfilename', 'graph.rdb', | |
| '--save', '', '--appendonly', 'no', '--maxmemory', '4gb', '--maxmemory-policy', 'noeviction', | |
| '--loadmodule', str(binary / 'falkordb.so'), 'THREAD_COUNT', '2']) | |
| children.append(server) | |
| deadline = time.monotonic() + 60 | |
| while time.monotonic() < deadline and not stopping: | |
| if server.poll() is not None: | |
| raise RuntimeError('FalkorDB exited during startup; inspect the preceding log') | |
| try: | |
| db = FalkorDB(host='127.0.0.1', port=port, socket_connect_timeout=2) | |
| db.connection.ping() | |
| break | |
| except RedisError: | |
| time.sleep(.2) | |
| else: | |
| raise RuntimeError('FalkorDB startup interrupted or timed out') | |
| graph = db.select_graph(GRAPH) | |
| ready_graph(db, graph, source_dir) | |
| print('FalkorDB memory:', db.connection.info('memory')['used_memory_human'], flush=True) | |
| if args.build or stopping: | |
| return | |
| username, password = reader_credentials(db) | |
| env = os.environ.copy() | |
| env.update(FALKORDB_HOST='127.0.0.1', FALKORDB_PORT=str(port), FALKORDB_GRAPH=GRAPH, | |
| FALKORDB_USERNAME=username, FALKORDB_PASSWORD=password, FALKORDB_SSL='false') | |
| env.setdefault('GRADIO_SERVER_NAME', '0.0.0.0') | |
| env.setdefault('GRADIO_SERVER_PORT', '7860') | |
| env.setdefault('GRADIO_ANALYTICS_ENABLED', 'False') | |
| app = subprocess.Popen([sys.executable, str(ROOT / 'app.py')], cwd=ROOT, env=env) | |
| children.append(app) | |
| while not stopping: | |
| if any(child.poll() is not None for child in children): | |
| raise RuntimeError('An application child exited; stopping its peer') | |
| time.sleep(.25) | |
| finally: | |
| if db is not None: | |
| db.connection.close() | |
| for child in reversed(children): | |
| if child.poll() is None: | |
| child.terminate() | |
| try: | |
| child.wait(timeout=10) | |
| except subprocess.TimeoutExpired: | |
| child.kill() | |
| child.wait() | |
| if __name__ == '__main__': | |
| main() | |