File size: 3,451 Bytes
ae2060e
 
 
 
 
 
 
 
 
 
c04f846
ae2060e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c04f846
ae2060e
 
 
 
 
 
 
 
 
 
 
 
c04f846
 
 
ae2060e
 
 
 
 
 
 
c04f846
 
 
 
 
ae2060e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c04f846
 
 
 
 
 
 
 
 
ae2060e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Create compact score indexes and verify completed TruFor inference outputs."""

import csv
import json
from pathlib import Path

import numpy as np


DATASETS = {
    "IMD2020": (Path("IMD2020_output"), 2423),
    "CASIA": (Path("CASIA_output"), 11996),
    "CocoGlide": (Path("CocoGlide_output"), 1024),
}


def scalar(value):
    return float(np.asarray(value).reshape(-1)[0])


def pair(value):
    values = np.asarray(value).reshape(-1).tolist()
    return int(values[0]), int(values[1])


def summarize(name, output_dir, expected):
    files = sorted(output_dir.rglob("*.npz"))
    if len(files) != expected:
        raise RuntimeError(f"{name}: expected {expected} files, found {len(files)}")

    rows = []
    scores = []
    scores_by_class = {}
    resized = 0
    for path in files:
        with np.load(path, allow_pickle=False) as data:
            score = scalar(data["score"])
            height, width = pair(data["imgsize"])
            if "processed_imgsize" in data.files:
                processed_height, processed_width = pair(data["processed_imgsize"])
            else:
                processed_height, processed_width = height, width
        was_resized = (height, width) != (processed_height, processed_width)
        resized += int(was_resized)
        scores.append(score)
        relative_path = path.relative_to(output_dir).as_posix()
        row = {
                "path": relative_path,
                "score": f"{score:.9f}",
                "height": height,
                "width": width,
                "processed_height": processed_height,
                "processed_width": processed_width,
                "resized": str(was_resized).lower(),
            }
        if name == "IMD2020":
            image_class = "authentic" if "_orig." in path.name else "tampered"
            row = {"path": relative_path, "class": image_class, **row}
            scores_by_class.setdefault(image_class, []).append(score)
        rows.append(row)

    csv_path = output_dir / "scores.csv"
    with open(csv_path, "w", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)

    score_array = np.asarray(scores, dtype=np.float64)
    summary = {
        "dataset": name,
        "files": len(files),
        "resized_over_1024": resized,
        "score_min": float(score_array.min()),
        "score_max": float(score_array.max()),
        "score_mean": float(score_array.mean()),
        "score_median": float(np.median(score_array)),
    }
    if scores_by_class:
        summary["classes"] = {
            image_class: {
                "files": len(class_scores),
                "score_mean": float(np.mean(class_scores)),
                "score_median": float(np.median(class_scores)),
            }
            for image_class, class_scores in sorted(scores_by_class.items())
        }
    with open(output_dir / "summary.json", "w") as stream:
        json.dump(summary, stream, indent=2)
        stream.write("\n")
    print(json.dumps(summary, sort_keys=True), flush=True)
    return summary


def main():
    summaries = [summarize(name, path, expected) for name, (path, expected) in DATASETS.items()]
    with open("inference_summary.json", "w") as stream:
        json.dump(summaries, stream, indent=2)
        stream.write("\n")
    print("SUMMARY_COMPLETE", flush=True)


if __name__ == "__main__":
    main()