File size: 1,295 Bytes
fc32096
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import hashlib
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def inside(path):
    path = Path(path).resolve()
    if not path.is_relative_to(ROOT):
        raise ValueError('Путь должен находиться внутри лаборатории')
    return path


def permit_compute():
    if not (ROOT / 'checkpoints/COMPUTE_AUTHORIZED').exists():
        raise SystemExit('Вычисления заблокированы: отсутствует локальный разрешающий файл.')


def save_json(path, value):
    path = inside(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_suffix(path.suffix + '.tmp')
    temp.write_text(json.dumps(value, ensure_ascii=False, indent=2))
    temp.replace(path)


def rows(path):
    with inside(path).open() as f:
        return [json.loads(line) for line in f if line.strip()]


def stable_seed(item_id, sample, seed=0):
    key = f'{seed}:{item_id}:{sample}'.encode()
    return int.from_bytes(hashlib.sha256(key).digest()[:4], 'little') & 0x7fffffff


def append(path, row):
    path = inside(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('a') as f:
        f.write(json.dumps(row, ensure_ascii=False) + '\n')
        f.flush()