bat._main API documentation

# bat._main

View Source

      1import click
      2import validators
      3
      4import numpy as np
      5from PIL import Image
      6
      7from bat.apis.imagga import Imagga
      8from bat.apis.google import CloudVision
      9from bat.apis.deepapi import bat_deepapi_model_list
     10
     11from bat.examples.simba_attack_deepapi import simba_attack_deepapi
     12from bat.examples.bandits_attack_deepapi import bandits_attack_deepapi
     13from bat.examples.square_attack_deepapi import square_attack_deepapi
     14
     15bat_api_list = {
     16    'deepapi': 'An open-source image classification cloud service for research on black-box adversarial attacks.',
     17    'google': 'Google Cloud Vision AI.',
     18    'imagga': 'Imagga automatic tagging API.'
     19}
     20
     21bat_attack_list = [
     22    ('SimBA', 'Local Search', 'A Simple Black-box Adversarial Attacks'),
     23    ('Square Attack', 'Local Search', 'A query-efficient black-box adversarial attack via random search.'),
     24    ('Bandits Atack', 'Gradient Estimation', 'Black-Box Adversarial Attacks with Bandits and Priors')
     25]
     26
     27bat_example_list = [
     28    ('simba_deepapi', 'SimBA Attack against DeepAPI'),
     29    ('bandits_deepapi', 'Bandits Attack against DeepAPI'),
     30    ('square_deepapi', 'Square Attack against DeepAPI'),
     31]
     32
     33# Main CLI (bat)
     34@click.group()
     35def main_cli():
     36    """The CLI tool for Black-box Adversarial Toolbox (BAT)."""
     37    pass
     38
     39# bat api
     40@click.group()
     41def api():
     42    """Manage Cloud APIs"""
     43    pass
     44
     45# bat api list
     46@api.command('list')
     47def api_list():
     48    """List supported Cloud APIs"""
     49    max_len = max([len(x) for x in bat_api_list.keys()])
     50    for i, api in enumerate(bat_api_list.keys(), start=1):
     51        print('{} : {:<{w}s}\t{}'.format(i, api, bat_api_list[api], w=max_len+1))
     52
     53# bat api run
     54@api.group('run')
     55def api_run():
     56    """Run supported Cloud APIs"""
     57    pass
     58
     59# bat api run deepapi
     60@api_run.command('deepapi')
     61def api_run_deepapi():
     62    """Send an image to DeepAPI"""
     63    for i, (_, model) in enumerate(bat_deepapi_model_list.items(), start=1):
     64        print(i, ':', model[0])
     65
     66    try:
     67        # Get the model type
     68        index = input(f"Please input the model index (default: 1): ")
     69        if len(index) == 0:
     70            index = 1
     71        else:
     72            while not index.isdigit() or int(index) > len(bat_deepapi_model_list):
     73                index = input(f"Model [{index}] does not exist. Please try again: ")
     74
     75        # Get the DeepAPI server url
     76        deepapi_url = input(f"Please input the DeepAPI URL (default: http://localhost:8080): ")
     77        if len(deepapi_url) == 0:
     78            deepapi_url = 'http://localhost:8080'
     79        else:
     80            while not validators.url(deepapi_url):
     81                deepapi_url = input(f"Invalid URL. Please try again: ")
     82
     83        # Get the image file
     84        try:
     85            file = input(f"Please input the image file: ")
     86            while len(file) == 0:
     87                file = input(f"Please input the image file: ")
     88            image = Image.open(file).convert('RGB')
     89            x = np.array(image)
     90        except Exception as e:
     91            print(e)
     92            return
     93
     94        deepapi_model = bat_deepapi_model_list[int(index)][1](deepapi_url)
     95
     96        y = deepapi_model.predict(np.array([x]))[0]
     97
     98        if y is not None:
     99            deepapi_model.print(y)
    100
    101    except KeyboardInterrupt as e:
    102        print()
    103        return
    104
    105# bat api run imagga
    106@api_run.command('imagga')
    107def api_run_deepapi():
    108    """Send an image to Imagga auto-tagging API"""
    109    api_key = input(f"Please input the Imagga API Key: ")
    110    api_secret = input(f"Please input the Imagga API Secret: ")
    111    imagga_client = Imagga(api_key, api_secret, concurrency=2)
    112
    113    # Get the image file
    114    try:
    115        file = input(f"Please input the image file: ")
    116        while len(file) == 0:
    117            file = input(f"Please input the image file: ")
    118    except Exception as e:
    119        print(e)
    120        return
    121
    122    # Make predictions
    123    y = imagga_client.predict(file)
    124
    125    # Print results
    126    if y is not None:
    127        imagga_client.print(y)
    128
    129# bat api run google
    130@api_run.command('google')
    131def api_run_google():
    132    """Send an image to Google Cloud Vision"""
    133    vision_client = CloudVision()
    134
    135    # Get the image file
    136    try:
    137        file = input(f"Please input the image file: ")
    138        while len(file) == 0:
    139            file = input(f"Please input the image file: ")
    140    except Exception as e:
    141        print(e)
    142        return
    143
    144    # Make predictions
    145    y = vision_client.predict(file)
    146
    147    # Print resuilts
    148    if y is not None:
    149        vision_client.print(y)
    150
    151# bat attack
    152@click.group()
    153def attack():
    154    """Manage Attacks"""
    155    pass
    156
    157# bat attack list
    158@attack.command('list')
    159def attack_list():
    160    """List supported Attacks"""
    161    max_len = max([len(x[0]) for x in bat_attack_list])
    162    for i, attack in enumerate(bat_attack_list, start=1):
    163        print('{} : {:<{w}s}\t{}'.format(i, attack[0], attack[1], w=max_len))
    164
    165# bat example
    166@click.group()
    167def example():
    168    """Manage Examples"""
    169    pass
    170
    171# bat example list
    172@example.command('list')
    173def example_list():
    174    """List examples"""
    175    max_len = max([len(x[0]) for x in bat_example_list])
    176    for i, example in enumerate(bat_example_list, start=1):
    177        print('{} : {:<{w}s}\t{}'.format(i, example[0], example[1], w=max_len))
    178
    179# bat exmaple run
    180@example.group('run')
    181def example_run():
    182    """Run examples"""
    183    pass
    184
    185# bat exmaple run simba_deepapi
    186@example_run.command('simba_deepapi')
    187def example_run_simba_deepapi():
    188    """SimBA Attack against DeepAPI"""
    189    simba_attack_deepapi()
    190
    191# bat exmaple run bandits_deepapi
    192@example_run.command('bandits_deepapi')
    193def example_run_bandits_deepapi():
    194    """Bandits Attack against DeepAPI"""
    195    bandits_attack_deepapi()
    196
    197# bat exmaple run square_deepapi
    198@example_run.command('square_deepapi')
    199def example_run_bandits_deepapi():
    200    """Square Attack against DeepAPI"""
    201    square_attack_deepapi()
    202
    203def main():
    204    main_cli.add_command(api)
    205    main_cli.add_command(attack)
    206    main_cli.add_command(example)
    207
    208    api.add_command(api_list)
    209    api.add_command(api_run)
    210
    211    attack.add_command(attack_list)
    212
    213    example.add_command(example_list)
    214    example.add_command(example_run)
    215
    216    return main_cli()
    217
    218if __name__ == "__main__":
    219
    220    main()

main_cli = <Group main-cli>

The CLI tool for Black-box Adversarial Toolbox (BAT).

api = <Group api>

Manage Cloud APIs

api_list = <Command list>

List supported Cloud APIs

api_run = <Group run>

Run supported Cloud APIs

api_run_deepapi = <Command imagga>

Send an image to Imagga auto-tagging API

api_run_google = <Command google>

Send an image to Google Cloud Vision

attack = <Group attack>

Manage Attacks

attack_list = <Command list>

List supported Attacks

example = <Group example>

Manage Examples

example_list = <Command list>

List examples

example_run = <Group run>

Run examples

example_run_simba_deepapi = <Command simba_deepapi>

SimBA Attack against DeepAPI

example_run_bandits_deepapi = <Command square_deepapi>

Square Attack against DeepAPI

def main(): View Source

    204def main():
    205    main_cli.add_command(api)
    206    main_cli.add_command(attack)
    207    main_cli.add_command(example)
    208
    209    api.add_command(api_list)
    210    api.add_command(api_run)
    211
    212    attack.add_command(attack_list)
    213
    214    example.add_command(example_list)
    215    example.add_command(example_run)
    216
    217    return main_cli()