1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| import hashlib import time, random, base64, json
import id_key app_id = id_key.dic['qq']['id'] app_key = id_key.dic['qq']['key']
api_url='https://api.ai.qq.com/fcgi-bin/aai/aai_asr'
def md5(string): md = hashlib.md5() md.update(string) md5 = md.hexdigest().upper() return md5
def signify(args, app_key): query_str = urlencode(args) query_str = query_str + '&app_key=' + app_key signiture = md5(query_str.encode('utf-8')) return signiture
import urllib
def urlencode(args): tuples = [(k, args[k]) for k in sorted(args.keys()) if args[k]] query_str = urllib.parse.urlencode(tuples) return query_str
import requests def http_post(api_url, args): resp = requests.post(url=api_url, data=args) resp = json.loads(resp.text) return resp
class BaseASR(object): ext2idx = {'pcm': '1', 'wav': '2', 'amr': '3', 'slk': '4'}
def __init__(self, api_url, app_id, app_key): self.api_url = api_url self.app_id = app_id self.app_key = app_key
def stt(self, audio_file, ext, rate): raise Exceptin("Unimplemented!")
class BasicASR(BaseASR): """ Online ASR from Tencent https://ai.qq.com/doc/aaiasr.shtml """ def __init__(self): super(BasicASR, self).__init__(api_url, app_id, app_key)
def stt(self, audio_file, ext='pcm', rate=16000): if ext == 'pcm': f = open(audio_file, 'rb') audio_data = f.read() f.close() else: raise Exception("Unsupport audio file format!")
args = { 'app_id': self.app_id, 'time_stamp': str(int(time.time())), 'nonce_str': '%.x' % random.randint(1048576, 104857600), 'format': self.ext2idx[ext], 'rate': str(rate), 'speech': base64.b64encode(audio_data), }
signiture = signify(args, self.app_key) args['sign'] = signiture resp = http_post(self.api_url, args) print(resp) text = resp['data']['text'].encode('utf-8')
return text
import sys
asr_engine = BasicASR() text = asr_engine.stt(sys.argv[1]) print(text)
|