Python Examples

Example: Post an image and a json to our image API.

This is a very basic python example script to post pictures to a our image API. You find a more examples here in our GitHub Repo. There are also more images for testing from our validation dataset in this repo.  

Single image processing

If you want to process a single image, you can use the following code snippet as basis for your application. Just replace the the string "" with your api key.

import os
import requests


IP = 'api.peat-cloud.com' #127.0.0.1:5000'  #'api.peat-cloud.com'
VERSION = 'v1'
ROUTE = 'image_analysis'
URL = 'http://%s/%s/%s' % (IP, VERSION, ROUTE)

    # Header of our requst. Replace <YOUR_API_KEY> with your api key.
HEADER = {'api_key': '<YOUR_API_KEY>'}

def single_processing():

    # make a dict with the picture
    image = os.path.join('..', 'data', 'tomato_nutrient', 'iron1.png')
    files = {"picture": open(image, 'rb')}

    # post both files to our API
    result = requests.get(URL, files=files, headers=HEADER, timeout=200000)

    if result.status_code == 401:
        print 'Authentication failed'
    elif result.status_code == 500:
        print 'Internal server error...'
    elif result.status_code == 200:
        # load response that comes in JSON format and print the result
        json_data = result.json()
        print json_data['image_analysis']
        for data in json_data['image_analysis']:
            print 'Disease name: %s\n\tProbability: %s%%' % (data['name'], data['similarity'])
    print ''
if __name__ == '__main__':
    single_processing()

Batch Processing

The following examples shows a batch processing example for all files in a given directory

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import os
import requests

# define some globals to build the API url
IP = 'api.peat-cloud.com' #127.0.0.1:5000'  #'api.peat-cloud.com'
VERSION = 'v1'
ROUTE = 'image_analysis'
URL = 'http://%s/%s/%s' % (IP, VERSION, ROUTE)

    # Header of our requst. Replace <YOUR_API_KEY> with your api key.
HEADER = {'api_key': '<YOUR_API_KEY>'}


def batch_processing(directory):
    '''
    this example is a bit more sophisticated than the simple single_processing function,
    it needs a base folder as argument
    and will iterate over every image in all subfolders of this directory
    '''

    # get a list of all the subfolders
    folderlist = [x[0] for x in os.walk(directory)]

    # iterate over all folder in a given directory
    for folder in folderlist:
        filelist = [i for i in os.listdir(folder) if i.endswith('.jpg') or i.endswith('.png')]

        # iterate over all files in a given subfolder
        for f in filelist:
            filepath = os.path.join(folder, f)
            files = {'picture': open(filepath, 'rb')}
            result = requests.get(URL, files=files, headers=HEADER, timeout=10)

            # all data comes in json format
            json_data = result.json()

            # just printing
            print 'filename:', f
            print 'input from folder:', folder
            print 'image API result:', json_data['image_analysis'][0]['name'], \
                  json_data['image_analysis'][0]['similarity'], 'peat_id', \
                  json_data['image_analysis'][0]['peat_id'], '\


if __name__ == "__main__":
    batch_processing('../data')

API response

the response on a valid API call would look like this

{ u'code': 200,
  u'recognized': u'True',
    u'image_analysis':  [{
        u'peat_id': 100095, 
        u'name': u'Rhynchosporium', 
        u'rank': 1, 
        u'similarity': 85
        }]
}

Combined image and symptoms request

The following code snippet shows a simple example, how you can combine the image and data api. First this programm sends a image and based on the response, the symptons of a specific desease is requested.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import os
import requests

IP = 'api.peat-cloud.com' #127.0.0.1:5000'  #'api.peat-cloud.com'

# Header of our requst. Replace <YOUR_API_KEY> with your api key.
HEADER = {'api_key': '<YOUR_API_KEY>'}

def single_processing():

    version = 'v1'
    route = 'image_analysis'
    url = 'http://%s/%s/%s' % (IP, version, route)

    # make a dict with the picture
    image = os.path.join('..', 'data', 'tomato_nutrient', 'iron1.png')
    files = {'picture': open(image, 'rb')}

    # post both files to our API
    result = requests.get(url, files=files, headers=HEADER, timeout=200000)

    if result.status_code == 401:
        print 'Authentication failed'
    elif result.status_code == 500:
        print 'Internal server error...'
    elif result.status_code == 200:
        # load response that comes in JSON format and print the result
        json_data = result.json()
        print json_data['image_analysis']
        for data in json_data['image_analysis']:
            print 'Disease name: %s\n\tProbability: %s%%' % (data['name'], data['similarity'])

    return json_data['image_analysis'][0]['name']


def request_symptoms(d_name):

    #Send request
    url = 'http://%s/pathogens_spec/disease_name/%s/symptoms' %(IP, d_name)
    req = requests.get(url,headers=HEADER) 

    #Evaluate response
    if req.status_code == 401:
        print 'Authentication failed'
    elif req.status_code == 200:
        data = req.json()
        print 'Symptoms:\n\t%s' %data['data'][0]['symptoms']

if __name__ == '__main__':
    disease_name = single_processing()
    request_symptoms(disease_name)