Skip to content

Instantly share code, notes, and snippets.

@josue
Last active May 7, 2021 13:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josue/588c083e4cc4d95a2078ac39930da6fb to your computer and use it in GitHub Desktop.
Save josue/588c083e4cc4d95a2078ac39930da6fb to your computer and use it in GitHub Desktop.
Kairos - Java API wrapper
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import javax.net.ssl.HttpsURLConnection;
public class Kairos {
// params
private final String APP_ID = System.getenv("APP_ID");
private final String APP_KEY = System.getenv("APP_KEY");
private final String API_HOST = "https://api.kairos.com";
private String API_URL = "";
private String method = "";
private String sourceType = "unknown";
private String sourceInput = "";
private String payload = "";
private int responseCode = 0;
private String responseData = "";
public static void main(String[] args) throws Exception {
Kairos Api = new Kairos();
Api.buildPayload(args);
Api.request();
Api.printResults();
}
// invoke API request
private void request() throws Exception {
// prepare API url with method
API_URL = API_HOST + "/" + method;
URL obj = new URL(API_URL);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// API header
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("APP_ID", APP_ID);
con.setRequestProperty("APP_KEY", APP_KEY);
// write JSON string to connection
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
out.write(payload);
out.close();
// get HTTP Status Code
responseCode = con.getResponseCode();
// read buffer response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
// get our response data
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
} in .close();
// get read response
responseData = response.toString();
}
private void buildPayload(String[] params) throws Exception {
method = (params.length >= 1 ? params[0] : "detect").trim();
sourceInput = (params.length >= 2 ? params[1] : "").trim();
if (sourceInput != "" && sourceInput.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*") == false) {
sourceType = "base64";
payload = "{ \"image\": \"" + getBase64Encoding(sourceInput) + "\" }";
} else {
sourceType = "url";
// if url is empty then use the default image
if (sourceInput == "") {
sourceInput = "http://media.kairos.com/test5.jpg";
}
payload = "{ \"image\": \"" + sourceInput + "\" }";
}
}
private String getBase64Encoding(String filepath) throws Exception {
File originalFile = new File(filepath);
String encodedBase64 = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
byte[] bytes = new byte[(int) originalFile.length()];
fileInputStreamReader.read(bytes);
encodedBase64 = new String(Base64.getEncoder().encode(bytes));
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
System.exit(1);
}
return encodedBase64;
}
private void printResults() throws Exception {
if (sourceType == "base64") {
payload = payload.substring(0, 150) + "...";
}
System.out.println("API URL: " + API_URL);
System.out.println("Source Type: " + sourceType);
System.out.println("Source Input: " + sourceInput);
System.out.println("Payload: " + payload);
System.out.println("\nHTTP Status Code: " + responseCode);
System.out.println("JSON Response: \n\n" + responseData);
}
}
@josue
Copy link
Author

josue commented Jan 30, 2018

Compile & Usage:

  1. Add your environment variable AppID + AppKey (developer auth):
export APP_ID=[....]
export APP_KEY=[....]
  1. Download script:
curl -o /tmp/Kairos.java https://gist.githubusercontent.com/josue/588c083e4cc4d95a2078ac39930da6fb/raw/Kairos.java
  1. Compile with Java:
javac /tmp/Kairos.java -verbose -d /tmp
  1. Run compiled source, calling the detect method ...
# using remote image url
java -cp /tmp Kairos detect http://media.kairos.com/test1.jpg

# using file path to encode as Base64 string
java -cp /tmp Kairos detect /tmp/pic.jpg

Expected Output:

API URL: https://api.kairos.com/detect
Source Type: url
Source Input: http://media.kairos.com/test1.jpg
Payload: { "image": "http://media.kairos.com/test1.jpg" }

HTTP Status Code: 200
JSON Response:

{
	"images": [{
		"faces": [{
			"attributes": {
				"age": 28,
				"asian": 0.16898,
				"black": 0.00135,
				"gender": {
					"femaleConfidence": 0.9995,
					"maleConfidence": 0.0005,
					"type": "F"
				},
				"glasses": "None",
				"hispanic": 0.28272,
				"lips": "Together",
				"other": 0.03853,
				"white": 0.50841
			},
			"chinTipX": 289,
			"chinTipY": 751,
			"confidence": 0.99947,
			"eyeDistance": 212,
			"face_id": 1,
			"height": 432,
			"leftEyeCenterX": 343,
			"leftEyeCenterY": 364,
			"pitch": -17,
			"quality": -0.32549,
			"rightEyeCenterX": 133,
			"rightEyeCenterY": 382,
			"roll": -8,
			"topLeftX": 28,
			"topLeftY": 276,
			"width": 431,
			"yaw": 27
		}],
		"file": "test1.jpg",
		"height": 1024,
		"status": "Complete",
		"width": 680
	}]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment