def authenticate(self, access, signature, params, verb='GET', server_string='127.0.0.1:8773', path='/', verify_signature=True): # TODO: Check for valid timestamp (access_key, sep, project_name) = access.partition(':') user = self.get_user_from_access_key(access_key) if user == None: raise exception.NotFound('No user found for access key') if project_name is '': project_name = user.name project = self.get_project(project_name) if project == None: raise exception.NotFound('No project called %s could be found' % project_name) if not user.is_admin() and not project.has_member(user): raise exception.NotFound('User %s is not a member of project %s' % (user.id, project.id)) if verify_signature: # hmac can't handle unicode, so encode ensures that secret isn't unicode expected_signature = signer.Signer(user.secret.encode()).generate( params, verb, server_string, path) logging.debug('user.secret: %s', user.secret) logging.debug('expected_signature: %s', expected_signature) logging.debug('signature: %s', signature) if signature != expected_signature: raise exception.NotAuthorized('Signature does not match') return (user, project)
def asr_sentence_aksk(_ak, _sk, data, url, encode_type='wav', sample_rate='8k'): _url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/voice/asr/sentence" sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk if data != '': data = data.decode("utf-8") _data = { "url": url, "data": data, "encode_type": encode_type, "sample_rate": sample_rate } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = "ais.cn-north-1.myhuaweicloud.com" kreq.uri = "/v1.0/voice/asr/sentence" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib.request.Request(url=_url, data=bytes(kreq.body), headers=kreq.headers) r = urllib.request.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError as e: resp = e.read() status_code = e.code except URLError as e: resp = e.read() status_code = e.code else: status_code = r.code resp = r.read() return resp.decode('utf-8')
def moderation_text_aksk(_ak, _sk, text, type='content', cattegories=[ "ad", "politics", "politics", "politics", "contraband", "contraband" ]): _url = 'https://ais.cn-north-1.myhuaweicloud.com/v1.0/moderation/text' sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "categories": cattegories, "items": [{ "text": text, "type": type }] } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = "ais.cn-north-1.myhuaweicloud.com" kreq.uri = "/v1.0/moderation/text" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib.request.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib.request.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError as e: resp = e.read() status_code = e.code except URLError as e: resp = e.read() status_code = e.code else: status_code = r.code resp = r.read() return resp.decode('utf-8')
def recapture_detect_aksk(_ak, _sk, image, url, threshold=0.95, scene=None): _url = 'https://ais.cn-north-1.myhuaweicloud.com/v1.0/image/recapture-detect' sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk if image != '': image = image.decode('utf-8') _data = { "image": image, "url": url, "threshold": threshold, "scene": scene, } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = "ais.cn-north-1.myhuaweicloud.com" kreq.uri = "/v1.0/image/recapture-detect" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib.request.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib.request.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError as e: resp = e.read() status_code = e.code except URLError as e: resp = e.read() status_code = e.code else: status_code = r.code resp = r.read() return resp.decode('utf-8')
def image_antiporn_aksk(_ak, _sk, image_str=None, url=None): sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk print( request_moderation_url_aksk(sig, '/v1.1/moderation/image/anti-p**n', image_str, url)) print( request_moderation_url_aksk(sig, '/v1.0/moderation/image', image_str, url))
def moderation_text_aksk(_ak, _sk, text, type='content', categories=[ "ad", "politics", "politics", "politics", "contraband", "contraband" ]): _url = 'https://%s/v1.0/moderation/text' % ais.AisEndpoint.MODERATION_ENDPOINT sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "categories": categories, # 检测场景 Array politics:涉政 p**n:涉黄 ad:广告 abuse:辱骂 contraband:违禁品 flood:灌水 "items": [{ "text": text, "type": type } # items: 待检测的文本列表 text 待检测文本 type 文本类型 ] } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = ais.AisEndpoint.MODERATION_ENDPOINT kreq.uri = "/v1.0/moderation/text" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def tts_aksk(_ak, _sk, text, voice_name='xiaoyan', volume='0', sample_rate='16k', speech_speed='0', pitch_rate='0'): _url = 'https://%s/v1.0/voice/tts' % ais.AisEndpoint.TTS_ENDPOINT sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "text": text, "voice_name": voice_name, "volume": volume, "sample_rate": sample_rate, "speech_speed": speech_speed, "pitch_rate": pitch_rate } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = ais.AisEndpoint.TTS_ENDPOINT kreq.uri = "/v1.0/voice/tts" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def image_tagging_aksk(_ak, _sk, image, url, languzge, limit=-1, threshold=0.0): endpoint = utils.get_endpoint(ais.AisService.IMAGE_SERVICE) _url = 'https://%s/v1.0/image/tagging' % endpoint sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "image": image, "url": url, "language": languzge, "limit": limit, "threshold": threshold } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = endpoint kreq.uri = "/v1.0/image/tagging" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def asr_sentence_aksk(_ak, _sk, data, url, encode_type='wav', sample_rate='8k'): _url = "https://%s/v1.0/voice/asr/sentence" % ais.AisEndpoint.ASR_ENDPOINT sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "url": url, "data": data, "encode_type": encode_type, "sample_rate": sample_rate } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = ais.AisEndpoint.ASR_ENDPOINT kreq.uri = "/v1.0/voice/asr/sentence" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def moderation_image_aksk(_ak, _sk, image, url, categories=None, threshold=None): _url = 'https://%s/v1.0/moderation/image' % ais.AisEndpoint.MODERATION_ENDPOINT sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "image": image, "url": url, "categories": categories, "threshold": threshold, } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = ais.AisEndpoint.MODERATION_ENDPOINT kreq.uri = "/v1.0/moderation/image" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) r = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def long_sentence_aksk(_ak, _sk, data, url=''): sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk status, r = _long_sentence_aksk(sig, data, url) if status != 200: print 'Process long sentence asr failed: summit job failed.' return '' submit_result = json.loads(r) job_id = submit_result['result'].get('job_id', '') print "Process job id is :", job_id words = '' time.sleep(1.0) try: while True: status, r = _get_result_aksk(sig, job_id) if status != 200: print 'Process long sentence asr failed: get result failed.' break rec_result = json.loads(r) process_status = rec_result["result"].get('status_code', 1) if process_status == -1: print 'Process long sentence asr failed: get result failed.' break elif process_status == 2: words = rec_result["result"].get('words', '') break # # process_status == 0 || process_status == 1 # else: time.sleep(2.0) continue except Exception: return '' return words
def moderation_video_aksk(_ak, _sk, url, frame_interval=5, categories=['politics', 'terrorism']): sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk endpoint = utils.get_endpoint(ais.AisService.MODERATION_SERVICE) status, r = _moderation_video_aksk(endpoint, sig, url, frame_interval, categories) if status != 200: return r submit_result = json.loads(r) job_id = submit_result['result'].get('job_id', '') #print "Process job id is :", job_id time.sleep(1.0) try: while True: status, r = _get_result_aksk(endpoint, sig, job_id) if status != 200: return r rec_result = json.loads(r) process_status = rec_result["result"].get('status') if process_status == 'failed': return r elif process_status == 'finish': return r # # process_status == 0 || process_status == 1 # else: time.sleep(2.0) continue except Exception: return ''
def moderation_video_aksk(_ak, _sk, url, frame_interval=5, categories=['politics', 'terrorism']): sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk status, r = _moderation_video_aksk(sig, url, frame_interval, categories) if status != 200: print('Process moderation vedio asr failed: summit job failed.') return '' submit_result = json.loads(r) job_id = submit_result['result'].get('job_id', '') print("Process job id is :", job_id) time.sleep(1.0) try: while True: status, r = _get_result_aksk(sig, job_id) if status != 200: print( 'Process moderation video asr failed: get result failed.') break rec_result = json.loads(r) process_status = rec_result["result"].get('status') if process_status == 'failed': return r elif process_status == 'finish': return r # # process_status == 0 || process_status == 1 # else: time.sleep(2.0) continue except Exception: return ''
def authenticate(self, params, signature, verb='GET', server_string='127.0.0.1:8773', path='/'): # TODO: Check for valid timestamp access_key = params['AWSAccessKeyId'] user = self.get_user_from_access_key(access_key) if user == None: return None expected_signature = signer.Signer(user.secret).generate( params, verb, server_string, path) _log.debug('user.secret: %s', user.secret) _log.debug('expected_signature: %s', expected_signature) _log.debug('signature: %s', signature) if signature == expected_signature: return user
def image_batch_jobs_aksk(_ak, _sk, urls, categories=['politics', 'terrorism']): sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk status, r = _image_batch_jobs_aksk(sig, urls, categories) if status != 200: return r submit_result = json.loads(r) job_id = submit_result['result'].get('job_id', '') # print "Process job id is :", job_id time.sleep(1.0) try: while True: status, r = _get_result_aksk(sig, job_id) if status != 200: return r rec_result = json.loads(r) process_status = rec_result["result"].get('status') if process_status == 'failed': return r elif process_status == 'finish': return r # # process_status == 0 || process_status == 1 # else: time.sleep(2.0) continue except Exception: return ''
def asr_bgm_aksk(_ak, _sk, url): _url = 'https://ais.cn-north-1.myhuaweicloud.com/v1.0/bgm/recognition' sig = signer.Signer() sig.AppKey = _ak sig.AppSecret = _sk _data = { "url": url, } kreq = signer.HttpRequest() kreq.scheme = "https" kreq.host = "ais.cn-north-1.myhuaweicloud.com" kreq.uri = "/v1.0/bgm/recognition" kreq.method = "POST" kreq.headers = {"Content-Type": "application/json"} kreq.body = json.dumps(_data) resp = None status_code = None try: sig.Sign(kreq) # # Here we use the unvertified-ssl-context, Because in FunctionStage # the client CA-validation have some problem, so we must do this. # _context = ssl._create_unverified_context() req = urllib2.Request(url=_url, data=kreq.body, headers=kreq.headers) resp = urllib2.urlopen(req, context=_context) # # We use HTTPError and URLError,because urllib2 can't process the 4XX & # 500 error in the single urlopen function. # # If you use a modern, high-level designed HTTP client lib, Yeah, I mean requests, # there is no this problem. # except HTTPError, e: resp = e.read() status_code = e.code
def __init__(self, AK, SK): self.sign = signer.Signer() self.sign.Key = AK self.sign.Secret = SK
def __init__(self): self.sign = signer.Signer() self.sign.Key = os.environ["HW_ACCESSKEY_ID"] #AK:BO9xxxxx self.sign.Secret = os.environ["HW_ACCESSKEY_SECRET"] # SK:cxBxxxxx