File size: 5,549 Bytes
557f178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Push/pull experiment files through the skill's marimo scratchpad client.

This helper does not launch experiments or retry execution. Model downloads
remain remote. Transfers are ordinary notebook code, with no SSH or service.
"""

from __future__ import annotations

import argparse
import base64
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import zipfile


SKILL_REMOTE = (Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex")))
                / "skills/molab-marimo/scripts/molab_remote.py")


def execute(code, state_file, capture=False):
    command = [sys.executable, str(SKILL_REMOTE), "exec", "--state-file", state_file]
    return subprocess.run(command, input=code, text=True, capture_output=capture, check=True)


def pull_archive(paths, destination, args):
    code = f'''import base64, io, zipfile
from pathlib import Path
_root = Path({args.remote_root!r}).resolve()
_buffer = io.BytesIO()
with zipfile.ZipFile(_buffer, "w", compression=zipfile.ZIP_DEFLATED) as _archive:
    for _name in {paths!r}:
        _path = _root / _name
        if _path.is_dir():
            for _item in sorted(_path.rglob("*")):
                if _item.is_file():
                    _archive.write(_item, str(_item.relative_to(_root)))
        else:
            _archive.write(_path, _name)
print("MOLAB_FILES_BEGIN", flush=True)
_encoded = base64.b64encode(_buffer.getvalue()).decode("ascii")
for _offset in range(0, len(_encoded), 32768):
    print(_encoded[_offset:_offset + 32768], flush=True)
print("MOLAB_FILES_END", flush=True)
'''
    result = execute(code, args.state_file, capture=True)
    encoded = result.stdout.split("MOLAB_FILES_BEGIN\n", 1)[1].split("\nMOLAB_FILES_END", 1)[0]
    encoded = "".join(encoded.split())
    destination.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(io.BytesIO(base64.b64decode(encoded))) as archive:
        archive.extractall(destination)
        print("Retrieved", len(archive.namelist()), "files into", destination, flush=True)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--state-file", default="work/molab-state.json")
    parser.add_argument("--remote-root", default="molab_runs/resource_planning")
    commands = parser.add_subparsers(dest="command", required=True)
    push = commands.add_parser("push")
    push.add_argument("paths", nargs="+")
    pull = commands.add_parser("pull")
    pull.add_argument("paths", nargs="+")
    pull.add_argument("--destination", default="work/remote")
    pull_jsonl = commands.add_parser("pull-jsonl")
    pull_jsonl.add_argument("path")
    pull_jsonl.add_argument("--destination", default="work/remote")
    pull_jsonl.add_argument("--lines-per-part", type=int, default=64)
    args = parser.parse_args()

    if args.command == "push":
        buffer = io.BytesIO()
        with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
            for raw_path in args.paths:
                path = Path(raw_path)
                if path.is_dir():
                    for item in sorted(path.rglob("*")):
                        if item.is_file() and "__pycache__" not in item.parts:
                            archive.write(item, str(item))
                else:
                    archive.write(path, str(path))
        encoded = base64.b64encode(buffer.getvalue()).decode("ascii")
        code = f'''import base64, io, zipfile
from pathlib import Path
_root = Path({args.remote_root!r}).resolve()
_root.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(io.BytesIO(base64.b64decode({encoded!r}))) as _archive:
    _archive.extractall(_root)
    print("Transferred", len(_archive.namelist()), "files to", str(_root), flush=True)
'''
        execute(code, args.state_file)
    elif args.command == "pull":
        pull_archive(args.paths, Path(args.destination), args)
    else:
        if args.lines_per_part < 1:
            raise ValueError("lines-per-part must be positive")
        part_root = str(Path(".transfer_parts") / args.path)
        code = f'''import json
from pathlib import Path
_root = Path({args.remote_root!r}).resolve()
_parts = _root / {part_root!r}
_parts.mkdir(parents=True, exist_ok=True)
_paths = []
_part = None
try:
    with (_root / {args.path!r}).open("rb") as _source:
        for _index, _line in enumerate(_source):
            if _index % {args.lines_per_part} == 0:
                if _part is not None:
                    _part.close()
                _path = _parts / ("part%05d" % len(_paths))
                _paths.append(str(_path.relative_to(_root)))
                _part = _path.open("wb")
            _part.write(_line)
finally:
    if _part is not None:
        _part.close()
print("MOLAB_PARTS " + json.dumps(_paths), flush=True)
'''
        result = execute(code, args.state_file, capture=True)
        paths = json.loads(result.stdout.split("MOLAB_PARTS ", 1)[1].splitlines()[0])
        destination = Path(args.destination)
        for path in paths:
            pull_archive([path], destination, args)
        canonical = destination / args.path
        canonical.parent.mkdir(parents=True, exist_ok=True)
        with canonical.open("wb") as output:
            for path in paths:
                part = destination / path
                with part.open("rb") as source:
                    shutil.copyfileobj(source, output)
                part.unlink()
        print("Retrieved complete JSONL into", canonical, flush=True)


if __name__ == "__main__":
    main()