File size: 3,263 Bytes
91ac3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import Any

from kawk50m.cli import configure_utf8_stdio


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Concatenate uint16 token parts with an optional exact limit."
    )
    parser.add_argument("--input-dir", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--max-tokens", type=int, default=None)
    parser.add_argument("--copy-buffer-mib", type=int, default=8)
    return parser.parse_args()


def main() -> None:
    configure_utf8_stdio()
    args = parse_args()
    if args.max_tokens is not None and args.max_tokens <= 0:
        raise ValueError("--max-tokens must be positive")
    if args.copy_buffer_mib <= 0:
        raise ValueError("--copy-buffer-mib must be positive")

    input_dir = Path(args.input_dir)
    parts = sorted(input_dir.glob("*.bin"))
    if not parts:
        raise FileNotFoundError(f"No token parts found in {input_dir}")
    output_path = Path(args.output)
    metadata_path = output_path.with_suffix(".metadata.json")
    if output_path.exists() or metadata_path.exists():
        raise FileExistsError(f"Refusing to overwrite combined output: {output_path}")
    output_path.parent.mkdir(parents=True, exist_ok=True)

    max_bytes = args.max_tokens * 2 if args.max_tokens is not None else None
    buffer_size = args.copy_buffer_mib * 1024**2
    bytes_written = 0
    parts_used = 0
    with output_path.open("wb") as target:
        for part in parts:
            part_size = part.stat().st_size
            if part_size % 2:
                raise ValueError(f"Odd byte size for uint16 part: {part}")
            remaining = (
                part_size
                if max_bytes is None
                else min(part_size, max_bytes - bytes_written)
            )
            if remaining <= 0:
                break
            with part.open("rb") as source:
                while remaining:
                    chunk = source.read(min(buffer_size, remaining))
                    if not chunk:
                        raise IOError(f"Unexpected EOF while reading {part}")
                    target.write(chunk)
                    bytes_written += len(chunk)
                    remaining -= len(chunk)
            parts_used += 1

    summaries: list[dict[str, Any]] = []
    for path in sorted(input_dir.glob("*.json")):
        summaries.append(json.loads(path.read_text(encoding="utf-8")))
    result = {
        "output": str(output_path),
        "tokens": bytes_written // 2,
        "bytes": bytes_written,
        "dtype": "uint16",
        "available_part_tokens": sum(part.stat().st_size for part in parts) // 2,
        "parts_available": len(parts),
        "parts_used": parts_used,
        "documents_seen": sum(int(row["documents_seen"]) for row in summaries),
        "documents_written": sum(
            int(row["documents_written"]) for row in summaries
        ),
    }
    metadata_path.write_text(
        json.dumps(result, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()