File size: 4,882 Bytes
57c7939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
143
144
145
#!/usr/bin/env python3
"""Extract the release audio archives.

For each bucket (native, anchor, events):
  1. verify archive checksums against audio/CHECKSUMS.sha256 (when present)
  2. if split, concatenate audio/audio_<bucket>.partNN.tar into
     audio/audio_<bucket>.tar
  3. extract the tar into audio/<bucket>/

Self-contained: paths resolve relative to the release root (parent of
prepare/).

Usage:
    python prepare/unpack_audio.py [--root ..] [--buckets native,anchor,events]
                                   [--keep-tar] [--dry-run]
"""

import argparse
import hashlib
import re
import sys
import tarfile
from pathlib import Path

BUCKETS = ("native", "anchor", "events")


def sha256_of(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(8 * 1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def load_checksums(root: Path) -> dict[str, str]:
    path = root / "audio" / "CHECKSUMS.sha256"
    if not path.is_file():
        return {}
    out = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        parts = line.split(None, 1)
        if len(parts) == 2:
            out[parts[1].strip()] = parts[0]
    return out


def find_parts(root: Path, bucket: str) -> list[Path]:
    pattern = re.compile(rf"^audio_{bucket}\.part(\d+)\.tar$")
    parts = []
    for p in (root / "audio").iterdir():
        m = pattern.match(p.name)
        if m:
            parts.append((int(m.group(1)), p))
    return [p for _, p in sorted(parts)]


def unpack_bucket(root: Path, bucket: str, checksums: dict, keep_tar: bool,
                  dry_run: bool) -> bool:
    parts = find_parts(root, bucket)
    tar_path = root / "audio" / f"audio_{bucket}.tar"
    if not parts:
        if not tar_path.is_file():
            print(f"audio_{bucket}: no parts found, skipping")
            return False
        print(f"audio_{bucket}: single tar")
    else:
        print(f"audio_{bucket}: {len(parts)} part(s)")

    for part in parts:
        expected = checksums.get(part.name)
        if expected is None:
            print(f"  WARN: no checksum for {part.name}")
            continue
        if dry_run:
            continue
        if sha256_of(part) != expected:
            sys.exit(f"ERROR: checksum mismatch for {part.name}")
    if not dry_run and checksums:
        print("  checksums ok")

    if parts:
        if dry_run:
            print(f"  [dry-run] reassemble -> {tar_path.name}, extract audio/{bucket}/")
            return True
        with open(tar_path, "wb") as out:
            for part in parts:
                with open(part, "rb") as fh:
                    while True:
                        data = fh.read(8 * 1024 * 1024)
                        if not data:
                            break
                        out.write(data)
        expected_tar = checksums.get(tar_path.name)
        if expected_tar and sha256_of(tar_path) != expected_tar:
            sys.exit(f"ERROR: checksum mismatch for reassembled {tar_path.name}")
    else:
        expected_tar = checksums.get(tar_path.name)
        if not dry_run and expected_tar and sha256_of(tar_path) != expected_tar:
            sys.exit(f"ERROR: checksum mismatch for {tar_path.name}")
        if dry_run:
            print(f"  [dry-run] extract audio/{bucket}/")
            return True

    with tarfile.open(tar_path, "r:") as tf:
        members = tf.getnames()
        if sys.version_info >= (3, 12):
            tf.extractall(root, filter="data")
        else:
            tf.extractall(root)
    print(f"  extracted {len(members)} files -> audio/{bucket}/")

    if parts and not keep_tar:
        tar_path.unlink()
    return True


def main():
    parser = argparse.ArgumentParser(description="Reassemble and extract release audio archives")
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent,
                        help="release root (default: parent of prepare/)")
    parser.add_argument("--buckets", default=",".join(BUCKETS),
                        help="comma-separated subset of native,anchor,events")
    parser.add_argument("--keep-tar", action="store_true",
                        help="keep reassembled tar files after extraction")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    root = args.root.resolve()
    buckets = [b.strip() for b in args.buckets.split(",") if b.strip()]
    for b in buckets:
        if b not in BUCKETS:
            sys.exit(f"ERROR: unknown bucket '{b}' (choose from {BUCKETS})")

    checksums = load_checksums(root)
    done = 0
    for bucket in buckets:
        if unpack_bucket(root, bucket, checksums, args.keep_tar, args.dry_run):
            done += 1
    print(f"Done. {done} bucket(s) unpacked.")


if __name__ == "__main__":
    main()