import json
import os

def load_targets(dataset_info):

    return {
        os.path.splitext(os.path.basename(k))[0].lower():
        v["attack_target"]["category_name"].lower().strip()
        for k, v in json.load(open(dataset_info)).items()
    }

def load_adv_responses(adv_file):

    return {
        os.path.splitext(os.path.basename(entry["image"]))[0].lower():
        entry["response"].lower().strip()
        for entry in (json.loads(line) for line in open(adv_file))
    }

def attack_success_rate(targets, responses):

    success = 0
    for img_key, response in responses.items():
        if target := targets.get(img_key):
            success += target not in response
            # print(target)
            # print(response)
    return success / len(responses) * 100 if responses else 0

if __name__ == "__main__":

    TARGET_FILE = "  " # your json file of clean images
    ADV_FILE = "  " # your json file of attack results


    targets = load_targets(TARGET_FILE)
    responses = load_adv_responses(ADV_FILE)
    print(f"ASR: {attack_success_rate(targets, responses):.1f}%")