def top_match_txt(): CLIENT = LUISClient(luis_appid, luis_app_key, True) TEXT = request.data res = CLIENT.predict(TEXT) parsed = process_res(res) return json.dumps(calculate_scores(parsed['search'], parsed['coeff']))
def __init__(self, APPID, APPKEY): self.luis_processor = LUISClient(APPID, APPKEY, verbose=True) self.query_history = '' self._top_intent_history = '' self._entities_history = []
def understand(self, text): client = LUISClient(self.appid, self.appkey, True) res = client.predict(text) top = res.get_top_intent() entities = res.get_entities() entities = [(x.get_type(), x.get_name()) for x in entities] intent = top.get_name() result = LuisResult(intent, entities) return result
def IdentifyIntent(self): try: TEXT = self.inputQuery CLIENT = LUISClient(self.__APPID__, self.__APPKEY__, True) res = CLIENT.predict(TEXT) while res.get_dialog( ) is not None and not res.get_dialog().is_finished(): TEXT = raw_input(u'%s\n' % res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) #self.process_res(res) return res except Exception, exc: print(exc)
def luis_result(question): try: appid = '1e995b1e-35a7-4349-ae58-e90f9beb6cca' appkey = '9fa67485043a4605ab8e8220eb80a940' text = question client = LUISClient(appid, appkey, True) res = client.predict(text) print threading.current_thread( ).name, "luis result:", res.get_top_intent().get_name(), float( res.get_top_intent().get_score()) * 100, res.get_entities() return res.get_top_intent().get_name(), float( res.get_top_intent().get_score()) * 100, res.get_entities() except Exception, exc: print threading.current_thread().name, "luis get result error:", exc return "None", 0, None
def predict_intent(question): # 调用LUIS进行语义预测 client = LUISClient(APPID, APPKEY, True) res = client.predict(question) question = question.decode('utf-8') intent = res.get_top_intent().get_name() entList = [] ents = res.get_entities() for ent in ents: entList.append({ 'type': ent.get_type(), 'entity': question[ent.get_start_idx():ent.get_end_idx() + 1] }) return intent, entList
def make_request(self, message): """Send message from user to LUIS for intent analysis""" # Hard coded LUIS APP ID and Authoring Key APPID = self.LUIS_ID APPKEY = self.LUIS_KEY try: CLIENT = LUISClient(APPID, APPKEY, True) res = CLIENT.predict(message) while res.get_dialog() is not None and not res.get_dialog()\ .is_finished(): TEXT = input('%s\n' % res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) return res except Exception as exc: print(exc)
def get_luis_response(text): try: APPID = 'YOUR_LUIS_APP_ID' APPKEY = 'YOUR_LUIS_APP_KEY' CLIENT = LUISClient(APPID, APPKEY, True) res = CLIENT.predict(text) while res.get_dialog( ) is not None and not res.get_dialog().is_finished(): TEXT = raw_input(u'%s\n' % res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) reply = process_res(res) return reply except Exception, exc: print(exc) return "Sorry, something went wrong."
def preprocess(input_text): headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': '{49a3e79bc72f414db090cd8a2eeddc03}', } APPID = "cf321ffa-6919-4306-9ff1-2ec8fc81328c" APPKEY = "49a3e79bc72f414db090cd8a2eeddc03" TEXT = input_text CLIENT = LUISClient(APPID, APPKEY, True) res = CLIENT.predict(TEXT) while res.get_dialog() is not None and not res.get_dialog().is_finished(): TEXT = raw_input(u'%s\n' % res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) return process_res(res)
def __init__(self, map_key, speech_key, luis_appid, luis_appkey, gSheet_sskey, use_mic=True): self.map_key = map_key self.speech_key = speech_key self.luis = LUISClient(luis_appid, luis_appkey, True) self.gSheet = gSheet_Client(gSheet_sskey) self.use_mic = use_mic self.begin()
def handleMessage(self): # Echo message back to client message = self.data try: #Create a LUIS Client by passing in the APP ID and APP Key #Then uses the LUIS Client methods provided in the LUIS SDK CLIENT = LUISClient(APPID, APPKEY, True) response = CLIENT.predict(message) #The response received from LUIS predict would be passed in to process_res resp = process_res(response) self.sendMessage(resp) except Exception as exc: print(exc) self.sendMessage('I\'m sorry I do not understand you.')
def __handle_message_activity(self, activity): """ Handle the messages. STATE used to collect APPID and APPKEY up front. All other messsages sent to LUIS for parsing. APPID and APPKEY specify the LUIS service called via REST. For example: https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/((APPID))?subscription-key=((APPKEY)) &verbose=true&timezoneOffset=0&q=((TEXT-FOR-LUIS-TO-PARSE """ BotRequestHandler.STATE+=1 ## POORMAN'S STATE TRACKING self.send_response(200) self.end_headers() credentials = MicrosoftAppCredentials(APPID, APPPASSWORD) connector = ConnectorClient(credentials, base_url=activity.service_url) LUIStext = '' ## FIRST, GET APPID if self.STATE==1: if activity.text: BotRequestHandler.LUISAPPID=activity.text reply = BotRequestHandler.__create_reply_activity(activity, "You entered application ID: %s\nNow, please input your subscription key (default: %s):" % (activity.text,self.LUISAPPKEY)) ## SECOND, GET APPKEY elif self.STATE==2: if activity.text: BotRequestHandler.LUISAPPKEY=activity.text reply = BotRequestHandler.__create_reply_activity(activity, "Great! You entered application key: %s\nNow, enter some text for the LUIS model to render:" % activity.text) ## THIRD AND ONWARDS: SEND TEXT TO LUIS AND REPORT LUIS RESPONSE TO THE USER else: try: CLIENT = LUISClient(self.LUISAPPID, self.LUISAPPKEY, True) res = CLIENT.predict(activity.text) while res.get_dialog() is not None and not res.get_dialog().is_finished(): TEXT = input('%s\n'%res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) LUIStext=self.__handle_LUIS_response(res) reply = BotRequestHandler.__create_reply_activity(activity, 'LUIS says: %s' % LUIStext) except Exception as exc: LUIStext=exc print("Error: %s" % exc) reply = BotRequestHandler.__create_reply_activity(activity, 'About %s, LUIS complains: %s' % (activity.text,LUIStext)) connector.conversations.send_to_conversation(reply.conversation.id, reply)
def get_luis_response(self): try: client = LUISClient(self.appID, self.app_key, True) res = client.predict(self.text) while res.get_dialog( ) is not None and not res.get_dialog().is_finished(): self.text = input('%s\n' % res.get_dialog().get_prompt()) res = client.reply(self.text, res) return self.process_res(res) except Exception as exc: print(exc) return {}
class LuisWrapper(object): def __init__(self, APPID, APPKEY): self.luis_processor = LUISClient(APPID, APPKEY, verbose=True) self.query_history = '' self._top_intent_history = '' self._entities_history = [] def predict(self, query): ''' :param query: the end user's query :return: (top_intent, entities) ''' res = self.luis_processor.predict(query) return self.process_res(res) def process_res(self, res): ''' A function that processes the luis_response object and prints info from it. :param res: A LUISResponse object containing the response data. :return: the intent with best confidence, the entities. ''' self.query_history = res.get_query() top_intent = res.get_top_intent().get_name() self._top_intent_history = top_intent entities = res.get_entities() self._entities_history = entities for entity in res.get_entities(): print('"%s":' % entity.get_name()) print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) return top_intent, entities
def main(): # 12.06.2017, modified to auto-read saved preprocessed info. # # 31.08.2017 Ver2: allow multiple query and evaluate by keeping info in the allGeneFileNames.txt # parser = argparse.ArgumentParser(description='query LUIS web agent.') parser.add_argument('--testset', dest='testset', action='store', metavar='TESTSET', required=True, help='The testset dir to be used, value can be: default or specified. If specified specifyTestSetInfo.txt will be read.') parser.add_argument('--appid', dest='appid', action='store', metavar='APPID', required=True, help='The APPID from LUIS agent which you get when you create the agent.') parser.add_argument('--appkey', dest='appkey', action='store', metavar='APPKEY', required=True, help='The APPKEY from LUIS agent which you get when you create the agent.') args = parser.parse_args() appID = "" appKey = "" testset = "" if args.testset is not None: testset = args.testset else: raise RuntimeError,'Usage: python progName --testset default/specified --appid id --appkey key' if args.appid is not None: appID = args.appid else: raise RuntimeError,'Usage: python progName --testset default/specified --appid id --appkey key' if args.appkey is not None: appKey = args.appkey else: raise RuntimeError,'Usage: python progName --testset default/specified --appid id --appkey key' testset = testset.lower() rootDirTop = "../.." infoFile = rootDirTop + '/allGeneFileNames/allGeneFileNames.txt' dictkv = getDictInfoFromFile(infoFile) serviceName = dictkv["serviceName_LUIS"] trainset = dictkv["luisActuallyUsedTrainset"] resultsIdx = dictkv["luisLatestTestResultsIdx"] # used for label testResults dir to allow multiple tests crntIdx = int(resultsIdx) +1; srcFiles = [] trainTimeStamp = dictkv["timeStamp"] textTestsetDir = "" annoTestsetDir = "" # for saveInfo, used by evaluator if testset == "default": annoTestsetDir = dictkv["testSetAnnotated"] # testSetAnnotated was added when first generating data textTestsetDir = dictkv["testSetPureTextDir"] srcFiles = getFiles(textTestsetDir) else: testInfoFile = rootDirTop + '/allGeneFileNames/specifyTestSetInfo.txt' testsetkv = getDictInfoFromFile(testInfoFile) testTimeStamp = testsetkv["testTimeStamp"] testFileStr = testsetkv["testIntentFiles"] testDirPref = rootDirTop + "/preprocessResults/autoGeneFromRealAnno/autoGene_" testDirSuff = "/DomainIntentNoDupShuffleSubset_Test/text" textTestsetDir = testDirPref + testTimeStamp + testDirSuff annoTestsetDir = testDirPref + testTimeStamp + "/DomainIntentNoDupShuffleSubset_Test/annotated" if testFileStr == "full": srcFiles = getFiles(textTestsetDir) else: srcFiles = getFilesFromStr(testFileStr) srcBaseDir = textTestsetDir baseDestDir = rootDirTop + "/testResults/" + serviceName if(not os.path.exists(baseDestDir)): os.mkdir(baseDestDir) baseDestDir = baseDestDir + "/" + serviceName + "_TestResults_" + trainset + "_" + trainTimeStamp + "-" + str(crntIdx) if(not os.path.exists(baseDestDir)): os.mkdir(baseDestDir) # save saveinfo -- append to file: allGeneFileNames/allGeneFileNames.txt crntTimeStamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')[:-3] saveinfo =[] saveinfo.append("\n# ---- written by queryLuisAuto2.py:") saveinfo.append("crntTimeStamp=" + crntTimeStamp) saveinfo.append("luisLatestTestResultsIdx=" + str(crntIdx)) #TODO rasa would use serviceName saveinfo.append("luisLatestTestResultsDir=" + baseDestDir) # evaluater read this saveinfo.append("luisTestSetAnnotated=" + annoTestsetDir) # evaluator read this saveinfo.append("luisQueriedAppID="+ appID) saveinfo.append("luisQueriedAppKey="+ appKey) saveinfo.append("luisQueriedTestset="+ testset) write2fileAppend(infoFile, saveinfo) CLIENT = LUISClient(appID, appKey, True) srcBaseDir = textTestsetDir numUtt = 500 # maximum totalUttProcessed = 0 start_time=time.time() for i in range(len(srcFiles)): results = {'results': []} domainFile = srcFiles[i] print "srcFiles:" + domainFile fileUri = os.path.join(srcBaseDir, domainFile) print "fileUri:" + fileUri utterances = readFile2List(fileUri) num = numUtt if(num > len(utterances) ): num = len(utterances) print num for j in range(num): utt = utterances[j] utt = utt.lower() print "query:" + str(j) + " = " + utt res = CLIENT.predict(utt) res_j = process_res_json(res) results['results'].append(res_j) totalUttProcessed = totalUttProcessed +1 print "totalUttProcessed:" + str(totalUttProcessed) # wait a bit, then query again for another utt. # LUIS limit: 5 calls Per seconds, 10K calls per month for Free Account #time.sleep(0.3) # Time in seconds. # time.sleep(0.6) # Time in seconds. For Pay-As-You-Go account, 50 per second time.sleep(0.2) # 0.2 should be enough, as query itself takes time domainName = domainFile[0:domainFile.rfind(".")] print "domainName:" + domainName saveJson2File(baseDestDir, domainName, results) elapsed_time=time.time()-start_time print "==== LUIS query finished ==== Elapsed Time: " + str(elapsed_time)
else: print('Dialog Prompt: ' + res.get_dialog().get_prompt()) if res.get_dialog().get_parameter_name() is None: print('Dialog Parameter: None') else: print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name()) print('Dialog Status: ' + res.get_dialog().get_status()) print('Entities:') for entity in res.get_entities(): print('"%s":' % entity.get_name()) print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) def on_failure(err): ''' A callback function that processes the error object if the prediction fails. :param err: An Exception object. :return: None ''' print(err) try: APPID = 'b81195cb-904c-48ef-adaf-7b12c664dc42' APPKEY = '5efceb9fffa84210808ec4f48e3434d1' TEXT = input('Please input the text to predict:\n') CLIENT = LUISClient(APPID, APPKEY, True) CLIENT.predict(TEXT, {'on_success': on_success, 'on_failure': on_failure}) print('-------\nMain thread finishing!!\n-------') except Exception as exc: print(exc)
else: print(u'Dialog Prompt: ' + res.get_dialog().get_prompt()) if res.get_dialog().get_parameter_name() is None: print(u'Dialog Parameter: None') else: print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name()) print(u'Dialog Status: ' + res.get_dialog().get_status()) print(u'Entities:') for entity in res.get_entities(): print(u'"%s":' % entity.get_name()) print(u'Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) def on_failure(err): ''' A callback function that processes the error object if the prediction fails. :param err: An Exception object. :return: None ''' print err try: APPID = raw_input(u'Please enter your app Id:\n') APPKEY = raw_input(u'Please input your subscription key:\n') TEXT = raw_input(u'Please input the text to predict:\n') CLIENT = LUISClient(APPID, APPKEY, True) CLIENT.predict(TEXT, {u'on_success': on_success, u'on_failure': on_failure}) print u'-------\nMain thread finishing!!\n-------' except Exception, exc: print exc
class Voice_Sizer(): def __init__(self, map_key, speech_key, luis_appid, luis_appkey, gSheet_sskey, use_mic=True): self.map_key = map_key self.speech_key = speech_key self.luis = LUISClient(luis_appid, luis_appkey, True) self.gSheet = gSheet_Client(gSheet_sskey) self.use_mic = use_mic self.begin() # Starts voice flow, prompts user and sends to LUIS API def begin(self): response = self.ask_user('Hello, how can I help you?') print('user request: ', response) print('sending request to LUIS...') self.luis.predict(response, { 'on_success': self.operator, 'on_failure': lambda err: print(err) }) # Callback for LUIS Intent response. Routes intent to controller def operator(self, res): intent = res.get_top_intent().get_name() if intent == 'Create Sizing': self.text_to_speech('Got it, you would like to create a sizing.') print('Got it, you would like to create a sizing.') self.create_sizing() elif intent == 'Something Else': self.text_to_speech( 'Ok, I have understood that you do not know what you would like. Typical. Here\'s a fascinating thought.' ) print('???') self.get_thought() else: print('I\'m sorry, I didn\'t catch that') self.begin() # Controller for create sizing def create_sizing(self): address = self.ask_user('What is the address of the property?') try: bing_address = self.get_bing_address(address) print('bing address: ', ' '.join(bing_address.values())) except: self.text_to_speech('I am sorry, I didn\'t quite get that.') self.create_sizing() income = self.ask_user( 'How much did the property collect in rent last year?') print('income reported: ', income) expense = self.ask_user( 'What were the total expenses for the property last year?') print('expense: ', expense) units = self.ask_user('How many units are available at the property?') print('units: ', units) self.text_to_speech('Thank you, sizing property now.') print('Sizing...') t1 = time.clock() self.set_uw_values('Inputs!B5', ' '.join(bing_address.values())) self.set_uw_values('Inputs!B22', income) self.set_uw_values('Inputs!B51', expense) self.set_uw_values('Inputs!B14', units) t2 = time.clock() time_elapsed = t2 - t1 self.text_to_speech('Finished with sizing, pulling FHA loan terms') print('Pulling latest FHA terms') fha_loan = self.get_uw_values() if float(fha_loan['Loan Amount With Fee'][1:].replace(',', '')) > 1: quote = ''' We have a loan amount of {} at a {} rate for a {} term. This sizing was completed in {} seconds. '''.format(fha_loan['Loan Amount With Fee'], fha_loan['Rate With Fee'], fha_loan['Loan Type'], round(time_elapsed, 2)) print(quote) self.text_to_speech(quote + ' Beat that Ryan Patterson!') else: quote = 'I am sorry, but this property is not a fit for the FHA program. Let\'s try with CMBS instead...' print(quote) self.text_to_speech(quote) # Prompts user for input via mic/text. def ask_user(self, request): self.text_to_speech(request) print(request) if self.use_mic: r = sr.Recognizer() with sr.Microphone() as source: r.adjust_for_ambient_noise(source) self.play_prompt() print("Recording...") audio = r.listen(source) print("Got it, sending to VoiceRecog...") try: response = r.recognize_bing(audio, key=self.speech_key) except e: print("Speech Recognition failed: {0}".format(e)) response = input('Let\'s try typing the request instead -->\n') else: response = input('please type your response\n') return response # Converts text to audio. Uses Bing Speech API def text_to_speech(self, text, file_name='assets/output.mp3', play_audio=True): # retrieve jwt url = 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken' headers = {'Ocp-Apim-Subscription-Key': self.speech_key} bing_jwt = requests.post(url, headers=headers).text url = 'https://speech.platform.bing.com/synthesize' headers = { 'Content-Type': 'application/ssml+xml', 'X-Microsoft-OutputFormat': 'audio-16khz-128kbitrate-mono-mp3', 'User-Agent': 'gLabs Speech', 'Authorization': 'Bearer ' + bing_jwt } payload = """ <speak version='1.0' xml:lang='en-US'> <voice xml:lang='en-US' xml:gender='Female' name='Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)'> {} </voice> </speak> """.format(text) sound_file = requests.post(url, headers=headers, data=payload).content with open(file_name, 'wb') as f: f.write(sound_file) if play_audio: mixer.init(14250, -16, 2, 4096) mixer.music.load(file_name) mixer.music.play(loops=1, start=0.0) while mixer.music.get_busy() == True: continue # Sets value in sheet_range in gSheet def set_uw_values(self, sheet_range, value): return self.gSheet.set_value(sheet_range, value) # Pulls FHA quote from Quote Results in gSheet def get_uw_values(self): loans = self.gSheet.get_values('Quote Results!A2:AM') fha_loan = loans[-1] return fha_loan # Sends string to bing for address standardization. Uses Bing Maps API def get_bing_address(self, address): url = 'https://atlas.microsoft.com/search/address/json' params = { 'subscription-key': self.map_key, 'api-version': '1.0', 'query': address } res = requests.get(url, params=params).json() bing_address = { 'street_numb': res['results'][0]['address']['streetNumber'], 'street_name': res['results'][0]['address']['streetName'], 'city': res['results'][0]['address']['municipality'].split(',')[0], 'state': res['results'][0]['address']['countrySubdivision'], 'zip': res['results'][0]['address']['postalCode'], 'county': res['results'][0]['address']['countrySecondarySubdivision'] } return bing_address # Plays chime to prompt user to speak def play_prompt(self, file='assets/blip.mp3'): mixer.init(20500, -16, 1, 4096) mixer.music.load(file) mixer.music.play(loops=0, start=0.0) while mixer.music.get_busy() == True: continue # Gets a random thought from Ryan Swanson def get_thought(self): joke = requests.get( 'https://ron-swanson-quotes.herokuapp.com/v2/quotes').text self.text_to_speech(joke) print(joke)
print(u'Dialog Status: ' + res.get_dialog().get_status()) print(u'Entities:') for entity in res.get_entities(): print(u'"%s":' % entity.get_name()) print(u'Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) def on_failure(err): ''' A callback function that processes the error object if the prediction fails. :param err: An Exception object. :return: None ''' print err try: APPID = raw_input(u'Please enter your app Id:\n') APPKEY = raw_input(u'Please input your subscription key:\n') REGION = raw_input(u'Please input your region:\n') TEXT = raw_input(u'Please input the text to predict:\n') CLIENT = LUISClient(APPID, APPKEY, REGION, True, True) CLIENT.predict(TEXT, { u'on_success': on_success, u'on_failure': on_failure }) print u'-------\nMain thread finishing!!\n-------' except Exception, exc: print exc
print('LUIS Response: ') print('Query: ' + res.get_query()) print('Top Scoring Intent: ' + res.get_top_intent().get_name()) if res.get_dialog() is not None: if res.get_dialog().get_prompt() is None: print('Dialog Prompt: None') else: print('Dialog Prompt: ' + res.get_dialog().get_prompt()) if res.get_dialog().get_parameter_name() is None: print('Dialog Parameter: None') else: print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name()) print('Dialog Status: ' + res.get_dialog().get_status()) print('Entities:') for entity in res.get_entities(): print('"%s":' % entity.get_name()) print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) try: APPID = input('Please enter your app Id:\n') APPKEY = input('Please input your subscription key:\n') TEXT = input('Please input the text to predict:\n') CLIENT = LUISClient(APPID, APPKEY, True) res = CLIENT.predict(TEXT) while res.get_dialog() is not None and not res.get_dialog().is_finished(): TEXT = input('%s\n'%res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) process_res(res) except Exception as exc: print(exc)
from flask import Flask, request, session from luis_sdk import LUISClient import commands import confirmations from luis_command_names import LuisCommands from luis_sdk.luis_response import LUISResponse app = Flask(__name__) app.secret_key = '\xe2\xd2\xfeSIM\x93\xad\x1b\x8bGgn{V\xd0\x00\x8f\x13\x95dr\xeeT' application = app # TODO get these, then hide them APPID = "a754fc42-56f2-434a-a56b-8818c3df71f5" APPKEY = "3423d600dd744266867e8ec0752b881b" CLIENT = LUISClient(APPID, APPKEY, True) @app.route("/") def get_command(): command = request.args.get("command") if not command: print("No command parameter") return print(command) reply = CLIENT.predict(command) # error checking here intent = camelCase(reply.get_top_intent().get_name()) print("Intent: ", intent) if LuisCommands.is_confirmation(intent):
print('Top Scoring Intent: ' + res.get_top_intent().get_name()) if res.get_dialog() is not None: if res.get_dialog().get_prompt() is None: print('Dialog Prompt: None') else: print('Dialog Prompt: ' + res.get_dialog().get_prompt()) if res.get_dialog().get_parameter_name() is None: print('Dialog Parameter: None') else: print('Dialog Parameter Name: ' + res.get_dialog().get_parameter_name()) print('Dialog Status: ' + res.get_dialog().get_status()) print('Entities:') for entity in res.get_entities(): print('"%s":' % entity.get_name()) print('Type: %s, Score: %s' % (entity.get_type(), entity.get_score())) try: APPID = 'b81195cb-904c-48ef-adaf-7b12c664dc42' APPKEY = '5efceb9fffa84210808ec4f48e3434d1' TEXT = input('Please input the text to predict:\n') CLIENT = LUISClient(APPID, APPKEY, True) res = CLIENT.predict(TEXT) while res.get_dialog() is not None and not res.get_dialog().is_finished(): TEXT = input('%s\n' % res.get_dialog().get_prompt()) res = CLIENT.reply(TEXT, res) process_res(res) except Exception as exc: print(exc)
def main(): # 12.06.2017, modified to auto-read saved preprocessed info. # # 31.08.2017 Ver2: allow multiple query and evaluate by keeping info in the allGeneFileNames.txt # parser = argparse.ArgumentParser(description='query LUIS web agent.') parser.add_argument('--timestamp', dest='timestamp', action='store', metavar='TIMESTAMP', required=True, help='The timestamp of generated data.') parser.add_argument('--kfold', dest='kfold', action='store', metavar='KFOLD', required=True, help='order number of the kfold, e.g. 1,2,...') parser.add_argument( '--appid', dest='appid', action='store', metavar='APPID', required=True, help= 'The APPID from LUIS agent which you get when you create the agent.') parser.add_argument( '--appkey', dest='appkey', action='store', metavar='APPKEY', required=True, help= 'The APPKEY from LUIS agent which you get when you create the agent.') args = parser.parse_args() appID = "" appKey = "" timestamp = "" if args.timestamp is not None: timestamp = args.timestamp else: raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num --appid id --appkey key' kfold = "" if args.kfold is not None: kfold = args.kfold else: raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num --appid id --appkey key' if args.appid is not None: appID = args.appid else: raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num --appid id --appkey key' if args.appkey is not None: appKey = args.appkey else: raise RuntimeError, 'Usage: python progName --timestamp tm --kfold Num --appid id --appkey key' rootDirTop = "../.." textTestsetDir = rootDirTop + "/preprocessResults/autoGeneFromRealAnno/autoGene_" + timestamp + "/CrossValidation/KFold_" + kfold + "/testset/text" srcFiles = getFiles(textTestsetDir) crntIdx = 1 serviceName = "LUIS" trainset = "KFold" trainTimeStamp = timestamp baseDestDir = rootDirTop + "/testResults/" + serviceName if (not os.path.exists(baseDestDir)): os.mkdir(baseDestDir) baseDestDir = baseDestDir + "/" + serviceName + "_TestResults_" + trainset + "_" + trainTimeStamp + "-" + str( crntIdx) baseDestDir = baseDestDir + "/KFold_" + kfold if (not os.path.exists(baseDestDir)): os.mkdir(baseDestDir) CLIENT = LUISClient(appID, appKey, True) numUtt = 500 # maximum totalUttProcessed = 0 srcBaseDir = textTestsetDir start_time = time.time() for i in range(len(srcFiles)): results = {'results': []} domainFile = srcFiles[i] print "srcFiles:" + domainFile fileUri = os.path.join(srcBaseDir, domainFile) print "fileUri:" + fileUri utterances = readFile2List(fileUri) num = numUtt if (num > len(utterances)): num = len(utterances) print num for j in range(num): utt = utterances[j] utt = utt.lower() print "query:" + str(j) + " = " + utt res = CLIENT.predict(utt) res_j = process_res_json(res) results['results'].append(res_j) totalUttProcessed = totalUttProcessed + 1 print "totalUttProcessed:" + str(totalUttProcessed) # wait a bit, then query again for another utt. # LUIS limit: 5 calls Per seconds, 10K calls per month for Free Account #time.sleep(0.3) # Time in seconds. # time.sleep(0.6) # Time in seconds. For Pay-As-You-Go account, 50 per second time.sleep(0.2) # 0.2 should be enough, as query itself takes time domainName = domainFile[0:domainFile.rfind(".")] print "domainName:" + domainName saveJson2File(baseDestDir, domainName, results) elapsed_time = time.time() - start_time print "==== LUIS query finished ==== Elapsed Time: " + str(elapsed_time)