<jupyter_start><jupyter_text>Notebook to show image classification using a locally running classigification server.Simply * **pip3 install tensorflow*** **pip3 install keras**Follow https://github.com/jrosebr1/simple-keras-rest-apiStart the server by running **python run_keras_server.py**<jupyter_code>ls
import pprint
import requests
import matplotlib.pyplot as plt
%matplotlib inline

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/predict"

def print_json(json_data):
    pprint.PrettyPrinter().pprint(json_data)<jupyter_output><empty_output><jupyter_text>Helper functions<jupyter_code>def make_predition(img_path):
    """Make a prediction via the API"""
    img = plt.imread(img_path)
    plt.imshow(img)

    image = open(img_path, "rb").read()
    payload = {"image": image}
    r = requests.post(KERAS_REST_API_URL, files=payload).json()

    if r["success"]:
        # loop over the predictions and display them
        for (i, result) in enumerate(r["predictions"]):
            print("{}. {}: {:.4f}".format(i + 1, result["label"],
                result["probability"]))
    return
%%time
make_predition("dog.jpg")
make_predition("bird.jpg")
make_predition("bird_2.jpg")
make_predition("bird_3.jpg")
make_predition("no_bird.jpg")
%%time
make_predition("robin.jpg")<jupyter_output>1. bow_tie: 0.1465
2. suit: 0.1316
3. lab_coat: 0.0616
4. neck_brace: 0.0452
5. Windsor_tie: 0.0380
CPU times: user 92.3 ms, sys: 71.2 ms, total: 163 ms
Wall time: 510 ms<jupyter_text>Class wrapperMake a simple class for performing the classification<jupyter_code>class Classification():
    """Perform a classification via the rest API."""

    ICON = 'mdi:file'

    def __init__(self, url, file_path):
        """Initialize the classification object."""
        self._url = url
        self._file_path = file_path   # Need to check its a valid path
        self._name = "Rest_classifier"
        self._state = None
        self._data = {}
        
    def process_image(self):
        """Perform image processing."""
        image = open(self._file_path, "rb").read()
        payload = {"image": image}
        response = requests.post(self._url, files=payload).json()
        if response["success"]:
            self._state = response['predictions'][0]['label']
            self._data = {e['label']:round(e['probability'],3) for e in response['predictions']}
        else:
            self._state = "Request failed"
            self._data = {}
        return

    @property
    def state(self):
        """Return the state of the entity."""
        return self._state
    
    @property
    def state_attributes(self):
        """Return device specific state attributes."""
        return self._data
    
    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        return self.ICON
    
    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name
file_path = "dog.jpg"
my_classification = Classification(KERAS_REST_API_URL, file_path)
my_classification.name
my_classification.process_image()
my_classification.state
my_classification.state_attributes<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12287217579696688, 'fraction_numerical': 0.017022593624264934, 'mean_word_length': 3.409276944065484, 'pattern_counts': {'":': 2, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '544306', 'license': 'MIT', 'n_tokens_mistral': 1046, 'n_tokens_neox': 994, 'n_words': 255, 'path': 'Keras and Theano/Keras rest API.ipynb', 'repo_name': 'afcarl/Useful-python', 'size': '3231'}