File size: 7,105 Bytes
4ad9219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""下载完整指定评测媒体,逐包校验/解压并保存清单,不据成功率删题。"""
import fcntl
import hashlib
import io
import json
import os
from pathlib import Path
import re
import shutil
import tarfile
import time
import zipfile
from download_assets import ROOT, atomic, download, safe_flock


def copy_member(stream, dest):
    dest.parent.mkdir(parents=True, exist_ok=True)
    digest = hashlib.sha256()
    with dest.open('wb') as out:
        while True:
            block = stream.read(4 * 1024**2)
            if not block:
                break
            while shutil.disk_usage(dest.parent).free < 80 * 1024**3+len(block):
                print(json.dumps(dict(stage='waiting_extract_space',destination=str(dest),
                    free_bytes=shutil.disk_usage(dest.parent).free,written_bytes=out.tell())),flush=True)
                time.sleep(30)
            digest.update(block)
            out.write(block)
    return dict(path=str(dest.relative_to(ROOT)), bytes=dest.stat().st_size, sha256=digest.hexdigest())


class Concatenated(io.RawIOBase):
    def __init__(self, paths):
        self.paths = iter(paths)
        self.current = None

    def readable(self):
        return True

    def readinto(self, b):
        while True:
            if self.current is None:
                path = next(self.paths, None)
                if path is None:
                    return 0
                self.current = path.open('rb')
            size = self.current.readinto(b)
            if size:
                return size
            self.current.close()
            self.current = None


def main():
    plan = json.loads((ROOT / 'manifests/download_eval_media.json').read_text())
    expected = json.loads((ROOT / 'manifests/eval_media_expected.json').read_text())
    inventory_path = ROOT / 'provenance/eval_media_inventory.json'
    inventory = json.loads(inventory_path.read_text()) if inventory_path.exists() else {}
    # 先处理较小的OVO源视频,尽快开始原版真实smoke;来源时间从0计,不使用ceil未来边界。
    ovo = [item for item in plan if item['repo'].endswith('/OVO-Bench')]
    if not all('ovo/' + key in inventory and (ROOT / inventory['ovo/' + key]['path']).exists()
               for key in expected['ovo']):
        paths = [Path(download(item)) for item in ovo]
        with io.BufferedReader(Concatenated(paths), buffer_size=8 * 1024**2) as stream:
            with tarfile.open(fileobj=stream, mode='r|') as archive:
                for member in archive:
                    if not member.isfile():
                        continue
                    matches = [key for key in expected['ovo'] if member.name == key or member.name.endswith('/' + key)]
                    if not matches:
                        continue
                    if len(matches) != 1:
                        raise RuntimeError('源视频匹配不唯一:' + member.name)
                    key = matches[0]
                    dest = ROOT / 'data/OVO-Bench/src_videos' / key
                    inventory['ovo/' + key] = dict(copy_member(archive.extractfile(member), dest), archive_member=member.name)
                    atomic(inventory_path, inventory)
                    print(json.dumps({'extracted':key,'benchmark':'ovo'}, ensure_ascii=False), flush=True)
        missing = [key for key in expected['ovo'] if 'ovo/' + key not in inventory]
        if missing:
            raise RuntimeError('OVO源视频缺失,不能宣布覆盖完整:' + str(missing))
        # 仅清理本项目新下载且校验、提取完成的传输文件,原始模型/数据不删除。
        for path in paths:
            path.unlink()
    # 媒体清单可能在标注完整到达后纠正,正式处理Streaming前重新读取。
    expected = json.loads((ROOT / 'manifests/eval_media_expected.json').read_text())
    for item in [item for item in plan if item['repo'].endswith('/StreamingBench')]:
        marker = ROOT / 'provenance' / ('extracted_' + Path(item['destination']).name + '.json')
        if marker.exists():
            saved=json.loads(marker.read_text())
            if saved.get('files') and all('streaming/'+name in inventory and (ROOT/inventory['streaming/'+name]['path']).exists() for name in saved['files']):
                continue
            raise RuntimeError('已有解压标记没有实际媒体,必须核查而不能视为完成:'+str(marker))
        path = Path(download(item))
        extracted = []
        with zipfile.ZipFile(path) as archive:
            for member in archive.infolist():
                name = Path(member.filename).name
                # 官方包为sample_N/video.mp4;按官方move_video.py的sample目录规则映射。
                # __MACOSX旁车不是真实媒体,不能误读或覆盖video.mp4。
                parts=Path(member.filename).parts
                if '__MACOSX' in parts or name.startswith('._'):
                    continue
                if name=='video.mp4' and len(parts)>=2 and re.fullmatch(r'sample_\d+',parts[-2]):
                    name=parts[-2]+'_real.mp4'
                if name not in expected['streaming']:
                    continue
                with archive.open(member) as stream:
                    inventory['streaming/' + name] = dict(copy_member(stream, ROOT / 'data/StreamingBench/videos' / name),
                                                         archive_member=member.filename)
                extracted.append(name)
                atomic(inventory_path, inventory)
                print(json.dumps({'extracted':name,'benchmark':'streaming'}, ensure_ascii=False), flush=True)
        numbers=re.search(r'_(\d+)-(\d+)\.zip$',item['file'])
        required={f'sample_{i}_real.mp4' for i in range(int(numbers[1]),int(numbers[2])+1)} & set(expected['streaming'])
        missing_package=sorted(required-set(extracted))
        if missing_package:
            atomic(marker.with_name(marker.name+'.failed'),dict(archive=item['destination'],files=extracted,missing=missing_package))
            raise RuntimeError('官方zip内缺指定媒体,保留压缩包:'+str(missing_package))
        atomic(marker, dict(archive=item['destination'], files=extracted, sha256=item['sha256'],complete=True))
        path.unlink()
    missing = [key for key in expected['streaming'] if 'streaming/' + key not in inventory]
    atomic(ROOT / 'provenance/eval_media_coverage.json', dict(
        ovo_expected=len(expected['ovo']), streaming_expected=len(expected['streaming']),
        streaming_missing=missing, file_integrity_passed=not missing,
        decode_integrity='pending', query_time_integrity='pending'))
    if missing:
        raise RuntimeError('Streaming媒体缺失:' + str(missing))


if __name__ == '__main__':
    lock_file = ROOT / 'coordination/eval_media.lock'
    lock_file.parent.mkdir(parents=True, exist_ok=True)
    with lock_file.open('w') as lock:
        safe_flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        lock.write(str(os.getpid())); lock.flush()
        main()