GiGA Genie AI API 서비스가이드 <GiGA Genie AI 영상분석 API> 1 / 33

Similar documents
API STORE 키발급및 API 사용가이드 Document Information 문서명 : API STORE 언어별 Client 사용가이드작성자 : 작성일 : 업무영역 : 버전 : 1 st Draft. 서브시스템 : 문서번호 : 단계 : Docum

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

GiGA Genie AI API 서비스가이드 <GiGA Genie AI 음성인식 API> 1 / 21

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

12-file.key

02 C h a p t e r Java

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

신림프로그래머_클린코드.key

KT AI MAKERS KIT 사용설명서 (Node JS 편).indd

07 자바의 다양한 클래스.key

rmi_박준용_final.PDF

gcloud storage 사용자가이드 1 / 17

1. SNS Topic 생성여기를클릭하여펼치기... Create Topic 실행 Topic Name, Display name 입력후 Create topic * Topic name : 특수문자는 hyphens( - ), underscores( _ ) 만허용한다. Topi

PowerPoint 프레젠테이션

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

비긴쿡-자바 00앞부속

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

PowerPoint Presentation

자바-11장N'1-502

Cluster management software

Modern Javascript

Microsoft PowerPoint - web-part03-ch19-node.js기본.pptx

Microsoft PowerPoint - 04-UDP Programming.ppt

JMF2_심빈구.PDF

PowerPoint Template

Java

05-class.key

Java ...

매뉴얼

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

ibmdw_rest_v1.0.ppt

JMF3_심빈구.PDF

자바 프로그래밍

게시판 스팸 실시간 차단 시스템

PowerPoint 프레젠테이션

mytalk

MasoJava4_Dongbin.PDF

Interstage5 SOAP서비스 설정 가이드

Polly_with_Serverless_HOL_hyouk

14-Servlet

ch09

슬라이드 1

JUNIT 실습및발표

03장

Secure Programming Lecture1 : Introduction

09-interface.key

PowerPoint Presentation

교육자료

PowerPoint Presentation

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

HLS(HTTP Live Streaming) 이용가이드 1. HLS 소개 Apple iphone, ipad, ipod의운영체제인 ios에서사용하는표준 HTTP 기반스트리밍프로토콜입니다. 2. HLS 지원대상 - 디바이스 : iphone/ipad/ipod - 운영체제 :

대량문자API연동 (with directsend)

JAVA PROGRAMMING 실습 09. 예외처리

PowerPoint 프레젠테이션

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

C# Programming Guide - Types

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밊

PowerPoint Presentation

Microsoft PowerPoint - Java7.pptx

1

JAVA PROGRAMMING 실습 02. 표준 입출력

Office 365 사용자 가이드

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

교육2 ? 그림

Secure Programming Lecture1 : Introduction

슬라이드 1

3장

Microsoft PowerPoint - 03-TCP Programming.ppt

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

SBR-100S User Manual

초보자를 위한 C# 21일 완성

untitled

FileMaker ODBC and JDBC Guide

PowerPoint Presentation

歯JavaExceptionHandling.PDF

Eclipse 와 Firefox 를이용한 Javascript 개발 발표자 : 문경대 11 년 10 월 26 일수요일

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

PowerPoint Presentation

3ÆÄÆ®-14

슬라이드 1

4장.문장

2015_핀업_작품접수매뉴얼

1. 자바프로그램기초 및개발환경 2 장 & 3 장. 자바개발도구 충남대학교 컴퓨터공학과

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

JAVA PROGRAMMING 실습 05. 객체의 활용

Chap12

5장.key

PowerPoint 프레젠테이션

Microsoft Word - ntasFrameBuilderInstallGuide2.5.doc

아래 항목은 최신( ) 이미지를 모두 제대로 설치하였을 때를 가정한다

Java XPath API (한글)

Web Scraper in 30 Minutes 강철

메뉴얼41페이지-2

FileMaker 15 ODBC 및 JDBC 설명서

PowerPoint 프레젠테이션

untitled

유니티 변수-함수.key

Transcription:

GiGA Genie AI API 서비스가이드 <GiGA Genie AI 영상분석 API> 1 / 33

GiGA Genie AI API 신청방법 회원가입방법 1. ucloud biz 포탈메인페이지에서회원가입이가능합니다 2. 자세한방법은고객센터 > 매뉴얼 > Server > 사용자가이드중첫걸음떼기의 내용을참조하시기바랍니다 사전준비사항 1. 상품 > 컴퓨팅 > Server 항목에서 ucloud server 상품을먼저신청합니다 GiGA Genie AI API 은 Running 상태인 VM(Virtual Machine) 이최소 1 대는존재해야 신청가능하도록제한하고있습니다. 이미 ucloud server 상품을사용하고계신사용자라면, 본과정을넘어가면됩니다. 2 / 33

2. ucloud server 상품신청후클라우드콘솔에접속합니다 3. 클라우드콘솔에서서버를 1 개생성합니다 3 / 33

4. 서버생성후상품 > GiGA Genie AI API 항목으로이동하여, 상품신청을진행합니다 GiGA Genie AI API 상품신청 1. 상품 > GiGA Genie AI API 을선택하여해당페이지로접근합니다 2. 우측플로팅버튼 [ 상품신청하기 ] 를클릭하여, 상품신청을진행합니다 3. ucloud biz 포탈에서의상품신청으로, 기가지니개발자센터 (www.gigagenie.ai) 의회 원가입처리가자동으로이루어집니다. 4 / 33

사용자는두개의웹사이트에별도로회원가입하실필요가없습니다. 기가지니개발자센터의회원가입이자동처리되는만큼, 해당사이트의약관을제 공하고있습니다. 약관확인후동의하셔야다음단계가진행됩니다 4. 상품가입이완료되면, 기가지니개발자포탈 (www.gigagenie.ai) 에서해당사이트의 임시비밀번호를메일로전달합니다. 해당임시비밀번호는기가지니개발자포탈 에로그인할때필요합니다 5 / 33

GiGA Genie AI API 서비스생성 1. 클라우드콘솔 > AI API Cloud 아이콘을선택합니다. 2. GiGA Genie AI API를사용하기위해선서비스생성이필요합니다. 서비스란 AI API를통해개발하는새로운서비스프로젝트개념에가깝습니다. 1개계정에는하나의 GiGA Genie AI 서비스만생성가능합니다. 서비스마다키가부여되어 AI API를호출할수있게됩니다. 3. [GiGA Genie AI 서비스생성 ] 버튼을클릭합니다 6 / 33

서비스명 : GiGA Genie AI를활용하기위한프로젝트명칭입니다. 개발시작일 : YYYY-MM-DD 형식으로 API를사용할시점을입력합니다. 개발종료일 : YYYY-MM-DD 형식으로 API 사용을종료할시점을입력합니다. 앱명 : 서비스의하위개념으로, 앱설명 : 해당앱의관리를위해필요한정보를텍스트로기술하시면됩니다사용자ID: ucloud biz 계정정보가노출됩니다. 위정보를입력한후신청버튼을클릭합니다. GiGA Genie AI API는 API 호출건수를기준으로사용한만큼과금됩니다. 서비스생성시개발시작일과개발종료일을입력할때요금때문에종료일을짧게설정하실필요는없습니다. GiGA Genie AI API 키확인 1. [GiGA Genie AI 키보기 ] 버튼을클릭합니다. 2. API 호출을위한 Client Key, Client ID, Client Secret 값을확인하실수있습니다. 7 / 33

3. API Key 가타인에게유출되지않도록유의하시기바랍니다. GIGA Genie AI API 사용전준비 키확인및파일다운로드 1. GiGA Genie AI API 키보기버튼을클릭합니다. 2. API 호출을위한 Client Key, Client ID, Client Secret값을확인하실수있습니다. Signature 생성 1. Signature는발급받은 client_id와 client_secret을이용해서생성합니다. 2. Signature는 timestamp를생성하고 client_id, timestamp을조합한 Text를 client_secret으로 sign 하는방식으로 digest 합니다. 3. timestamp 형식은 YYYYMMDD24hhmmssSSS 입니다. (milliseconds 3자리까지 ) ex) 20180425113110123 4. Signature는 hex string으로최종생성합니다. Signature=HMAC-SHA256(client_secret, client_id+ : +timestamp) GiGA Genie AI 영상분석 API 개요및안내사항영상분석 API는이미지파일에서얼굴을검출후검출된얼굴에대한분석을통하여연령, 성별, 표정, 특징값을제공하고특징값비교로두얼굴간의유사율을제공하는 HTTP 기반 REST API입니다. * 이미지업로드후이미지에대한검출 / 분석 / 인식요청이가능하며업로드된이미지의 8 / 33

유효시간은 30분입니다. * 얼굴분석 / 인식을위해이미지내얼굴이너무작거나정면에서촬영된얼굴이아닐경우검출이되지않습니다. * 지원하는이미지포멧은 JPEG, BMP, PNG 이며파일사이즈는 5MByte까지허용됩니다. * 지원하는이미지해상도는 320 * 240 이상 1920 * 1080 이하입니다. GiGA Genie AI 영상분석이미지업로드 API 명세 BaseURL Method Request Params https://visionkit.gigagenie.ai/api/v1/upload POST Method Name Desc command Upload 고정 client_id 발급받은 client_id timestamp Signature 생성 Timestamp signature Signature 값 imagecontent 이미지파일 (multipart/form) JSON 규격의이미지등록결과및이미지ID Response Body Response Params ex> { resultcode: 0000, resultmessage: success, imageuuid: 8fdee9b1e8434aaeb0ae92c77bde79631 Name Desc resultcode 결과코드 0000: 정상, 그외오류 resultmessage 결과메시지 imageuuid 업로드한이미지의 ID Sample Code 1. node.js const crypto = require('crypto'); const fs = require('fs'); const request = require('request'); const http = require('http'); const dateformat = require('dateformat'); function gettimestamp(){ 9 / 33

return dateformat(new Date(),'yyyymmddHHmmssl'); ; function createsignature(id, timestamp, secret){ return crypto.createhmac('sha256', secret).update(id + ':' + timestamp).digest('hex'); ; const command = 'Upload'; const baseurl = 'https://visionkit.gigagenie.ai/api/v1/upload'; const client_id = '[YOUR_CLIENT_ID]'; const client_secret = '[YOUR_CLIENT_SECRET]'; const timestamp = gettimestamp(); const signature = createsignature(client_id, timestamp, client_secret); const filepath = '[IMAGE_FILE_PATH]'; var requestparam = { 'client_id' : client_id, 'signature' : signature, 'timestamp' : timestamp, 'command' : command, 'imagecontent' : fs.createreadstream(filepath) ; request.post({ url: baseurl, formdata: requestparam, function(error, response, body) { if(error) { console.log(err); return; if (response.statuscode == '200') { var parsed = JSON.parse(body); console.log('resultcode : ' + parsed.resultcode); console.log('resultmessage : ' + parsed.resultmessage); if (parsed.resultcode == '0000') { console.log('imageuuid : ' + parsed.imageuuid); ); 2. Python import requests import datetime import hmac import hashlib import json 10 / 33

command = 'Upload' url = 'https://visionkit.gigagenie.ai/api/v1/upload' client_id = '[YOUR_CLIENT_ID]' client_secret = '[YOUR_CLIENT_SECRET]' timestamp = datetime.datetime.now().strftime("%y%m%d%h%m%s%f")[:-3] imagecontent = {'imagecontent': open('image_file_path', 'rb') #python 2.x signature = hmac.new(client_secret, client_id + ':' + timestamp, hashlib.sha256).hexdigest() #python 3.x #signature = hmac.new(bytes(client_secret, 'utf8'), bytes(client_id + ':' + timestamp, 'utf8'), hashlib.sha256).hexdigest() requestparam = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command':command response = requests.post(baseurl, params=requestparam, files=imagecontent) print(response.text) 3. JAVA import java.io.file; import java.io.ioexception; import java.io.unsupportedencodingexception; import java.net.httpurlconnection; import java.security.invalidkeyexception; import java.security.nosuchalgorithmexception; import java.text.simpledateformat; import java.util.date; import java.util.locale; import javax.crypto.mac; import javax.crypto.spec.secretkeyspec; import org.apache.http.httpentity; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.entity.contenttype; import org.apache.http.entity.mime.multipartentitybuilder; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.util.entityutils; 11 / 33

public class ImageUploadTest { public static void main(string[] args) { boolean iserror = false; SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.KOREA); String command = "Upload"; String baseurl = "https://visionkit.gigagenie.ai/api/v1/upload"; String clientid = "[YOUR_CLIENT_ID]"; String clientsecret = "[YOUR_CLIENT_SECRET]"; String timestamp = dateformat.format(new Date()); String signature = null; try { signature = hmacdigest(clientid, timestamp, clientsecret); catch (InvalidKeyException UnsupportedEncodingException NoSuchAlgorithmException e) { e.printstacktrace(); iserror = true; if (!iserror) { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpEntity entity = MultipartEntityBuilder.create().addTextBody("command", command).addtextbody("client_id", clientid).addtextbody("timestamp", timestamp).addtextbody("signature", signature).addbinarybody("imagecontent", new File("[IMAGE_FILE_PAHT]"),ContentType.MULTIPART_FORM_DATA, "[IMAGE_FILE_NAME]").build(); HttpPost httppost = new HttpPost(baseURL); httppost.setentity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httppost); if (response!= null && response.getstatusline()!= null) { if (response.getstatusline().getstatuscode() == HttpURLConnection.HTTP_OK) { String resultstr = EntityUtils.toString(response.getEntity()); System.out.println(resultStr); else { System.out.println("Error : HTTP StatusCode is " + response.getstatusline().getstatuscode()); catch (IOException e) { e.printstacktrace(); 12 / 33

finally { if (response!= null) { try { response.close(); catch (IOException e) { e.printstacktrace(); response = null; if (httpclient!= null) { try { httpclient.close(); catch (IOException e) { e.printstacktrace(); httpclient = null; private static String hmacdigest(string clientid, String timestamp, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { String digest = null; SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); String digesttarget = clientid + ":" + timestamp; byte[] bytes = mac.dofinal(digesttarget.getbytes("ascii")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); hash.append(hex); digest = hash.tostring(); hash = null; return digest; 13 / 33

GiGA Genie AI 영상분석얼굴검출 API 명세 * 사전조건 - GiGA Genie AI 영상분석이미지업로드 API 를통하여응답받은 imageuuid BaseURL Method Request Params Response Body Response Params https://api.ucloudbiz.olleh.com/ai/v1/client/api POST Method Name Desc command Detection ( 고정 ) client_id 발급받은 client_id timestamp Signature 생성 Timestamp signature Signature 값 imageuuid 이미지등록후응답받은 imageuuid JSON 규격의얼굴검출결과 ex> { resultcode: 0000, resultmessage: Success, analysisresult: [ { faceid: xxxxx-xxxxx-xxxxx-xxxxxx-xxxxxxxx, facerectangle: {x: 10, y: 10, width: 20, heigth: 30, faceattribute: { landmark: [ {x: 1.22, y: 3.32,..., {x: 1.22, y: 3.32 ],... Name Desc 자료형 resultcode 결과코드 0000: 정상, 그외오류 String resultmessage 결과메시지 String analysisresult 얼굴검출결과목록 AnalysisResult Request/Response 자료형정의 Name Desc 자료형 AnalysisResult 검출된얼굴에부여된 1회성아 faceid 이디로영상분석서버로얼굴분석 String 요청시사용 14 / 33

FaceRectangle FaceAttribute Location facerectangle 검출된얼굴의영역 (x, y, w, h) FaceRectangle Name Desc 자료형 x 검출된얼굴의 X 좌표 int y 검출된얼굴의 Y 좌표 int width 검출된얼굴의너비 int height 검출된얼굴의높이 int Name Desc 자료형 landmark 70개로구성된얼굴과눈 / 코 / 입에대한경계선좌표 (x, y) 값목록 Location[] Name Desc 자료형 x 얼굴 X 좌표 float y 얼굴 Y 좌표 float Sample Code 1. node.js const crypto = require('crypto'); const request = require('request'); const http = require('http'); const dateformat = require('dateformat'); function gettimestamp(){ return dateformat(new Date(),'yyyymmddHHmmssl'); ; function createsignature(id,timestamp,secret){ return crypto.createhmac('sha256',secret).update(id+':'+timestamp).digest('hex'); ; const command = 'Detection'; const url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api'; const client_id = '[YOUR_CLIENT_ID]'; const client_secret = '[YOUR_CLIENT_SECRET]'; const timestamp = gettimestamp(); const signature = createsignature(client_id, timestamp, client_secret); const imageuuid = '[ 이미지등록후응답받은 imageuuid]'; var requestjson = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command': command, 'imageuuid': imageuuid ; 15 / 33

request.post({ url:url, json:requestjson, function(err, response, body) { if(err) { console.log(err); return; if (response.statuscode == '200') { console.log('resultcode : ' + body.resultcode); console.log('resultmessage : ' + body.resultmessage); if (body.resultcode == '0000') { console.log('analysisresult[0].faceid : ' + body.analysisresult[0].faceid); console.log('analysisresult[0].facerectangle : ' + body.analysisresult[0].facerectangle.x + ',' + body.analysisresult[0].facerectangle.y+ ',' + body.analysisresult[0].facerectangle.width + ',' + body.analysisresult[0].facerectangle.height); ); 2. Python import requests import datetime import hmac import hashlib import json command = 'Detection' url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api' client_id = '[YOUR_CLIENT_ID]' client_secret = '[YOUR_CLIENT_SECRET]' timestamp = datetime.datetime.now().strftime("%y%m%d%h%m%s%f")[:-3] imageuuid = '[ 이미지등록후응답받은 imageuuid]' #python 2.x signature = hmac.new(client_secret, client_id + ':' + timestamp, hashlib.sha256).hexdigest() #python 3.x #signature = hmac.new(bytes(client_secret, 'utf8'), bytes(client_id + ':' + timestamp, 'utf8'), hashlib.sha256).hexdigest() requestparam = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command':command, 16 / 33

'imageuuid':imageuuid response = requests.post(baseurl, json=requestparam) print response.text 3. JAVA import java.io.ioexception; import java.io.unsupportedencodingexception; import java.net.httpurlconnection; import java.security.invalidkeyexception; import java.security.nosuchalgorithmexception; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.locale; import java.util.map; import javax.crypto.mac; import javax.crypto.spec.secretkeyspec; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.util.entityutils; import com.google.gson.gson; public class FaceDetectionTest { public static void main(string[] args) { boolean iserror = false; SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.KOREA); String command = "Detection"; String baseurl = "https://api.ucloudbiz.olleh.com/ai/v1/client/api"; String clientid = "[YOUR_CLIENT_ID]"; String clientsecret = "[YOUR_CLIENT_SECRET]"; String timestamp = dateformat.format(new Date()); String signature = null; String imageuuid = "[ 이미지등록후응답받은 imageuuid]"; try { signature = hmacdigest(clientid, timestamp, clientsecret); catch (InvalidKeyException UnsupportedEncodingException NoSuchAlgorithmException e) { e.printstacktrace(); iserror = true; 17 / 33

if (!iserror) { Map<String, String> parammap = new HashMap<String, String>(); parammap.put("command", command); parammap.put("client_id", clientid); parammap.put("timestamp", timestamp); parammap.put("signature", signature); parammap.put("imageuuid", imageuuid); Gson gson = new Gson(); String jsonstr = gson.tojson(parammap); gson = null; StringEntity postingstring = new StringEntity(jsonStr, "UTF-8"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost http = new HttpPost(baseURL); http.setheader("content-type", "application/json"); http.setentity(postingstring); CloseableHttpResponse response = null; try { response = httpclient.execute(http); if (response!= null && response.getstatusline()!= null) { if (response.getstatusline().getstatuscode() == HttpURLConnection.HTTP_OK) { String resultstr = EntityUtils.toString(response.getEntity()); System.out.println(resultStr); else { System.out.println("Error : HTTP StatusCode is " + response.getstatusline().getstatuscode()); catch (IOException e) { e.printstacktrace(); finally { if (response!= null) { try { response.close(); catch (IOException e) { e.printstacktrace(); response = null; if (httpclient!= null) { try { httpclient.close(); catch (IOException e) { 18 / 33

e.printstacktrace(); httpclient = null; private static String hmacdigest(string clientid, String timestamp, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { String digest = null; SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); String digesttarget = clientid + ":" + timestamp; byte[] bytes = mac.dofinal(digesttarget.getbytes("ascii")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); hash.append(hex); digest = hash.tostring(); hash = null; return digest; 19 / 33

GiGA Genie AI 영상분석얼굴분석 API 명세 * 사전조건 - GiGA Genie AI 영상분석이미지업로드 API를통하여응답받은 imageuuid - GiGA Genie AI 영상분석얼굴검출 API의결과로응답받은 landmark가존재하는 faceid BaseURL Method Request Params https://api.ucloudbiz.olleh.com/ai/v1/client/api POST Method Name Desc command Analysis ( 고정 ) client_id 발급받은 client_id timestamp Signature 생성 Timestamp signature Signature 값 imageuuid 이미지등록후응답받은 imageuuid 이미지검출시응답값으로받은 faceid를전달 faceid * imageuuid 내여러얼굴에대한분석을요청 시 faceid들을콤마 (,) 로연결하여전달 expressionyn 얼굴표정결과검출요청여부 (Y or N) ageyn 연령결과검출요청여부 (Y or N) genderyn 성별결과검출요청여부 (Y or N) featureyn 얼굴특징값검출요청여부 (Y or N) JSON 규격의얼굴분석결과 Response Body ex> { resultcode: 0000, resultmessage: Success, analysisresult: [ { faceid: xxxxx-xxxxx-xxxxx-xxxxxx-xxxxxx, faceattribute: { expression: 1, age: 10, gender: 1, feature: [2243.22, 2522.522,..., 6763.72],. ] 20 / 33

Response Params Name Desc 자료형 resultcode 결과코드 0000: 정상, 그외오류 String resultmessage 결과메시지 String analysisresult 얼굴검출결과목록 AnalysisResult 자료형정의 AnalysisResult FaceAttribute Name Desc 자료형 faceid 검출된얼굴에부여된 1회성아이디로영상분석서버로얼굴분석 String 요청시사용 faceattribute 검출된얼굴의속성 FaceAttribute Name Desc 자료형 표정코드 (-1: unknown, 1: expression neutral, 2: surprise, 3: angry, 4: int smile) age 분석된얼굴의연령 int gender 분석된얼굴의성별 (1: male, 2: female, 3: unknown) int feature 500개로구성된얼굴특징값 float[] Sample Code 1. node.js const crypto = require('crypto'); const request = require('request'); const http = require('http'); const dateformat = require('dateformat'); function gettimestamp(){ return dateformat(new Date(),'yyyymmddHHmmssl'); ; function createsignature(id,timestamp,secret){ return crypto.createhmac('sha256',secret).update(id+':'+timestamp).digest('hex'); ; const command = 'Analysis'; const url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api'; const client_id = '[YOUR_CLIENT_ID]'; const client_secret = '[YOUR_CLIENT_SECRET]'; const timestamp = gettimestamp(); const signature = createsignature(client_id, timestamp, client_secret); const imageuuid = '[ 이미지등록후응답받은 imageuuid]'; 21 / 33

const faceid = '[ 얼굴검출후응답받은 faceid]'; var requestjson = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command': command, 'imageuuid': imageuuid, 'faceid': faceid, 'expressionyn': 'Y', 'ageyn': 'Y', 'genderyn': 'Y', 'featureyn': 'Y' ; request.post({ url:url, json:requestjson, function(err, response, body) { if(err) { console.log(err); return; if (response.statuscode == '200') { console.log('resultcode : ' + body.resultcode); console.log('resultmessage : ' + body.resultmessage); if (body.resultcode == '0000') { console.log('faceid : ' + body.analysisresult[0].faceid); console.log('faceattribute : ' + body.analysisresult[0].faceattribute.expression); console.log('age : ' + body.analysisresult[0].faceattribute.age); console.log('gender : ' + body.analysisresult[0].faceattribute.gender); console.log('feature : ' + body.analysisresult[0].faceattribute.feature); ); 2. Python import requests import datetime import hmac import hashlib import json command = 'Analysis' url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api' 22 / 33

client_id = '[YOUR_CLIENT_ID]' client_secret = '[YOUR_CLIENT_SECRET]' timestamp = datetime.datetime.now().strftime("%y%m%d%h%m%s%f")[:-3] imageuuid = '[ 이미지등록후응답받은 imageuuid]' faceid = '[ 얼굴검출후응답받은 faceid]' #python 2.x signature = hmac.new(client_secret, client_id + ':' + timestamp, hashlib.sha256).hexdigest() #python 3.x #signature = hmac.new(bytes(client_secret, 'utf8'), bytes(client_id + ':' + timestamp, 'utf8'), hashlib.sha256).hexdigest() requestparam = { 'client_id': client_id, 'signature': signature, 'timestamp': timestamp, 'command': command, 'imageuuid': imageuuid, 'faceid': faceid, 'expressionyn': 'Y', 'ageyn': 'Y', 'genderyn': 'Y', 'featureyn': 'Y' response = requests.get(baseurl, json=requestparam) print response.text 3. JAVA import java.io.ioexception; import java.io.unsupportedencodingexception; import java.net.httpurlconnection; import java.security.invalidkeyexception; import java.security.nosuchalgorithmexception; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.locale; import java.util.map; import javax.crypto.mac; import javax.crypto.spec.secretkeyspec; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.closeablehttpclient; 23 / 33

import org.apache.http.impl.client.httpclients; import org.apache.http.util.entityutils; import com.google.gson.gson; public class FaceAnalysisTest { public static void main(string[] args) { boolean iserror = false; SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.KOREA); String command = "Analysis"; String baseurl = "https://api.ucloudbiz.olleh.com/ai/v1/client/api"; String clientid = "[YOUR_CLIENT_ID]"; String clientsecret = "[YOUR_CLIENT_SECRET]"; String timestamp = dateformat.format(new Date()); String signature = null; String imageuuid = "[ 이미지등록후응답받은 imageuuid]"; // imageuuid 내여러얼굴의 faceid 를콤마 (,) 구분자로연결하여여러얼굴분석가능 String faceid = "[ 얼굴검출후응답받은 faceid]"; try { signature = hmacdigest(clientid, timestamp, clientsecret); catch (InvalidKeyException UnsupportedEncodingException NoSuchAlgorithmException e) { e.printstacktrace(); iserror = true; if (!iserror) { Map<String, String> parammap = new HashMap<String, String>(); parammap.put("command", command); parammap.put("client_id", clientid); parammap.put("timestamp", timestamp); parammap.put("signature", signature); parammap.put("imageuuid", imageuuid); parammap.put("faceid", faceid); parammap.put("expressionyn", "Y"); parammap.put("ageyn", "Y"); parammap.put("genderyn", "Y"); parammap.put("featureyn", "Y"); Gson gson = new Gson(); String jsonstr = gson.tojson(parammap); gson = null; StringEntity postingstring = new StringEntity(jsonStr, "UTF-8"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost http = new HttpPost(baseURL); http.setheader("content-type", "application/json"); 24 / 33

http.setentity(postingstring); CloseableHttpResponse response = null; try { response = httpclient.execute(http); if (response!= null && response.getstatusline()!= null) { if (response.getstatusline().getstatuscode() == HttpURLConnection.HTTP_OK) { String resultstr = EntityUtils.toString(response.getEntity()); System.out.println(resultStr); else { System.out.println("Error : HTTP StatusCode is " + response.getstatusline().getstatuscode()); catch (IOException e) { e.printstacktrace(); finally { if (response!= null) { try { response.close(); catch (IOException e) { e.printstacktrace(); response = null; if (httpclient!= null) { try { httpclient.close(); catch (IOException e) { e.printstacktrace(); httpclient = null; private static String hmacdigest(string clientid, String timestamp, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { String digest = null; SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); String digesttarget = clientid + ":" + timestamp; byte[] bytes = mac.dofinal(digesttarget.getbytes("ascii")); StringBuffer hash = new StringBuffer(); 25 / 33

for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); hash.append(hex); digest = hash.tostring(); hash = null; return digest; 26 / 33

GiGA Genie AI 영상분석얼굴인식 API 명세 * 사전조건 - GiGA Genie AI 영상분석얼굴분석 API를통하여응답받은 feature 값 - feature 값은이미지이미지등록 얼굴검출 얼굴분석을통하여얻을수있으며검출된 feature 값을통하여얼굴간의유사도분석에사용함 BaseURL Method Request Params https://api.ucloudbiz.olleh.com/ai/v1/client/api POST Method Name Desc command Recognition ( 고정 ) client_id 발급받은 client_id timestamp Signature 생성 Timestamp signature Signature 값얼굴인식을비교할첫번째 Feature 값 ( 얼굴분석요청을통하여응답받은값을사용 ) feature * feature 값을 JSON 형식의스트링으로변환후 Base64로인코딩하여전달얼굴인식을비교할두번째 Feature 값 ( 얼굴분석요청을통하여응답받은값을사용 ) comparefeature * feature 값을 JSON 형식의스트링으로변환후 Base64로인코딩하여전달 JSON 규격의얼굴분석결과 Response Body Response Params ex> { resultcode: 0000, resultmessage: Success, matchscore: 26.112, matchpercent: 67.11 Name Desc 자료형 resultcode 결과코드 0000: 정상, 그외오류 String resultmessage 결과메시지 String matchscore 두얼굴간분석된유사도점수 float matchpercent 두얼굴간분석된특징값의유사도백분율 float 27 / 33

Sample Code 1. node.js const crypto = require('crypto'); const request = require('request'); const http = require('http'); const dateformat = require('dateformat'); function gettimestamp(){ return dateformat(new Date(),'yyyymmddHHmmssl'); ; function createsignature(id,timestamp,secret){ return crypto.createhmac('sha256',secret).update(id+':'+timestamp).digest('hex'); ; const command = 'Recognition'; const url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api'; const client_id = '[YOUR_CLIENT_ID]'; const client_secret = '[YOUR_CLIENT_SECRET]'; const timestamp = gettimestamp(); const signature = createsignature(client_id, timestamp, client_secret); // feature, comparefeature= [ 얼굴분석요청을통하여응답받은특징값 ] ; const feature = "{feature:[43392416,-27651024,..,-71209304,1954622.9]"; const comparefeature = "{feature:[43392416,-27651024,..,-1384033.6,1954622.9]"; var requestjson = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command': command, 'feature': Buffer.from(feature).toString('base64'), 'comparefeature':buffer.from(comparefeature).tostring('base64') ; request.post({ url:url, json:requestjson, function(err, response, body) { if(err) { console.log(err); return; if (response.statuscode == '200') { console.log('resultcode : ' + body.resultcode); console.log('resultmessage : ' + body.resultmessage); if (body.resultcode == '0000') { 28 / 33

); console.log('matchscore : ' + body.matchscore); console.log('matchpercent : ' + body.matchpercent); 2. Python import requests import datetime import hmac import hashlib import json import base64 command = 'Recognition' url = 'https://api.ucloudbiz.olleh.com/ai/v1/client/api' client_id = '[YOUR_CLIENT_ID]' client_secret = '[YOUR_CLIENT_SECRET]' timestamp = datetime.datetime.now().strftime("%y%m%d%h%m%s%f")[:-3] #python 2.x signature = hmac.new(client_secret, message, hashlib.sha256).hexdigest() #python 3.x #signature = hmac.new(bytes(client_secret, 'utf8'), bytes(message, 'utf8'), hashlib.sha256).hexdigest() feature = '{feature:[43392416,-27651024,.,-1437471.5,1954622.9]'; comparefeature = '{feature:[43392416,-27651024,.,-1437471.5,1954622.9]'; feature_encode = base64.b64encode(feature) comparefeature_encode = base64.b64encode(comparefeature) requestparam = { 'client_id':client_id, 'signature':signature, 'timestamp':timestamp, 'command':command, 'feature': feature_encode, 'comparefeature':comparefeature_encode response = requests.post(baseurl, json=requestparam) print(response.text) 3. JAVA import java.io.ioexception; import java.io.unsupportedencodingexception; import java.net.httpurlconnection; 29 / 33

import java.nio.charset.standardcharsets; import java.security.invalidkeyexception; import java.security.nosuchalgorithmexception; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.locale; import java.util.map; import java.util.base64; import java.util.base64.encoder; import javax.crypto.mac; import javax.crypto.spec.secretkeyspec; import org.apache.http.client.methods.closeablehttpresponse; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.impl.client.httpclients; import org.apache.http.util.entityutils; import com.google.gson.gson; public class FaceRecognitionTest { public static void main(string[] args) { boolean iserror = false; SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.KOREA); Encoder encoder = Base64.getEncoder(); String command = "Recognition"; String baseurl = "https://api.ucloudbiz.olleh.com/ai/v1/client/api"; String clientid = "[YOUR_CLIENT_ID]"; String clientsecret = "[YOUR_CLIENT_SECRET]"; String timestamp = dateformat.format(new Date()); String signature = null; // 얼굴분석요청을통하여응답받은 json형태의 feature 값을 Base64로인코딩 String feature = new String(encoder.encode("{feature:[4.3392416E7,...,1954622.9]".getBytes(StandardCharsets.UTF_8))); String comparefeature = new String(encoder.encode("{feature:[-2.7651024E7,...,-1437471.5,1954622.9]".getBytes(StandardCharsets.UTF_8))); try { signature = hmacdigest(clientid, timestamp, clientsecret); catch (InvalidKeyException UnsupportedEncodingException NoSuchAlgorithmException e) { e.printstacktrace(); iserror = true; 30 / 33

if (!iserror) { Map<String, String> parammap = new HashMap<String, String>(); parammap.put("command", command); parammap.put("client_id", clientid); parammap.put("timestamp", timestamp); parammap.put("signature", signature); parammap.put("feature", feature); parammap.put("comparefeature", comparefeature); Gson gson = new Gson(); String jsonstr = gson.tojson(parammap); gson = null; StringEntity postingstring = new StringEntity(jsonStr, "UTF-8"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost http = new HttpPost(baseURL); http.setheader("content-type", "application/json"); http.setentity(postingstring); CloseableHttpResponse response = null; try { response = httpclient.execute(http); if (response!= null && response.getstatusline()!= null) { if (response.getstatusline().getstatuscode() == HttpURLConnection.HTTP_OK) { String resultstr = EntityUtils.toString(response.getEntity()); System.out.println("result is " + resultstr); else { System.out.println("Error : HTTP StatusCode is " + response.getstatusline().getstatuscode()); catch (IOException e) { e.printstacktrace(); finally { if (response!= null) { try { response.close(); catch (IOException e) { e.printstacktrace(); response = null; if (httpclient!= null) { try { httpclient.close(); catch (IOException e) { e.printstacktrace(); 31 / 33

httpclient = null; private static String hmacdigest(string clientid, String timestamp, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { String digest = null; SecretKeySpec key = new SecretKeySpec((secret).getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); String digesttarget = clientid + ":" + timestamp; byte[] bytes = mac.dofinal(digesttarget.getbytes("ascii")); StringBuffer hash = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { hash.append('0'); hash.append(hex); digest = hash.tostring(); hash = null; return digest; Result Code resultcode Code Desc 0000 success 1001 missing mandatory parameter 1002 parameter value error 1003 unsupported protocols 1004 non-existent image UUID 1005 non-existent face ID 32 / 33

1006 Base64 decoding error 1007 json grammar error 1008 unsupported image resolution 1009 unsupported image format 1010 over file capacity 2001 no detected faces 2002 facial analysis failure 2003 feature similarity analysis failure 3001 Signature 불일치 3002 존재하지않는 ClientID 3003 호출제한초과 3004 시스템에러 33 / 33