File size: 3,903 Bytes
38f2c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""列出同目录中缺少 <编号>_source.png 的 <编号>_result[_版本].png。

默认扫描脚本所在的数据集目录,结果写入 results_without_source.txt。
仅检查文件名及文件是否存在,不修改或删除任何图片。

示例:
  python3 find_results_without_source.py
  python3 find_results_without_source.py --version v104 --output missing_v104.txt
"""
import argparse
from collections import Counter
import json
import os
from pathlib import Path
import re
import tempfile


RESULT_NAME = re.compile(r"^(?P<stem>.+?)_result(?:_(?P<version>[^.]+))?\.png$")


def scan(root, version=None):
    missing = []
    scanned = 0
    missing_ids = set()
    counts = Counter()

    def fail_on_walk_error(error):
        raise error

    for directory, folders, files in os.walk(root, followlinks=False, onerror=fail_on_walk_error):
        folders[:] = sorted(name for name in folders if name not in {'.git', '__pycache__', '.cache'})
        parent = Path(directory)
        for name in files:
            match = RESULT_NAME.fullmatch(name)
            if match is None or (version is not None and match['version'] != version):
                continue
            result = parent / name
            if not result.is_file():
                continue
            scanned += 1
            stem = match['stem']
            if (parent / (stem + '_source.png')).is_file():
                continue
            missing.append(str(result))
            missing_ids.add((str(parent), stem))
            counts[match['version'] or 'unversioned'] += 1
    return sorted(missing), {
        'scanned_result_images': scanned,
        'missing_source_images': len(missing),
        'missing_source_identities': len(missing_ids),
        'by_version': dict(sorted(counts.items())),
    }


def write_list(output, paths):
    # Refuse image destinations and symlinks; publish the complete list atomically.
    if output.suffix.lower() != '.txt' or output.is_symlink():
        raise ValueError('输出路径必须是普通 .txt 文件,不能是图片或符号链接')
    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', newline='\n',
                dir=output.parent, prefix='.' + output.name + '.', suffix='.tmp', delete=False) as stream:
            temporary = Path(stream.name)
            for path in paths:
                stream.write(path + '\n')
        os.replace(temporary, output)
    finally:
        if temporary is not None:
            temporary.unlink(missing_ok=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parent,
                        help='递归扫描的数据集根目录,默认脚本所在目录')
    parser.add_argument('--output', type=Path, help='输出 .txt 路径,默认根目录下 results_without_source.txt')
    parser.add_argument('--version', help='仅检查指定版本,如 v104;默认检查所有 result 版本')
    options = parser.parse_args()
    root = options.root.resolve()
    if not root.is_dir():
        parser.error('数据集目录不存在:' + str(root))
    output = options.output if options.output is not None else root / 'results_without_source.txt'
    output = output.absolute()
    try:
        paths, summary = scan(root, options.version)
        write_list(output, paths)
    except (OSError, ValueError) as error:
        parser.exit(1, '扫描失败:' + str(error) + '\n')
    print(json.dumps({'root': str(root), 'output': str(output),
                     'criterion': 'same-directory <stem>_source.png is missing',
                     **summary}, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()