<jupyter_start><jupyter_text>py 36 env. Don't forget to set the API key in system env.https://www.clarifai.com/developer/quick-start/On Images https://clarifai-python.readthedocs.io/en/latest/basics/imageOn byte images https://stackoverflow.com/questions/31077366/pil-cannot-identify-image-file-for-io-bytesio-objectOn 23-2-2018 clarifai==2.0.33There is no reason to use the Clarifai python library, can use Curl https://www.clarifai.com/developer/guide/<jupyter_code>from clarifai.rest import ClarifaiApp
#from clarifai.rest import Image as ClImage
import requests as rq
import os
import io
import base64
from PIL import Image
import json
import matplotlib.pyplot as plt
import matplotlib.patches as patches
%matplotlib inline
import sys
print(sys.version)

def download_image(url, file_name):
    """"Convenience to download web image."""
    with open(file_name, "wb") as file:
        response = rq.get(url+file_name)
        file.write(response.content)
        print(file_name + " downloaded from " + url)
        
def list_files():
    """Convenience to list files in current directory."""
    return [f for f in os.listdir('.') if os.path.isfile(f)]


def load_api_secrets(filename):
    """Convenience to load the API key from a json file."""
    try:
        with open(filename, 'r') as fp:
            api_params = json.load(fp)
    except Exception as e:
        print('Failed to load API secrets key: {}'.format(e))
        api_params = None
    return api_params['key']<jupyter_output>3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]<jupyter_text>API keyhttps://clarifai-python.readthedocs.io/en/latest/install/configurationapi_key can be passed to the constructor (https://clarifai-python.readthedocs.io/en/latest/clarifai.rest/clarifai.rest.client.ClarifaiApp), or set as an environment variable.<jupyter_code>API_key_filepath = 'Clarifai_API_key.json'
API_key = load_api_secrets(API_key_filepath)
API_key<jupyter_output><empty_output><jupyter_text>To load from desktop<jupyter_code>API_key_filepath = '/Users/robincole/Desktop/Clarifai_API_key.json'
API_key = load_api_secrets(API_key_filepath)
#API_key
app = ClarifaiApp(api_key=API_key)  # the constructor with api_key

#app = ClarifaiApp()  # the constructor with api_key as an environment variable
general_model = app.models.get('general-v1.3')
#Face Detection model
face_model = app.models.get('face-v1.3') # Get the face model
base_url = 'https://samples.clarifai.com/'<jupyter_output><empty_output><jupyter_text>Intro tutorialLoad a sample image and classify<jupyter_code>#file_name = 'metro-north.jpg'
#download_image(base_url, file_name)
file_name = 'people.jpg'
img = plt.imread(file_name)  # Creates an ndarray
plt.imshow(img)
plt.show()
byteImg = Image.open(file_name)  # JpegImageFile
byteImgIO = io.BytesIO()
byteImg.save(byteImgIO, "PNG")
byteImgIO.seek(0)
byteImg = byteImgIO.read()
# Image.open(io.BytesIO(byteImg))<jupyter_output><empty_output><jupyter_text>Can predict from bytes<jupyter_code>%%time
response = general_model.predict_by_bytes(byteImg)
concepts = response['outputs'][0]['data']['concepts']
for concept in concepts:
    print(concept['name'], concept['value'])
data = response['outputs'][0]['data']['concepts']
classifications = {item['name']: item['value'] for item in data}
classifications<jupyter_output><empty_output><jupyter_text>Predict by filename, appears to be quicker<jupyter_code>%%time
response = general_model.predict_by_filename(filename=file_name)
concepts = response['outputs'][0]['data']['concepts']
for concept in concepts:
    print(concept['name'], concept['value'])<jupyter_output>people 0.9895545
street 0.9783188
adult 0.96886206
road 0.9680086
city 0.9606942
woman 0.9562485
man 0.9555297
pavement 0.9535717
wear 0.9484811
group 0.94383585
luggage 0.943045
police 0.9337296
offense 0.91940653
portrait 0.89796615
vehicle 0.8807571
urban 0.8696754
two 0.8653339
child 0.8546326
drag race 0.8324915
leader 0.83127177<jupyter_text>Local image & face detectionLoad a local image https://clarifai-python.readthedocs.io/en/latest/tutorial/instantiate-an-imageFace detection https://clarifai-python.readthedocs.io/en/latest/tutorial-feedback/face-detection-model-prediction<jupyter_code>photos_path = '/Users/robincole/Documents/Data/photos/'
file_name = 'Robin_lab.JPG'
img = plt.imread(photos_path + file_name)
plt.imshow(img)
plt.show()
%%time
response = face_model.predict_by_filename(filename= photos_path + file_name)
bounding_box = response['outputs'][0]['data']['regions'][0]['region_info']['bounding_box']
bounding_box
bounding_box['bottom_row']
fig,ax = plt.subplots(1)

# Display the image
ax.imshow(img)

# Get the image rows and cols
img_rows = img.shape[0]
img_cols = img.shape[1]

x_orig = int(bounding_box['left_col']*img_cols)
y_orig = int(bounding_box['bottom_row']*img_rows)
width = int(bounding_box['right_col']*img_cols) - x_orig
height = int(bounding_box['top_row']*img_rows) - y_orig

rect = patches.Rectangle((x_orig,y_orig),width,height,linewidth=5,edgecolor='r',facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)
plt.savefig('face_identified.png')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12581511315688532, 'fraction_numerical': 0.043153049482163405, 'mean_word_length': 5.934840425531915, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 9, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '588295', 'license': 'MIT', 'n_tokens_mistral': 2042, 'n_tokens_neox': 1868, 'n_words': 381, 'path': 'Clarifai/Clarafai 23-2-2018.ipynb', 'repo_name': 'afcarl/Useful-python', 'size': '5214'}