Exemplo n.º 1
0
    def run(self):
        hlp = Helper();br=True;results={};resultsort=[];correcting = False
        while br:  
            if correcting or self.matchgeo:
                pass
            else:
                command = raw_input("SMS in: ")
            if not self.matchgeo:
                t,option,word = self.process(unicode(command))
                words = t[0];disting = t[1][-1]
            if option and len(resultsort)==0:
                self.option = option;self.match = word
                if len(self.display) > 0 :
                    self.last_Display = self.display
                self.display = Chunks(self.option.print_Options())
                self.display.create_Chunks(heading="By ({0}) Did you mean: ".format(word),
                           footing="Please choose.")
                print self.display.goto_Chunk(); continue
            
            if len(self.option)>0 and len(words[0])==1:
                ch = self.option.select_Option(words[0])
                if ch!=None and len(resultsort)==0:
                    self.main.correctedHistory[self.match]=self.option[ch][2]
                    disting = t[1][-2]; 
                    k = disting['tokens'].index(self.match)
                    disting['tokens'][k] = self.option[ch][2]
                    try:
                        k = disting['words'].index(self.match)
                        disting['words'][k] = self.option[ch][2]
                        words = disting['words']
                    except:
                        disting['words'].append(self.option[ch][2])
                        words = disting['words']
                    if self.option[ch][2] == "find":
                        word = "find";self.option = Options()
                    else:
                        self.option = Options();correcting = True
                        command = " ".join(disting['tokens']); continue
                if ch!=None and type(resultsort)!=unicode:
                    text = "{0} - Ratings : {1}".format(resultsort[ch][0],resultsort[ch][1])
                    text += "\n" +" Telephone Number: " + results[resultsort[ch][0]][1]
                    text += "\n Address: "+results[resultsort[ch][0]][0]
                    self.display = Chunks(text)
                    self.display.create_Chunks()
                    print self.display.goto_Chunk()
                    self.option = Options();continue
                if ch!=None and type(resultsort)==unicode:
                    self.matchgeo = [results[ch]]; self.location_History[resultsort] = [results[ch]]
                    disting = t[1][-2]; words = disting['words'];self.option = Options()
                    continue

            correcting = False
                               
            if word == "find" or "find" in words:
                if word == "find":
                    self.find = self.last_Display
                else:
                    self.find = self.display
                expand = self.find.find_Chunks(" ".join([i for i in disting['tokens'] if i!="find"]))
                if expand!=False:
                    self.find.chunk_list = expand
                    print self.find.goto_Chunk()
                else:
                    print "No results found"
                continue
            
            for k in range(len(words)):
                dirfin = finder(r'directory|places',words[k])   
                if dirfin.found():
                    if "list" in words:
                        self.display = Chunks(",".join(hlp.dirtypes()).replace("_"," "))
                        self.display.create_Chunks(heading="List of types of places:")
                        print self.display.goto_Chunk(); break
                    direc=Directory([i for i in words if i!="directory" or i!="places"])
                    if len(self.matchgeo) > 0:
                        direc.locs=self.matchgeo; self.matchgeo = ""
                    results,resultsort = direc.run(disting,self.location_History)
                    if results == None:
                        break
                    elif type(resultsort) == unicode:
                        for i in results:
                            self.option.add_Option(content="{0}".format(i[0].encode('utf-8')))
                        self.display = Chunks(self.option.print_Options())
                        self.display.create_Chunks(heading="By {0} did you mean:".format(str(resultsort)),
                              footing="Please choose a location. ")
                        print self.display.goto_Chunk(); break                        
                            
                    for i in resultsort:
                        self.option.add_Option(content="{0} - Ratings : {1}".format(i[0].encode('utf-8'),str(i[1])))
                    self.display = Chunks(self.option.print_Options())
                    self.display.create_Chunks(heading="Nearby places:",
                              footing="Choose for more details. ")
                    print self.display.goto_Chunk(); break     
                        
                outfin = finder(r'outline',words[k])
                if outfin.found():
                    with open("textblock.txt","rb") as f:
                        textblock= f.read().decode("string_escape")
                    for i in range(len(textblock)):
                        if textblock[i:i+2] == "\u":   
                            textblock= textblock[:i]+unichr(int(textblock[i+2:i+6],base=16)).encode("utf-8")  +textblock[i+6:]
                    f.close()
                    self.table.add_TxtBlock(textblock)
                    if self.table.run([i for i in words if i !="outline"],disting['numbers']) != False:
                        self.display = self.table.run([i for i in words if i !="outline"],disting['numbers'])
                        print self.display.goto_Chunk(); break
                
                exifin = finder(r'exit',words[k])
                if exifin.found():
                    br=False;break   
                helpfin = finder(r'help',words[k])
                if helpfin.found():
                    print hlp;break
                
                if "next" in words[k]:
                    print self.display.next_Chunk(); break
                
                if "goto" in words[k]:
                    try:
                        n = disting['numbers'][0]
                        num = int(n)
                    except:
                        num = -1
                    print self.display.goto_Chunk(num); break
Exemplo n.º 2
0
    def run(self, disting, his):
        types = []
        keywords = []
        d = ["places"]
        hlp = Helper()
        self.history = his
        add = []
        test2 = similarity(" ".join(self.args), " ".join(hlp.dirtypes()), sort=True, average=False)

        for s in self.args:
            for k in test2[s][:4]:
                if k[1] >= 0.5:
                    types.append(k[0])
                    if s not in d:
                        d.append(s)
        test4 = similarity(
            " ".join([i for i in self.args if i not in d]), " ".join(hlp.addresstypes()), sort=False, average=True
        )
        for wo in test4:
            if test4[wo][-1] <= 0.4:
                continue
            elif wo not in add and wo in self.args:
                add.append(wo)
        p = []
        if "food" in types and len([i for i in self.args if i not in (d + add)]) >= 1:
            for j in [i for i in self.args if i not in (d + add)]:
                for k in d[1:]:
                    if filter_Concepts(k, j) > 4000 and j not in p:
                        p.append(j)
        d += p

        others = disting["numbers"] + disting["splits"]
        found, index = self.check_location(" ".join([i for i in self.args if i not in d] + others))
        if found:
            self.locs = self.history[index]
        types = "&types=" + "|".join(types)
        keywords = "&keyword=" + "+".join(keywords + d[1:])
        address = "address=" + "+".join([i for i in self.args if i not in d + add] + others + add)
        key = "&key=---------"
        print address
        if len(self.locs) == 0:
            base = "https://maps.googleapis.com/maps/api/geocode/json?"
            addressurl = base + address + key
            req = urllib2.Request(addressurl)
            html = urllib2.urlopen(req).read()
            addressdata = json.loads(html)
            for i in addressdata["results"]:
                self.locs.append(
                    [
                        i["formatted_address"],
                        str(i["geometry"]["location"]["lat"]) + "," + str(i["geometry"]["location"]["lng"]),
                    ]
                )
        if len(self.locs) > 1:
            return self.locs, " ".join([i for i in self.args if not i in d] + others)
        if len(self.locs) == 0:
            print "location not found, please try again"
            return None, None

        location = self.locs[0][1]
        location = "location=" + location

        base = "https://maps.googleapis.com/maps/api/place/radarsearch/json?"

        radius = "&radius=5000"

        final = base + location + radius + types + keywords + key
        print final
        req = urllib2.Request(final)
        html = urllib2.urlopen(req).read()
        data = json.loads(html)
        base2 = "https://maps.googleapis.com/maps/api/place/details/json?"
        results = {}
        resultsratings = {}
        for i in range(4):
            try:
                placeid = "placeid=" + data["results"][i]["place_id"]
            except IndexError:
                if i == 0:
                    print ("no results found")
                    break
                pass

            placeurl = base2 + placeid + key
            req = urllib2.Request(placeurl)
            html = urllib2.urlopen(req).read()

            placedata = json.loads(html)
            if "user_ratings_total" in placedata["result"]:
                resultsratings[placedata["result"]["name"]] = int(placedata["result"]["user_ratings_total"])
            else:
                resultsratings[placedata["result"]["name"]] = 0
            results[placedata["result"]["name"]] = []
            if "formatted_address" in placedata["result"]:
                results[placedata["result"]["name"]].append(placedata["result"]["formatted_address"])
            else:
                results[placedata["result"]["name"]].append("address not found")
            if "formatted_phone_number" in placedata["result"]:
                results[placedata["result"]["name"]].append(placedata["result"]["formatted_phone_number"])
            elif "international_phone_number" in placedata["result"]:
                results[placedata["result"]["name"]].append(placedata["result"]["international_phone_number"])
            else:
                results[placedata["result"]["name"]].append("telephone not found")

        resultsort = sorted(resultsratings.items(), key=operator.itemgetter(1), reverse=True)
        return results, resultsort