Ejemplo n.º 1
0
def interpret(rosrequest):
    sentence = rosrequest.sentence
    rospy.logdebug("Interpreting {0}".format(sentence))
    response = json.loads(wit.text_query(sentence, APIKEY))
    rospy.logdebug("Response: {0}".format(response))

    return parse_response(response, InterpretResponse)
Ejemplo n.º 2
0
def interpret(rosrequest):
    sentence = rosrequest.sentence
    rospy.logdebug("Interpreting {0}".format(sentence))
    response = json.loads(wit.text_query(sentence, APIKEY))
    rospy.logdebug("Response: {0}".format(response))

    return parse_response(response, InterpretResponse)
Ejemplo n.º 3
0
	def stt(self):
		txt = dict()
		result = ''
		ret = False
		
		if self.real:
			result = wit.voice_query_auto( self.wit_token )
			ans = self.getKey( json.loads(result) )
			
			if ans['intent'] == 'attention':
				self.logger.info('[*] Listening')	
				self.playSound('../sounds/misc/beep_hi.wav')
				result = wit.voice_query_auto( self.wit_token )
				self.logger.info('[*] Done listening')
				self.playSound('../sounds/misc/beep_lo.wav')
				ret = True
			else:
				self.logger.info('[-] Error, no audio detected')	
				ret = False
		else:
			print 'You:'
			result = self.stdin.readline()
			result = wit.text_query(result, self.wit_token )
			ret = True
		
		txt = self.getKey( json.loads(result) )
		if txt['intent'] == 'error':
			ret = False
			
		return txt, ret
Ejemplo n.º 4
0
def process(query):
    wit_response = wit.text_query(query, access_token)
    data = json.loads(wit_response)
    if is_good_candidate(data):
        search_prepare.prepare_json_for_search(data)
        search_result = search_processor.get_search_results(data)
        pretty_content_builder.print_contents(search_result)
Ejemplo n.º 5
0
    def stt(self):
        txt = dict()
        result = ''
        ret = False

        if self.real:
            result = wit.voice_query_auto(self.wit_token)
            ans = self.getKey(json.loads(result))

            if ans['intent'] == 'attention':
                self.logger.info('[*] Listening')
                self.playSound('../sounds/misc/beep_hi.wav')
                result = wit.voice_query_auto(self.wit_token)
                self.logger.info('[*] Done listening')
                self.playSound('../sounds/misc/beep_lo.wav')
                ret = True
            else:
                self.logger.info('[-] Error, no audio detected')
                ret = False
        else:
            print 'You:'
            result = self.stdin.readline()
            result = wit.text_query(result, self.wit_token)
            ret = True

        txt = self.getKey(json.loads(result))
        if txt['intent'] == 'error':
            ret = False

        return txt, ret
Ejemplo n.º 6
0
def search_text(_text):
    wit.init()
    result = wit.text_query(_text, 'VAVQDA6WFDRZBY7W62HER5QTDTEHOOR2')
    j = json.loads(result)
    #print j
    #print json.dumps(j, sort_keys=True, indent = 4 ,  separators = (',',': '))
    wit.close()
    return j['outcomes'][0]['entities']
Ejemplo n.º 7
0
def ask_wit(message):
    access_token = 'PWKWIJSS4XX3EJDMC6AHHI6N7VQ5JJXW'
    wit.init()
    # response = wit.voice_query_auto(access_token)

    response = wit.text_query(message, access_token)
    wit.close()
    return 'Response: {}'.format(response)
Ejemplo n.º 8
0
def search_text(_text):
    wit.init()
    result = wit.text_query(_text, 'VAVQDA6WFDRZBY7W62HER5QTDTEHOOR2')
    j = json.loads(result)
    #print j
    #print json.dumps(j, sort_keys=True, indent = 4 ,  separators = (',',': '))
    wit.close()
    return j['outcomes'][0]['entities']
Ejemplo n.º 9
0
def parse(text):
    response = json.loads(wit.text_query(text, access_token))
    if 'contact' in response['outcomes'][0]['entities']:
        for i in range(0, len(response['outcomes'][0]['entities']['contact'])):
            if str(response['outcomes'][0]['entities']['contact'][i]['value']).lower() == 'i':
                del response['outcomes'][0]['entities']['contact'][i]
                break

    print response['outcomes'][0]
    return response['outcomes'][0]
Ejemplo n.º 10
0
def getRequest(_text):
    wit.init()
    result = wit.text_query(_text.lower(), 'VAVQDA6WFDRZBY7W62HER5QTDTEHOOR2')
    j = json.loads(result)
    data = j['outcomes'][0]['entities']['how_to_text'][0]
    wit.close()
#check if exist the value
    if data.has_key('value'):
        return data['value']
    else:
        return None
Ejemplo n.º 11
0
def getRequest(_text):
    wit.init()
    result = wit.text_query(_text.lower(), 'VAVQDA6WFDRZBY7W62HER5QTDTEHOOR2')
    j = json.loads(result)
    data = j['outcomes'][0]['entities']['how_to_text'][0]
    wit.close()
    #check if exist the value
    if data.has_key('value'):
        return data['value']
    else:
        return None
Ejemplo n.º 12
0
def text_command(text):
	import wit
  	wit.init()

  	# Let's hack!
  	commandJSON = json.loads('{}'.format(wit.text_query(text, tok)))
  	wit.close()

	parsed = jsonparser.parseAlt(text,commandJSON)

	#if confidence is low
	if parsed[1] < .5:
		take_command()
	else:
		verify(parsed)
Ejemplo n.º 13
0
    def run(self, text, application=None):
        if not application and self._default_application:
            app = self._default_application
        elif application:
            app = application
        else:
            raise Exception('Unknown application: %s' % application)

        access_token = self._applications.get(app, None)
        if not access_token:
            raise Exception('Missing API key for application %s' % application)

        wit.init()
        response = wit.text_query(text, access_token)
        wit.close()

        return json.loads(response)
Ejemplo n.º 14
0
def handle_query(text):
    """Send a text-based query to Wit."""
    wit.init()

    message = DEFAULT_MESSAGE

    response = wit.text_query(text, private.WIT_API_TOKEN)
    result = json.loads(response)

    intent = result['outcomes'][0]['intent']

    if result['outcomes'] and 'entities' in result['outcomes'][0]:
        entity = result['outcomes'][0]['entities']

    if 'get_weather' in intent:
        message = get_weather(entity)

    return message
Ejemplo n.º 15
0
def findResponse(query):
	ACCES_TOKEN = '7BBOPUV5O46MVZC3IUCYMRXOYYTDZJRH' #acces to wit.ai/konrajak/Household database  
	return wit.text_query(query, ACCES_TOKEN)
Ejemplo n.º 16
0
def wit_function(access_token, string):
    wit.init()
    response = json.loads(wit.text_query(string, access_token))
    wit.close()

    return response['outcomes'][0]
Ejemplo n.º 17
0
        try:
            text = r.recognize_google(audio)
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition service; {0}".format(e))
        return text

    def handle_response(self, response):
        try:
            response = json.loads(response)
            if response['_text'] == 'stop':
                self.bot.stop_talking()

            # continuously call the listen function
            self.listen()
        except Exception as e:
            print e

if __name__ == '__main__':
    wit.init()

    # Let's hack!
    resp = wit.text_query('Turn on the lights', TOKEN)
    response = wit.voice_query_auto(TOKEN)

    print('Response: {}'.format(resp))
    print('Response: {}'.format(response))

    # Wrapping up
    wit.close()
Ejemplo n.º 18
0
def query_str(user_input):
    global listing_url
    list_of_empty_params = filter(lambda x:user_session[x]==None, user_session.keys())
    if len(list_of_empty_params) == 4:
        response = wit.text_query(user_input, access_token)
        print 'response --> ', response
        json_res = json.loads(response)
        intent = json_res['outcomes'][0]['intent']
        confidence = json_res['outcomes'][0]['confidence']
        entities = json_res['outcomes'][0]['entities']
        message = ""

        #print  "\n",intent, confidence, entities,"\n\n"
        # if "wikipedia_search_query" in entities:
        #     wikipedia_search_query =  entities['wikipedia_search_query'][0]['value']
        #     wiki_result = wiki_call(wikipedia_search_query)
        #     print wiki_result
        if intent=="seeker":
            global user_session
            if 'search_intent' in entities:
                search_intent = entities['search_intent'][0]['value']
                if search_intent=='rent':
                    user_session['search_intent'] = 'rent'
                elif search_intent in ['sale','purchase']:
                    user_session['search_intent'] = 'sale'
            else:
                user_session['search_intent'] = None

            if 'room_type' in entities:
                room_type = entities['room_type'][0]['value']
                user_session['bed_rooms']  = room_type_parse(room_type)
            else:
                user_session['room_type'] = None

            if 'area' in entities:
                user_session['area'] = entities['area'][0]['value']
            else:
                user_session['area'] = None

            list_of_empty_params = filter(lambda x:user_session[x]==None, user_session.keys())
            #print list_of_empty_params
            while None in user_session.values():
                message = reply_back_now(entity=list_of_empty_params[0])
                break
            
            return message
                # for each in list_of_empty_params:
                #     reply_back_now(entity=each)
                #     user_input = raw_input()
                #     main_parse(user_input, each)
                #     #print user_session
                #     list_of_empty_params = filter(lambda x:user_session[x]==None, user_session.keys())
        elif intent=="greetings":
            name = entities['name'][0]['value']
            user_name = name
            return "Hello " + name + "!! Please tell me your requirement?"
        elif intent=="about":
            return graph_query_str(user_input)
        elif intent=='UNKNOWN':
            return "Sorry, I couldn't understand that. I am still learning."
            # import sys
            # sys.exit(1)
    elif len(list_of_empty_params) == 0:
        response = wit.text_query(user_input, access_token)
        print 'response --> ', response
        json_res = json.loads(response)
        intent = json_res['outcomes'][0]['intent']
        confidence = json_res['outcomes'][0]['confidence']
        entities = json_res['outcomes'][0]['entities']
        message = ""
        if intent=="about":
            return graph_query_str(user_input)
    else:
        entity_to_set = list_of_empty_params[0]
        main_parse(user_input, entity_to_set)
        list_of_empty_params = filter(lambda x:user_session[x]==None, user_session.keys())
        if len(list_of_empty_params)>0:
            return reply_back_now(entity=list_of_empty_params[0])
        else:
            url_formation = "https://www.commonfloor.com/listing-search?city=Bangalore&prop_name[]="+user_session['area']\
            +"&property_location_filter[]="+ user_session['area_code'] +"&use_pp=0&set_pp=1&polygon=1&page=1&page_size=30&\
            search_intent="+user_session['search_intent']+"&min_inr="+user_session['min_inr']+"&max_inr="+\
            user_session['max_inr']+"&house_type[]=Apartment&bed_rooms[]="+str(user_session['bed_rooms'])

            listing_url = url_formation

            page = requests.get(url_formation)
            tree = html.fromstring(page.text)
            message = ""
            t = "".join(tree.xpath("//span[@class='result-count-number']/text()"))

            if int(t)==0:
                message += "Sorry..I didn't find any listing matching your requirements."
            else:
                message += "I could find "+ t +" listings for you."

            message += "Click on the link to have a look at the properties<br /><a href='" + url_formation + "'>Look for it >>>></a><br /> Do you want to look for better project's listing?"
            #message += "Bot finally collects these many values", user_session

            #print "intent = {}\n confidence={}\n entities={}\n wikipedia_search_query={}".format(intent, confidence, entities, wikipedia_search_query)
            #wit.close()
            return message
Ejemplo n.º 19
0
config = ConfigParser.ConfigParser()
config.readfp(open(r'/home/pi/.conf'))
sciezka = config.get('live', 'sciezka')
witapi = config.get('api', 'witai')

reload(sys)
sys.setdefaultencoding('UTF8')

c = '"'
s = ' '
e1 = "nic"
e2 = "nic"
source = sys.argv[1]

wit.init()
response = wit.text_query(sys.argv[2], witapi)
z = json.loads(format(response))
wit.close()
intent = z["outcomes"][0]["intent"]
dane = z["outcomes"][0]["_text"]
print intent + dane
if intent == "szukaj":
    r = requests.get('http://searx.me/?format=json&q=%21go%20' + dane)
    z = r.json()
    w1 = z["results"][0]["content"]
    link = z["results"][0]["url"]
    os.system("python " + sciezka + "sendtw.py " + source + s + c + w1 + c)
    os.system("python " + Sciezka + "sendtw.py " + source + s + c + link + c)
if intent == "Pogoda":
    os.system("python " + sciezka + "pogoda.py " + source +
              " gorzowwielkopolski")
# 21/Mar/2015
# Drapela Jakub; [email protected] 

# for running this script install wit 
# the website: https://wit.ai/docs/python/1.0.0/quickstart


# doesnt work in Python 3

import wit
wit.init()
ACCES_TOKEN = '7BBOPUV5O46MVZC3IUCYMRXOYYTDZJRH' #acces to wit.ai/konrajak/Household database 

while True:
	query=raw_input('\n Enter query: ');
	resp = wit.text_query(query, ACCES_TOKEN)
	#print('Response: {}'.format(resp))

wit.close()

#my output:

#[wit] initialized sox: 14.4.1
#[wit] init state machine
#[wit] initialized with device: default

# Enter query: [wit] ready. state=idle
#Should i take an umbrella outside 
#[wit] ready. state=idle
#[wit] received response: {"_text":"Should i take an umbrella outside","msg_id":"9b204aab-75b4-4804-97df-0448c3b99b41","outcomes":[{"_text":"Should i take an umbrella outside","confidence":1,"entities":{"location"[{"suggested":true,"type":"value","value":"outside"}],"weather_detail":[{"type":"value","value":"rain"}]},"intent":"weather"}]}
# 21/Mar/2015
# Drapela Jakub; [email protected]

# for running this script install wit
# the website: https://wit.ai/docs/python/1.0.0/quickstart

# doesnt work in Python 3

import wit
wit.init()
ACCES_TOKEN = '7BBOPUV5O46MVZC3IUCYMRXOYYTDZJRH'  #acces to wit.ai/konrajak/Household database

while True:
    query = raw_input('\n Enter query: ')
    resp = wit.text_query(query, ACCES_TOKEN)
    #print('Response: {}'.format(resp))

wit.close()

#my output:

#[wit] initialized sox: 14.4.1
#[wit] init state machine
#[wit] initialized with device: default

# Enter query: [wit] ready. state=idle
#Should i take an umbrella outside
#[wit] ready. state=idle
#[wit] received response: {"_text":"Should i take an umbrella outside","msg_id":"9b204aab-75b4-4804-97df-0448c3b99b41","outcomes":[{"_text":"Should i take an umbrella outside","confidence":1,"entities":{"location"[{"suggested":true,"type":"value","value":"outside"}],"weather_detail":[{"type":"value","value":"rain"}]},"intent":"weather"}]}
Ejemplo n.º 22
0
def findResponse(query):
	ACCES_TOKEN = '7BBOPUV5O46MVZC3IUCYMRXOYYTDZJRH' #acces to wit.ai/konrajak/Household database  
	return wit.text_query(query, ACCES_TOKEN)
Ejemplo n.º 23
0
	def text_query(self, text):
		res = json.loads(wit.text_query(text, WitClient._access_token))
		return res["outcomes"]
Ejemplo n.º 24
0
import wit

if __name__ == "__main__":
    wit.init()
    response = wit.text_query("turn on the lights in the kitchen",
                              "ACCESS_TOKEN")
    print("Response: {}".format(response))
    wit.close()
Ejemplo n.º 25
0
    y = 0;
    for x in sys.argv:
        if x == "--voice" or x == "-v":
            voice = True
        elif x == "--text" or x == '-t':
            usetext = True
            textpos = y+1
        y = y+1

    response = {}

    if(voice):
        response = wit.voice_query_auto(TOKEN)
    elif(usetext):
        response = wit.text_query(sys.argv[textpos], TOKEN)
    else:
        time.sleep(1)
        response = wit.text_query(raw_input(">> "), TOKEN)

    wit.close()
    time.sleep(0.1)

    inp = InputHandler(response)
    task = inp.getIntent()

    if(task == 'time_places'):
        handle = TimeHandler(inp.getValue())
        for x in handle.lookup():
            print(x)
    elif(task == 'weather_in'):
Ejemplo n.º 26
0
sciezka = config.get('live','sciezka')
witapi = config.get ('api','witai')

reload(sys)
sys.setdefaultencoding('UTF8')

c = '"'
s= ' '
e1 = "nic"
e2 = "nic"
source = sys.argv[1]



wit.init()
response = wit.text_query(sys.argv[2], witapi)
z = json.loads(format(response))
wit.close()
intent = z["outcomes"][0]["intent"]
dane = z["outcomes"][0]["_text"]
print intent+dane
if intent == "szukaj":
 r = requests.get('http://searx.me/?format=json&q=%21go%20' + dane)
 z = r.json()
 w1 = z["results"][0]["content"]
 link = z["results"][0]["url"]
 os.system("python " + sciezka + "sendtw.py " + source + s + c + w1 +  c)
 os.system("python " + Sciezka + "sendtw.py " + source + s + c + link +  c)
if intent == "Pogoda":
 os.system("python " + sciezka + "pogoda.py " + source +  " gorzowwielkopolski")
if intent == "sentencja":
Ejemplo n.º 27
0
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print(
                "Could not request results from Google Speech Recognition service; {0}"
                .format(e))
        return text

    def handle_response(self, response):
        try:
            response = json.loads(response)
            if response['_text'] == 'stop':
                self.bot.stop_talking()

            # continuously call the listen function
            self.listen()
        except Exception as e:
            print e


if __name__ == '__main__':
    wit.init()

    # Let's hack!
    resp = wit.text_query('Turn on the lights', TOKEN)
    response = wit.voice_query_auto(TOKEN)

    print('Response: {}'.format(resp))
    print('Response: {}'.format(response))

    # Wrapping up
    wit.close()