Example #1
0
def search():
    temp_search = []
    results_search = []
    data = ast.literal_eval(request.data)

    location = data[0].split("*")
    destination = data[1].split('*')
    activities = data[2].split('*')


    final_dest_num = int(data[3]) - len(destination)
    for loc in location:
            for dest in destination:
                print "destination"
                print results_search
                results_search.append(yelp.query_api(dest,loc))
    if (final_dest_num > 0):
        for loc in location:
            for act in activities:
                print "hi"
                print temp_search
                temp_search.append(yelp.query_api(act,loc))
    while final_dest_num >0:
        n = randint(0,len(temp_search)-1)
        results_search.append(temp_search[n])
        final_dest_num =- 1
    return json.dumps(results_search)
Example #2
0
def webhook():
    """
    This is the default POST webhook
    """
    log.info("request recieved from slack...")
    pretty_print_POST(request)
    if SLACK_VARIFY_TOKEN == request.form.get('token'):
        text = request.form.get('text')
        args = text.split()
        terms, location = None, None

        if args[0].lower() == 'yelp':
            log.info("calling dialogflow api")
            try:
                term, location, conf = dialogflow_api(args[1:])
            except Exception as e:
                pass
            log.info("calling yelp api..")
            if terms != None and location != None:
                slack_payload = query_api(args[0], term, location)
            else:
                slack_payload = query_api(args[0], args[1], ' '.join(args[2:]))
        else:
            slack_payload = {u'text': u'invalid action word'}

        return Response(json.dumps(slack_payload),
                        status=200,
                        mimetype='application/json')
    else:
        log.warning("message from unknown sources")
Example #3
0
def boba():
    response = yelp.query_api("Bubble Tea", "Mountain View, CA", 5)
    businesses = response.get('businesses')

    pprint.pprint(businesses)

    return dict(businesses=businesses)
Example #4
0
def handler(event, context):
    os.environ['TZ'] = 'America/New_York'
    time.tzset()
    cur_time = datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d-%H:%M')
    logger.debug("invokeChatBotScheduler %s" % (cur_time))
    
    #receive and delete messages
    import sqs
    dining_setting = sqs.receive_message()
    logger.debug("dining_setting: {}".format(dining_setting))
    if not dining_setting:
        return None
    dining_setting['Time'] = dining_setting['Time'].replace(":", '-')
    cuisine = dining_setting['Cuisine']
    location = dining_setting['Location']
    dining_date = dining_setting['Date']
    dining_hour = dining_setting['Time']
    phone = dining_setting['Phone']
    
    #yelp
    try:
        restaurants = yelp.query_api(cuisine, location, dining_date, dining_hour)
        logger.debug(restaurants)
        suggestions = build_suggestion(dining_setting, restaurants)
        #print("sending message to {}".format(phone))
        sns.send_message('1'+ phone, suggestions)
        
    except HTTPError as error:
        logger.debug('Encountered HTTP error {0} on {1}:\n {2}\nAbort program.'.format(
                error.code,
                error.url,
                error.read()))
    
    return None
def get_restaurants(lat=SARAH_HOUSE_LAT,lng=SARAH_HOUSE_LNG,pmin=1,pmax=5):
    sleep(1)
    ll = str(lat) + "," + str(lng)
    restaurant_list = yelp.query_api(ll)
    if restaurant_list==None:
        return None
    counter = 1
    for restaurant in restaurant_list:
        if counter == 10:
            sleep(1)
        lat = None
        lng = None
        name = None
        if 'coord' in restaurant:
            lat = restaurant['coord']['latitude']
            lng = restaurant['coord']['longitude']
        if 'name' in restaurant:
            name = restaurant['name']
        if lat and lng and name:
            #print "calling google places"
            google_dict = google_places.query_google(lat, lng, name)
            if (google_dict!=None):
                #print "google dict was not none"
                restaurant['google_place_id'] = google_dict['google_place_id']
                restaurant['google_rating'] = google_dict['google_rating']
                restaurant['google_review_list'] = google_dict['reviews']
            else:
                #print "google dict was none"
                restaurant['google_place_id'] = ""
                restaurant['google_rating'] = None
                restaurant['google_review_list'] = []
        counter += 1

    return restaurant_list
Example #6
0
def query(location, distance=5.0, category='restaurant', limit=6):
    try:
        result = yelp.query_api(category, location, distance, False, 1, limit)
    except:
        result = '1'
    if result == None:  #sometimes result will return None for an invalid category
        result = '1'
    return result
Example #7
0
def yelpperImpl(distance, prices, uberType):
	currentLat #taken from JS
	currentLon #taken from JS
	addressArray = getAddress(currentLat, currentLon) #[street address, city, state]
	mealTime = getMealTime()
	restaurantData  = query_api(mealTime, getRestaurant(addressArray[0])) #should be private
	restaurant = getRestaurant(restaurantData)		#name
	restaurantLat = getRestaurantLat(restaurantData)#lat
	restaurantLon = getRestaurantLon(restaurantData)#long
	uberImpl( )#tbc muhommad
Example #8
0
def get_city_info(parsed_weather_dictionary):
    ## WEATHER ##
    city_name = parsed_weather_dictionary['name']
    country = parsed_weather_dictionary['sys']['country']
    weather_description = parsed_weather_dictionary['weather'][0]['description']
    temperature = parsed_weather_dictionary['main']['temp']
    min_temp = parsed_weather_dictionary['main']['temp_min']
    max_temp = parsed_weather_dictionary['main']['temp_max']
    humidity = parsed_weather_dictionary['main']['humidity']
    wind_speed = parsed_weather_dictionary['wind']['speed']


    search_term = urllib.quote_plus(city_name)
    search_term = search_term.replace('%20', '+')


    # NEARBY RESTAURANTS AND BUSINESSES ##
    parsed_yelp_list = yelp.query_api(search_term)
    logging.info(parsed_yelp_list)
    business_list = []
    business = {}
    has_yelp = True
    if len(parsed_yelp_list) != 0:
        for i in range(len(parsed_yelp_list)):
            business['name'] = urllib.unquote(parsed_yelp_list[i]['id']).replace('-', ' ').title()
            business['rating'] = parsed_yelp_list[i]['rating']
            business['url'] = parsed_yelp_list[i]['url']
            address = ', '.join(parsed_yelp_list[i]['location']['display_address'])
            business['address'] = urllib.unquote(address)
            business_list.append(business.copy())
    else:
        has_yelp = False



    template_vars = {
        'city_name': city_name,
        'country': country,
        'description': weather_description,
        'temperature': int(temperature),
        'min_temp': int(min_temp),
        'max_temp': int(max_temp),
        'humidity': humidity,
        'wind_speed': wind_speed,
        'has_yelp': has_yelp,
        'business_list': business_list
        }

    return template_vars
Example #9
0
def get_city_info(parsed_weather_dictionary):
    ## WEATHER ##
    city_name = parsed_weather_dictionary["name"]
    country = parsed_weather_dictionary["sys"]["country"]
    weather_description = parsed_weather_dictionary["weather"][0]["description"]
    temperature = parsed_weather_dictionary["main"]["temp"]
    min_temp = parsed_weather_dictionary["main"]["temp_min"]
    max_temp = parsed_weather_dictionary["main"]["temp_max"]
    humidity = parsed_weather_dictionary["main"]["humidity"]
    wind_speed = parsed_weather_dictionary["wind"]["speed"]

    search_term = urllib.quote_plus(city_name)
    search_term = search_term.replace("%20", "+")

    # NEARBY RESTAURANTS AND BUSINESSES ##
    parsed_yelp_list = yelp.query_api(search_term)
    logging.info(parsed_yelp_list)
    business_list = []
    business = {}
    has_yelp = True
    if len(parsed_yelp_list) != 0:
        for i in range(len(parsed_yelp_list)):
            business["name"] = urllib.unquote(parsed_yelp_list[i]["id"]).replace("-", " ").title()
            business["rating"] = parsed_yelp_list[i]["rating"]
            business["url"] = parsed_yelp_list[i]["url"]
            address = ", ".join(parsed_yelp_list[i]["location"]["display_address"])
            business["address"] = urllib.unquote(address)
            business_list.append(business.copy())
    else:
        has_yelp = False

    template_vars = {
        "city_name": city_name,
        "country": country,
        "description": weather_description,
        "temperature": int(temperature),
        "min_temp": int(min_temp),
        "max_temp": int(max_temp),
        "humidity": humidity,
        "wind_speed": wind_speed,
        "has_yelp": has_yelp,
        "business_list": business_list,
    }

    return template_vars
Example #10
0
def search():
    form = SearchForm( )
    # if form is submitted, take zip code and option user gave
    # feed it to yelp api to get a json file back
    if form.validate_on_submit( ):
        zipcode = form.zipcode.data
        option = form.options.data
        businessesDict = yelp.query_api(option, str(zipcode))
        # from json file, take each elements id and append it to THE GLOBAL ARRAY
        # shuffle GLOBAL ARRAY and return helper function
        global business_id_array
        for i in range(0, len(businessesDict)):
            business_id = businessesDict[i]['id']
            business_id_array.append(business_id)
        random.shuffle(business_id_array)
        # print(business_id_array)
        return pickRestaurant()
    # else, return template
    return render_template("search.html", form=form)
Example #11
0
                    stuff3['results'][b]['opening_hours']['open_now'])
            except:
                allRes['g_open_now'].append("N/A")
            allRes['open_days'].append(days_list)
# print(allRes)

for ele in range(len(allRes['url'])):
    temp = getIndexes(allRes['url'][ele], allRes['open_days'][ele])
    allRes['pop_numbers'].append(temp[0].copy())
    allRes['pop_info'].append(temp[1].copy())
    print(str(ele + 1) + " Place(s) Scraped")
# getIndexes("https://maps.google.com/?cid=12777293506627589287") #for testing

try:
    for i in range(len(allRes['name'])):
        temp = query_api(allRes['name'][i], allRes['lat'][i], allRes['lon'][i])
        allRes['y_open_now'].append(temp['y_open_now'])
        allRes['y_rating'].append(temp['y_rating'])
        allRes['y_#reviews'].append(temp['y_#reviews'])
        fig, ax = plt.subplots()
        lege = []
        v = list(allRes['pop_numbers'][i].keys())[1:]
        for j in range(len(v)):
            lege.append(
                ax.bar(np.arange(18) + float(j / 10),
                       allRes['pop_numbers'][i].get(v[j]),
                       width=0.1,
                       color=co[j])[0])
        ax.set_xticks(
            np.arange(18) +
            (len(list(allRes['pop_numbers'][i].keys())[1:]) - 1) / 20)
Example #12
0
import yelp
import json_format_parser
import noteWriter
import LocationFinder
import LocationChooser

PriceGUI.main()
rating = PriceGUI.get_rating_level()['level']
food_type = TypeGUI.get_food_type()['type']
print rating, food_type
#succesfully get input rating and food type! YAY


location = LocationFinder.getCity()
print location
#get city succesfully

json_response = yelp.query_api('food',location)
r_dict = json_format_parser.get_res_dict(json_response)
name_list = json_format_parser.get_name_list(r_dict)
#print "------------------------------\n----------------------------------\n"
chosen_res = LocationChooser.choose(name_list)
print chosen_res

note_dict = json_format_parser.get_name_note_dict(r_dict)
print note_dict

chosen_note = note_dict[chosen_res]

noteWriter.writeToNote(chosen_note)
Example #13
0
def main(cities, origin_address, origin_coordinates, search_limit=1):
    SEARCH_LIMIT = 1
    if search_limit != 1:
        SEARCH_LIMIT = search_limit
    # coordinates of locations
    locations = []
    # User-friendly Addresses
    prettyLocations = []

    locations.append(origin_coordinates)
    prettyLocations.append(['Origin',origin_address])

    counter = 0
    # Get list of top restaurants in each city
    for city in cities:
       try:
           response = yelp.query_api('bars', city, SEARCH_LIMIT)
           for item in response:
               locations.append(str(item.get('location').get('coordinate').get('latitude')) + ',' +
                                str(item.get('location').get('coordinate').get('longitude')))
               # Save restaurant name and address
               prettyName = ""
               if len(item.get('location').get('display_address')) > 0:
                   prettyName += item.get('location').get('display_address')[0]
               if len(item.get('location').get('display_address')) > 1:
                   prettyName += ", "+item.get('location').get('display_address')[1]
               if len(item.get('location').get('display_address')) > 2:
                   prettyName += ", "+item.get('location').get('display_address')[2]
               prettyLocations.append([item.get('name'),prettyName])
       except urllib2.HTTPError as error:
           sys.exit('Encountered HTTP error {0}. Abort program.'.format(error.code))

    # ------
    # STEP 2 - Get distances between each restaurant
    # ------
    # Generate list of locations to visit in order
    url = 'https://maps.googleapis.com/maps/api/directions/json'

    # Create 2D array to keep track of pairs of locations - USE NUMPY LATER
    pairs = [[0]*len(locations) for x in xrange(len(locations))]
    distances_matrix = [[0]*len(locations) for x in xrange(len(locations))]

    # Numbers to indicate progress
    lookupNum = 0
    for i in range(len(locations) - 1):
        lookupNum += (i+1)
    counter = 0

    for i in range(0, len(locations)):
       for j in range(0, len(locations)):
           # Skip over duplicate pairs of locations to reduce requests
           if pairs[i][j] != 1 and i != j:
               # Set parameters
               params = dict(
                   origin = locations[i],
                   destination = locations[j],
                   key = get_server_key()
               )

               # Set to 1 to skip later
               pairs[i][j] = 1
               pairs[j][i] = 1

               # Send request to Google Maps
               time.sleep(0.1)
               resp = requests.get(url=url, params=params)
               data = json.loads(resp.text)
               if (data.get('status') == 'ZERO_RESULTS'):
                   return {"status": 500,
                           "message": "Directions not found from " + prettyLocations[i][1]
                                         + " to " + prettyLocations[j][1]}
               else:
                   # Storing distances in matrix for tsp_solver
                   distances_matrix[i][j] = data.get('routes')[0].get('legs')[0].get('distance').get('value')
                   distances_matrix[j][i] = data.get('routes')[0].get('legs')[0].get('distance').get('value')
                   counter += 1
                   sys.stdout.write("\rGetting Distances...%d%%" % int((float(counter)/lookupNum) * 100))
                   sys.stdout.flush()

    # ------
    # STEP 3 - Algorithm to find shortest path
    # ------
    # Returns route cycle

    cities_index = tsp_solver.solve_tsp(distances_matrix, 3)

    # Start and end cycle at start location
    route_distance = 0
    previous = 0
    for index, city in enumerate(cities_index):
        route_distance += distances_matrix[previous][city]
        previous = city
    route_distance += distances_matrix[cities_index[-1]][0]

    print('\nDone!')
    route_dict = {"origin_coordinates":{"lat": float(origin_coordinates.split(",")[0]),
                                        "lng": float(origin_coordinates.split(",")[1])},
                  "route_coordinates":[],
                  "route_names":[],
                  "route_addresses":[],
                  "status": 200}
    for item in cities_index:
        coordinates = locations[item].split(",")
        coordict = {"lat": float(coordinates[0]),
                    "lng": float(coordinates[1])}
        route_dict["route_coordinates"].append(coordict)
        route_dict["route_names"].append(prettyLocations[item][0])
        route_dict["route_addresses"].append(prettyLocations[item][1])

    return route_dict
Example #14
0
def get_city_info(parsed_weather_dictionary):
    ## WEATHER ##
    city_name = parsed_weather_dictionary['name']
    country = parsed_weather_dictionary['sys']['country']
    weather_description = parsed_weather_dictionary['weather'][0]['description']
    weather_icon = parsed_weather_dictionary['weather'][0]['icon']
    temperature = parsed_weather_dictionary['main']['temp']
    min_temp = parsed_weather_dictionary['main']['temp_min']
    max_temp = parsed_weather_dictionary['main']['temp_max']
    humidity = parsed_weather_dictionary['main']['humidity']
    wind_speed = parsed_weather_dictionary['wind']['speed']
    icon_url = 'http://openweathermap.org/img/w/%s.png' % weather_icon

    search_term = urllib.quote_plus(city_name)
    search_term = search_term.replace('%20', '+')

    ## NEWS ARTICLES ##
    news_search_url = ('http://api.nytimes.com/svc/search/v2/articlesearch' +
        '.json?fq=glocations.contains:%s&sort=newest&api-key=30721e81fcd118af473cdc4b5abf54cb:9:72577901'
        % search_term)
    news_data_source = urlfetch.fetch(news_search_url)
    news_json_content = news_data_source.content
    parsed_news_dictionary = json.loads(news_json_content)
    news_articles = []
    article = {}
    for i in range(0, 3):
        if i < len(parsed_news_dictionary['response']['docs']):
            article['web_url'] = parsed_news_dictionary['response']['docs'][i]['web_url']
            article['headline'] = parsed_news_dictionary['response']['docs'][i]['headline']['main']
            article['pub_date'] = parsed_news_dictionary['response']['docs'][i]['pub_date']
            article['snippet'] = parsed_news_dictionary['response']['docs'][i]['snippet']
            news_articles.append(article.copy())
        else:
            break
    has_news = True
    if len(news_articles) == 0:
        has_news = False

    ## FLICKR IMGS ##
    has_img = True
    if len(flickr.photos_search(tags=search_term)) != 0:
        while True:
            img_num = random.randint(1, 10)
            if img_num < len(flickr.photos_search(tags=search_term)):
                img_url = flickr.photos_search(tags=search_term)[img_num].getMedium()
                break
    else:
        img_url = 'null'
        has_img = False

    # NEARBY RESTAURANTS AND BUSINESSES ##
    parsed_yelp_list = yelp.query_api(search_term)
    logging.info(parsed_yelp_list)
    business_list = []
    business = {}
    has_yelp = True
    if len(parsed_yelp_list) != 0:
        for i in range(len(parsed_yelp_list)):
            business['name'] = urllib.unquote(parsed_yelp_list[i]['id']).replace('-', ' ').title()
            business['rating'] = parsed_yelp_list[i]['rating']
            business['url'] = parsed_yelp_list[i]['url']
            address = ', '.join(parsed_yelp_list[i]['location']['display_address'])
            business['address'] = urllib.unquote(address)
            business_list.append(business.copy())
    else:
        has_yelp = False



    template_vars = {
        'city_name': city_name, 'country': country, 'description': weather_description, 'icon_url': icon_url,
        'temperature': int(temperature), 'min_temp': int(min_temp),
        'max_temp': int(max_temp), 'humidity': humidity, 'wind_speed': wind_speed,
        'has_img': has_img, 'img_url': img_url, 'has_news': has_news, 'news_articles': news_articles,
        'has_yelp': has_yelp, 'business_list': business_list}

    return template_vars
Example #15
0
extra_cities = raw_input('Enter cities (Ex: Boston,Cambridge,LA,Philadelphia):  ').split(',')

if len(extra_cities) > 0 and extra_cities[0] != '':
    cities += extra_cities

print(cities)
if len(cities) == 1:
    SEARCH_LIMIT = int(raw_input("Enter the number of bars to visit: "))

print('-' * 50)
counter = 0
# Get list of top restaurants in each city
for city in cities:
   try:
       print('')
       response = yelp.query_api('bars', city, SEARCH_LIMIT)
       #pprint.pprint(response)
       for item in response:
           locations.append(str(item.get('location').get('coordinate').get('latitude')) + ',' +
                            str(item.get('location').get('coordinate').get('longitude')))
           # change to use coordinates to be more accurate
           # Print out restaurant name and address
           prettyName = ""
           print("\n" + city + ':')
           print(item.get('name'))
           if len(item.get('location').get('display_address')) > 0:
               prettyName += item.get('location').get('display_address')[0]
               print(item.get('location').get('display_address')[0])
           if len(item.get('location').get('display_address')) > 1:
               prettyName += ", "+item.get('location').get('display_address')[1]
               print(item.get('location').get('display_address')[1])