Created
May 16, 2016 02:45
-
-
Save l04m33/ebb9b5eb873047265be001bdd9d49056 to your computer and use it in GitHub Desktop.
Script to tag an image using Clarifai
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
export CLIENT_ID="client-id" \ | |
CLIENT_SECRET="client-secret" \ | |
TOKEN_FILE="$HOME/.clarifai_token" | |
export TOKEN_API="https://api.clarifai.com/v1/token" \ | |
TAG_API="https://api.clarifai.com/v1/tag" | |
function gen_access_token () { | |
local json=$(curl -s \ | |
-X POST "$TOKEN_API" \ | |
-d "client_id=$CLIENT_ID" \ | |
-d "client_secret=$CLIENT_SECRET" \ | |
-d "grant_type=client_credentials") | |
python3 << EOF | |
import json | |
import time | |
jobj = json.loads('$json') | |
print(jobj['access_token'], int(time.time()) + jobj['expires_in']) | |
EOF | |
} | |
function get_access_token () { | |
local token_info="" | |
if [ -r "$TOKEN_FILE" ]; then | |
token_info=$(cat "$TOKEN_FILE") | |
else | |
token_info=$(gen_access_token) | |
fi | |
local token=$(echo $token_info | cut -d' ' -f1) | |
local deadline=$(echo $token_info | cut -d' ' -f2) | |
if [ "$deadline" -gt "$(date +'%s')" ]; then | |
echo "$token_info" > "$TOKEN_FILE" | |
echo "$token" | |
else | |
token_info=$(gen_access_token) | |
echo "$token_info" > "$TOKEN_FILE" | |
echo "$(echo token_info | cut -d' ' -f1)" | |
fi | |
} | |
function get_tags () { | |
local img_file=$1; | |
if [ -z "$img_file" ]; then | |
echo "No image file name provided. Abort." | |
exit 1 | |
fi | |
local token=$(get_access_token) | |
local json=$(curl -s \ | |
"$TAG_API" \ | |
-F "encoded_data=@$img_file" \ | |
-H "Authorization: Bearer $token") | |
python3 << EOF | |
import json | |
jobj = json.loads('$json') | |
if jobj['status_code'] != 'OK': | |
print(jobj['status_msg']) | |
else: | |
pr = [repr(s) for s in jobj['results'][0]['result']['tag']['classes']] | |
print(*pr) | |
EOF | |
} | |
get_tags $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment