"""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()