1. 程式人生 > >Python 訪問騰訊人臉融合介面

Python 訪問騰訊人臉融合介面

response_data = {}

	url = 'http://aiconsole.cloud.tencent.com/fuseapi/face'

	appid        = "xxxx"
	bucket       = ""
	secret_id    = "yyyyyyy"
	secret_key   = "zzzzzzzzzz"
	expired      = str((int)(time.time()) + 2592000)
	onceExpired  = 0
	current      = str((int)(time.time()))
	rdm          = str(random.randint(1, 10000))
	userid       = "0"
	fileid       = "tencentyunSignTest"
	
	srcStr       = 'a=' + appid + '&b=' + bucket + '&k=' + secret_id + '&e=' + expired + '&t=' + current + '&r=' + rdm + '&u=' + userid + '&f='
	print(srcStr)
	my_sign = hmac.new(secret_key.encode('utf-8'), srcStr.encode('utf-8'), sha1).digest()
	print(my_sign)
	signStr      = base64.b64encode(my_sign + srcStr.encode('utf-8'))
	print(signStr)

	headers = { 'Authorization' : signStr }
	# request.('Authorization', signStr)

	values = {'rsp_img_type' : 'url',  
			'project_id' : 'project_id',  
			'appid' : 'appid',
			"uin" : "uin",
			"img_data" : img_data,
			"model_id" : "model_id" }  

	req = request.Request(url, headers=headers)
	# with request.urlopen(req, data=bytes(json.dumps(values), "utf-8")) as f:
	# 	print(f.read().decode('utf-8'))
	response = request.urlopen(req, data=bytes(json.dumps(values), "utf-8")).read().decode('utf-8') # , data=bytes(json.dumps(headers), encoding="utf-8")
	# reponse = 
	print(response)
	response = json.loads(response)
	# data = None
	# req = urllib2.Request(url, data, headers)
	if response["ret"] == "0" :
		nowtime = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S_%f')

		img_url = response["img_url"]

		with request.urlopen(img_url) as f:
			img_file = os.path.join('static', 'upload', nowtime + "_tx.jpg")
			fhandle2 = open(img_file,'wb')
			fhandle2.write(f.read())
			fhandle2.close()

		response_data['output_file'] = nowtime + "_tx.jpg"
		response_data['msg'] =  "成功"
	elif (response["ret"] == "1000" or response["ret"] == "-4" or response["ret"] == "-8") :
		response_data['msg'] =  "未能識別照片中的頭像,請重新上傳"
	else :
		response_data['msg'] =  response["ret"]
	return response_data