Exemplo n.º 1
0
def showRestaurantDetails(request, value):
	p = Pyzomato('ca5cbda00917434b4886bcf7fcc01b97')
	restDetails = p.getRestaurantDetails(value)
	id = value
	name=restDetails["name"]
	url=restDetails["url"]
	address=restDetails['location']['address']
	cuisines=restDetails['cuisines']
	average_cost_for_two=restDetails['average_cost_for_two']
	thumbnail=restDetails['thumb']
	rating=restDetails['user_rating']['aggregate_rating']
	popular_opinion=restDetails['user_rating']['rating_text']
	votes=restDetails['user_rating']['votes']
	photos=restDetails['photos_url']
	menu=restDetails['menu_url']
	featured_image=restDetails['featured_image']
	details = [dict() for x in range(12)]
	details = {'id':id, 'name':name, 'name':name, 'address':address, 'average_cost_for_two':average_cost_for_two,'featured_image':featured_image, 
	'thumbnail':thumbnail, 'rating':rating, 'popular_opinion':popular_opinion, 'photos':photos, 'menu':menu,'cuisines': cuisines,'votes':votes}
	request.session[0]=value
	request.session[1]=details
	all_enties = RestaurantReview.objects.all().filter(restaurantId=value)
	reviewList = []
	for p in all_enties:
		reviewElement = [dict() for x in range(9)]
		review = p.review
		rating = p.rating
		userName = p.user
		reviewElement={'review':review,'rating':rating, 'userName':userName}
		reviewList.append(reviewElement)
	return render(request, 'restaurantview.html', {'restdetails':details, 'reviewsAndRatings':reviewList})
Exemplo n.º 2
0
class ZomotoAPI:
    def __init__(self):

        # Api secret keys stored in enviornment variable

        self.api_key = os.environ.get('api_key')

    def get_Categories(self, citi_id):

        self.api_client_auth = Pyzomato(self.api_key)

        self.api_client_auth.search(name="Chennai")

        # city id for chennai is 7

        return self.api_client_auth.getCategories()

    def search_city_by_geo_code(self, latitude, longitude):

        return self.api_client_auth.getByGeocode(latitude, longitude)

    def locating_res_by_id(self, res_id):

        # id > 18387708
        # name > kakada ramprasad
        # "locality_verbose": "Kilpauk, Chennai"

        return self.api_client_auth.getRestaurantDetails(res_id)
Exemplo n.º 3
0
    def get_Categories(self, citi_id):

        self.api_client_auth = Pyzomato(self.api_key)

        self.api_client_auth.search(name="Chennai")

        # city id for chennai is 7

        return self.api_client_auth.getCategories()
Exemplo n.º 4
0
def get_zomato():
    """
        Function to grab the restaurants from zomato
    """

    # Bing key to standardized the addresses
    bing_key = "bNV4gwzuDF0BY7hRBr2D~SwYlwf_NvSxlbZ36oGsTdA~AthfnABkus6e2oSBb4W9Q9_7yHrFh1cHbreVFmsPad2apAgjYqLYZi8E2iSyiJk-"
    bing = geocoders.Bing(bing_key)

    # Empty list to add restaurants in
    yelp_params = []

    # Use Pyzomato to make requests to zomato api
    p = Pyzomato('a27dcc3db4574a4ae90e9852091e736c')

    # Location response
    response = (p.getByGeocode(lan="37.792085", lon="-122.399368"))

    # Json response from zomato
    restaurants = (response.get('nearby_restaurants'))

    # Iterate over response and grab necessary information
    for place in restaurants:
        restaurant = {}
        info = place.get('restaurant')
        name = (info.get('name'))
        address = (info.get('location').get('address'))[:-1]
        rating = float(info.get('user_rating').get('aggregate_rating'))
        reviews_count = int(info.get('user_rating').get('votes'))
        restaurant['total_reviews'] = reviews_count
        standardized_rating = round((rating / 5), 2)
        restaurant['standard_rating'] = standardized_rating
        rating_weight = round((reviews_count * 1.35), 2)
        restaurant['rating_weight'] = rating_weight
        price_range = info.get('price_range')
        restaurant['price_range'] = price_range

        # Try to update the location with bing's addesss
        try:
            for place in bing.geocode(address, exactly_one=False, timeout=5):
                location = str(place)
            if location is None:
                restaurant['name'] = name
                restaurant['location'] = address
                yelp_params.append(restaurant)
            else:
                restaurant['name'] = name
                restaurant['location'] = location
                yelp_params.append(restaurant)
        except Exception as e:
            print("ZERROR:", e)
    # Return the completed list
    return yelp_params
Exemplo n.º 5
0
def get_zomato():
    """
        Function to grab the restaurants from zomato
    """

    # Bing key to standardized the addresses
    bing_key = os.environ.get('BING_API_KEY')
    bing = geocoders.Bing(bing_key)

    # Empty list to add restaurants in
    yelp_params = []

    # Use Pyzomato to make requests to zomato api
    p = Pyzomato(ZOMATO_API_KEY)

    # Location response
    response = (p.getByGeocode(lan="37.792085", lon="-122.399368"))

    # Json response from zomato
    restaurants = (response.get('nearby_restaurants'))

    # Iterate over response and grab necessary information
    for place in restaurants:
        restaurant = {}
        info = place.get('restaurant')
        name = (info.get('name'))
        address = (info.get('location').get('address'))[:-1]
        rating = float(info.get('user_rating').get('aggregate_rating'))
        reviews_count = int(info.get('user_rating').get('votes'))
        restaurant['total_reviews'] = reviews_count
        standardized_rating = round((rating / 5), 2)
        restaurant['standard_rating'] = standardized_rating
        rating_weight = round((reviews_count * 1.35), 2)
        restaurant['rating_weight'] = rating_weight
        price_range = info.get('price_range')
        restaurant['price_range'] = price_range

        # Try to update the location with bing's addesss
        try:
            for place in bing.geocode(address, exactly_one=False, timeout=5):
                location = str(place)
            if location is None:
                restaurant['name'] = name
                restaurant['location'] = address
                yelp_params.append(restaurant)
            else:
                restaurant['name'] = name
                restaurant['location'] = location
                yelp_params.append(restaurant)
        except Exception as e:
            print("ZERROR:", e)
    # Return the completed list
    return yelp_params
Exemplo n.º 6
0
def getZomato(request):
    p = Pyzomato('1c9999881f4fe458a246ecbb5e5a4f36')
    if request.method == 'POST':
        zomato_form = ZomatoForm(request.POST)
        if zomato_form.is_valid():
            data2 = zomato_form.cleaned_data
            resp2 = p.search(q=data2['locationcity'],
                             lat='41.277072',
                             lon='-96.060682',
                             radius='25000',
                             count='3',
                             sort='rating')
    return HttpResponse(json.dumps(resp2))
Exemplo n.º 7
0
    def __init__(self): 

        self.conn = sqlite3.connect('project.db')
        c = self.conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS restaurant (restaurant_name, restaurant_location)''')
        c.execute('''CREATE TABLE IF NOT EXISTS photos (restaurant_name, img_link, user)''')
        self.conn.commit()
        #zomato key
      
        self.p = Pyzomato("4fec777b3693765001b7f8000cfd2da8")

        rest_to_add = 20

        c = self.conn.cursor()
        for row in c.execute('SELECT * FROM city_hourly'):
            latitude= row[0].split(",")[1]
            langtitude= row[0].split(",")[0]

            restaurants = self.p.search(lat=latitude, lon=langtitude)["restaurants"]
            for restaurant in restaurants:
                if rest_to_add > 0:
                    name = restaurant["restaurant"]["name"]
                    location = restaurant["restaurant"]["location"]["address"]
                    c.execute('INSERT INTO restaurant VALUES (?,?)', (name ,location,))
                    self.conn.commit()
                    rest_to_add -= 1
                else:
                    return

                if "photos" in restaurant["restaurant"]: 
                    for review in restaurant["restaurant"]["photos"]:
                        name = restaurant["restaurant"]["name"]
                        user = review["photo"]["user"]["name"]
                        img = review["photo"]["url"]
                        if rest_to_add > 0:
                            c.execute('INSERT INTO photos VALUES (?,?,?)', (name, img, user))
                            self.conn.commit()
                            rest_to_add -= 1
                        else:
                            return
Exemplo n.º 8
0
def callAPI():
    p = Pyzomato("0037bd86fc45f5201beebaa204099f72")

    er = p.getLocationDetails(484, "city")

    final = []
    for k in er["best_rated_restaurant"]:
        for k2 in k:
            if "American" in k[k2]["cuisines"] and "Latin American" not in k[
                    k2]["cuisines"]:
                d = {}
                d["name"] = k[k2]["name"]
                d["address"] = k[k2]["location"]["address"]
                d["cuisines"] = k[k2]["cuisines"]
                d["rating"] = k[k2]["user_rating"]["aggregate_rating"]
                d["votes"] = k[k2]["user_rating"]["votes"]
                d["photo_url"] = k[k2]["photos_url"]
                d["menu_url"] = k[k2]["menu_url"]
                final.append(d)

    final = sorted(final, key=lambda k: k["rating"], reverse=True)
    return final
Exemplo n.º 9
0
def search(request):
	p = Pyzomato('')
	list = []
	try:
		searchCategory = request.GET.get('searchCategory','')
		searchKeyWord = request.GET.get('searchKeyWord','')
		response=''
		if searchCategory == 'cuisines':
			cuisine_id = ''
			cusineResponse = p.getCuisines(city_id = '4')
			for num, cuisine in enumerate(cusineResponse['cuisines']):
				if cuisine['cuisine']['cuisine_name'] == searchKeyWord:
					cuisine_id = cuisine['cuisine']['cuisine_id']
			response = p.search(entity_type="city", entity_id='4',cuisines=cuisine_id)
		if searchCategory == 'restaurantType':
			restaurantTypeValue = ''
			restaurantTypeResponse = p.getEstablishments(city_id = '4')
			for num, establishment in enumerate(restaurantTypeResponse['establishments']):
				if establishment['establishment']['name'] == searchKeyWord:
					restaurantTypeValue = establishment['establishment']['id']
			response = p.search(entity_type="city", entity_id='4', establishment_type=restaurantTypeValue)
		if searchCategory == 'restaurantCategory':
			category_id = ''
			category_response = p.getCategories()
			for num, category in enumerate(category_response['categories']):
				if category['categories']['name'] == searchKeyWord:
					category_id = category['categories']['id']
			response = p.search(entity_type="city", entity_id='4', category=category_id)
	except Exception as e:
		print(e)
	try:
		for num, restaurant in enumerate(response['restaurants']):
			number= num+1,
			name=restaurant['restaurant']['name']
			name = name.format()
			url=restaurant['restaurant']['url']
			cuisines=restaurant['restaurant']['cuisines']
			rating=restaurant['restaurant']['user_rating']['aggregate_rating']
			icon=restaurant['restaurant']['thumb']
			price=restaurant['restaurant']['average_cost_for_two']
			res_id=restaurant['restaurant']['id']
			dictlist = [dict() for x in range(9)]
			dictlist={'number':number, 'name':name, 'url':url, 'cuisines':cuisines, 'rating':rating, 'icon':icon, 'price':price, 'res_id':res_id }
			list.append(dictlist)
	except Exception as e:
		print(e)
	return render(request, 'home.html', {'context': list})
Exemplo n.º 10
0
    def searchZomato(self):
        self.cityName = str(self.lineEdit.text())
        self.restName = str(self.lineEdit_2.text())
        self.mykey = '7dcf7b79d4c7bdfd5ffe013ae7361388'
        self.p = Pyzomato(self.mykey)
        print(dir(self.p))
        print('*' * 100)
        print('\n\n')
        print('INSIDE FUNCTION:-', inspect.stack()[0][3])
        print('CITY NAME AND RESTAURANT NAME\'S ARE "-', self.cityName,
              self.restName)
        print('THE ZOMATO API OBJECT:=', self.p)
        print('SEARCHING THE DATABASE FOR YOUR QUERY')
        print('\n\n')
        try:
            self.cityId = self.p.getCityDetails(q=self.cityName)
            l = self.cityId['location_suggestions']
            for d in l:
                for k, v in d.items():
                    if k == 'id':
                        self.cityId = d[k]
                        print('CITY ID:-', self.cityId)

            self.details = self.p.search(q=self.restName,
                                         city=self.cityName,
                                         count=10,
                                         entity_id=self.cityId,
                                         entity_type='city')
            print('\n\n THE DETAILS OF THE RESTAURANT ARE AS FOLLOWS:-',
                  self.details)
            self.output = zomato_script.searchRestaurant(
                self.details, self.restName.upper())
            self.processOutput(self.output)
        except Exception as exc:
            print('INVALID DETAILS ENTERED:-', exc)
            print('TRACEBACK :-', traceback.format_exc())
Exemplo n.º 11
0
def restaurants():
    address = request.args.get('address')
    if not address:
        return "Bad Request!<br>Address parameter is empty or invalid."
    client = GeocodioClient('e69dd65d59f64d56bb99e5fea55f5b1d999a696')
    zomato = Pyzomato('188eda180987998d1dd37a7b93fee08a')

    location = client.geocode(address) # .coords to get lat and lng right away
    lat = location['results'][0]['location']['lat']     # parsing json
    lng = location['results'][0]['location']['lng']

    zomatoData = zomato.getByGeocode(lat, lng)

    output = {
        'restaurants': []
    }
    for r in zomatoData['nearby_restaurants']:
        output['restaurants'].append(dict({'name': r['restaurant']['name'],
                                           'address': r['restaurant']['location']['address'],
                                           'cuisines:': r['restaurant']['cuisines'],
                                           'rating': r['restaurant']['user_rating']['aggregate_rating']
                                           }))
    print(output)
    return jsonify(output)
Exemplo n.º 12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pyzomato import Pyzomato
import os

p = Pyzomato(os.environ['ZOMATO_API_KEY'])
cuisine_list = []
latitude = 40
longitude = -73


def get_cuisines(location=None):
    global latitude, longitude
    latitude = location['latitude']
    longitude = location['longitude']
    geocode = p.getByGeocode(latitude, longitude)
    city_id = geocode['location']['city_id']
    nearby_cuisines = geocode['popularity']['top_cuisines']
    cuisines_dict = p.getCuisines(city_id)
    global cuisine_list
    for i in range(len(cuisines_dict['cuisines'])):
        cuisine_list.append(cuisines_dict['cuisines'][i]['cuisine'])
    return nearby_cuisines


def get_values(result, lat, long, title, address):
    l = result['results_shown']
    for i in range(0, l):
        if result['restaurants'][i]['restaurant']['name'] not in title and len(
                lat) < 5:
Exemplo n.º 13
0
                elif isinstance(obj, dict):
                    arr.append(obj.get(key, None))
                else:
                    arr.append(None)
            return arr

        if isinstance(obj, dict):
            return extract(obj, path, 0, [])
        elif isinstance(obj, list):
            outer_arr = []
            for item in obj:
                outer_arr.append(extract(item, path, 0, []))
            return outer_arr


p = Pyzomato("4d23393190ba2ae6c5b5298145c70f07")


class GetRst:
    def getRestaurants(lat, lon, *args):
        response = p.getByGeocode(lat, lon)
        rid = Exjson.extract_element_from_json(
            response, ["nearby_restaurants", "restaurant", "id"])
        data = Exjson.extract_element_from_json(
            response, ["nearby_restaurants", "restaurant", "name"])
        cost = Exjson.extract_element_from_json(
            response,
            ["nearby_restaurants", "restaurant", "average_cost_for_two"])
        img = Exjson.extract_element_from_json(
            response, ["nearby_restaurants", "restaurant", "featured_image"])
        loc = Exjson.extract_element_from_json(response, [
Exemplo n.º 14
0
@author: sameerkumar
"""

from pyzomato import Pyzomato
import os

fileExists = os.path.isfile('zomatoData.txt')
headerList = [
    'restaurant_id', 'rating', 'review_id', 'review_text', 'rating_color',
    'review_time_friendly', 'rating_text', 'time_stamp', 'likes',
    'comment_count', 'user_name', 'user_zomatohandle', 'user_foodie_level',
    'user_level_num', 'foodie_color', 'profile_url', 'profile_image'
]
restaurantIdList = []
p = Pyzomato("a6bbe2d54ec7dd7741ef5991f9a9cafa")
results = p.search(lat="33.222063", lon="-96.972784")
restaurants = results['restaurants']
for restaurant in restaurants:
    restaurantId = 0
    restaurantId = restaurant['restaurant']['R']['res_id']
    restaurantIdList.append(restaurantId)

for restaurantId in restaurantIdList:
    reviews = p.getRestaurantReviews(restaurantId)
    userReviews = reviews['user_reviews']
    for review in userReviews:
        reviewContentList = []
        userReview = review['review']
        rating = userReview['rating']
        reviewId = userReview['id']
Exemplo n.º 15
0
#!/usr/bin/env python
#This file keeps on updating the current stored data.
from pyzomato import Pyzomato
import nltk
import re
import urllib2, json, sys
from textblob import TextBlob
import pymongo
import unicodedata
import sys
from pymongo import MongoClient

client = MongoClient()
client = MongoClient('127.0.0.1', 27017)
db = client.restaurants_database
p = Pyzomato('fbde89c2e30ec611b531a3a17c7eeca3')
# m stores name of all tables
m=[]
for i in tab:
	m.append(i.encode("UTF-8"))

for postsss in m:
	val=postsss[5:]  #table10 gives 10 which is used as city id
	db[postsss]drop() #drops the current table
	res_url="https://api.zomato.com/v1/directory.json?city_id="+str(val)+"&count=94&apikey=16b682609de39e187aceba2cafcaaa5d"
	#Update the database for the dropped table by using its city id.

	requestss = urllib2.Request(res_url)
	rest = urllib2.urlopen(requestss)
	json_rest = json.load(rest)
	restaurants=json_rest['results']
Exemplo n.º 16
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pyzomato import Pyzomato
import os

p = Pyzomato('d67aae36be44be5d4483e0546ff03360')
cuisine_list = []
latitude = 40
longitude = -73


def get_cuisines(location=None):
    global latitude, longitude
    latitude = location['latitude']
    longitude = location['longitude']
    geocode = p.getByGeocode(latitude, longitude)
    city_id = geocode['location']['city_id']
    nearby_cuisines = geocode['popularity']['top_cuisines']
    cuisines_dict = p.getCuisines(city_id)
    global cuisine_list
    for i in range(len(cuisines_dict['cuisines'])):
        cuisine_list.append(cuisines_dict['cuisines'][i]['cuisine'])
    return nearby_cuisines


def get_values(result, lat, long, title, address):
    l = result['results_shown']
    for i in range(0, l):
        if result['restaurants'][i]['restaurant']['name'] not in title and len(
                lat) < 5:
Exemplo n.º 17
0
@app.route('/')
def index():
    return render_template('index.html')


@app.route('/results', methods=['GET', 'POST']) # decorator, defines your website's /
def result():
    
    results = callAPI()
    return render_template('results.html', results = results)

if __name__ == "__main__":
    app.run(debug = True) #Set debug = False in a production environment
=======
p = Pyzomato("0037bd86fc45f5201beebaa204099f72")

er = p.getLocationDetails(484, "city")

final = []
for k in er["best_rated_restaurant"]:
    for k2 in k:
        if "American" in k[k2]["cuisines"] and "Latin American" not in k[k2]["cuisines"]:
            d = {}
            d["name"] = k[k2]["name"]
            d["address"] = k[k2]["location"]["address"]
            d["cuisines"] = k[k2]["cuisines"]
            d["rating"] = k[k2]["user_rating"]["aggregate_rating"]
            d["votes"] = k[k2]["user_rating"]["votes"]
            d["photo_url"] = k[k2]["photos_url"]
            d["menu_url"] = k[k2]["menu_url"]
Exemplo n.º 18
0
from pyzomato import Pyzomato
import json
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv('PROJECT_API_KEY')

p = Pyzomato(API_KEY)

# Create an empty list, that will be used to append each dictionary returned.
restaurantList = []

# Create a loop that iterates five times starting from 0th record and increases by increments of 20
for a in range(0, 100, 20):
    restaurants = p.search(lat=51.509865,
                           lon=-0.118092,
                           count=20,
                           sort='rating',
                           order='desc',
                           category=10,
                           start=a)
    print(a)
    restaurantList.append(restaurants)

# Write list of dictionaries to a json file
with open('Top60London.json', 'w') as fp:
    json.dump(restaurantList, fp)
Exemplo n.º 19
0
# -*- coding: cp1252 -*- #to avoid encoding problem
from flask import Flask, request, render_template, url_for, redirect, session  #importing flask to the environment and also required functions
from pyzomato import Pyzomato  #importing zomato api
from nutritionix import Nutritionix  #importing nutritionx api
import sys, os  #importing miscellenous lib

app = Flask(__name__)  #initialising flask framework as app
p = Pyzomato('b114ed71e5b2ec1fb505e869c891e157'
             )  #initialising zomato api and authenticating through api key
nix = Nutritionix(app_id="d6c8b53e",
                  api_key="3f98f4237dd0e647591d10d4c6c56450"
                  )  #initialising nutritionx api and authentication


@app.route('/', methods=['POST', 'GET'])  #defining url and method of action
def hello_world():
    if request.method == 'GET':  #fetching python file to user
        return render_template('admin.html')  #using admin html as template
    elif request.method == 'POST':
        username = request.form['username']  #getting input from users to login
        password = request.form['password']
        if username == "admin" and password == "admin":  #verifing username and password
            return redirect(
                url_for('home')
            )  #if its correct its redirect to restaurant finding page
        else:
            kwargs = {  #keyword arguments
                'error':
                "Invalid Username or Password",  #sending error message to user if its wrong 
            }
            return render_template(
Exemplo n.º 20
0
#!/usr/bin/python

from flask import Flask, request, jsonify, redirect, url_for
from flask_restful import Resource, Api
from geocodio import GeocodioClient
from pyzomato import Pyzomato
import requests.exceptions


app = Flask(__name__)
api = Api(app)
app.config['JSON_SORT_KEYS'] = False

#API KEYS
client = GeocodioClient('f46ef5bbdcfbbebd4dcc75c5b6cce9767ee744b')
zomato = Pyzomato('ac9ae8751e5e53622383740fd5a20d9c')


class Home(Resource):
    def get(self):
        r = requests.get('https://api.geocod.io/v1.3/geocode')
        r2 = requests.get('https://developers.zomato.com/api/v2.1/geocode')

        if(r.status_code == 500): 
            return {'message': "Geocodio is Down. Error code: 500"}
        elif(r2.status_code == 500):
            return {'message': "Zomato is Down. Error code: 500"}
        else: 
            {"about: this is home"}

    def post(self):
Exemplo n.º 21
0
This python application performs GET respose by accepting an address string
as parameter and uses it to perform a GET call to Geocode.io API in order
to get the coordinates of given address. After getting such coordinates,
another API call is perform to Zomato.io API in order to get the 20th nearest
restaurants around. The data obtained from Zomato is then cleaned up and
return back to the user in the original GET request to this application.
"""
from flask import Flask, request, Response, json
from geocodio import GeocodioClient
from pyzomato import Pyzomato
# from pyspark import SparkContext

# GIOCODE API KEY:
geocode_client = GeocodioClient('API KEY')
# ZOMATO API KEY:
zomato_client = Pyzomato('API KEY')
app = Flask(__name__)


@app.route("/restaurant")
def start():
    data = {'route': 'restaurant', 'echo': 'GET'}
    js = json.dumps(data)
    resp = Response(js, status=200, mimetype='application/json')
    resp.headers['Link'] = 'http://luisrei.com'
    return resp


@app.route("/restaurant/<address>", methods=['GET'])
def get_address(address):
    #if address == None:
from pyzomato import Pyzomato
import os, sys

ZOMATO_API = '<YOUR-API-CODE>'

#Initialise Zomato API
res_api = Pyzomato(ZOMATO_API)

def search(restaurant_name):	
	res_results = res_api.search(q=restaurant_name)
	res_results = res_results['restaurants']
	if(not os.path.isfile('res_details.csv')):
		os.system('touch res_details.csv')
		with open('res_details.csv','w') as fin:
			fin.write('Restaurant Name' + ","+ 'Cuisines' + ","+'Location' + ","+ 'Price for 2'+ ","+  'Rating' + "\n") 

	with open('res_details.csv','a') as fin:
		for i in xrange(min(2,len(res_results))):
			res_details = res_results[i]['restaurant']
			if(res_details['location']['city']!='Bangalore'):
				break
			else:
				print res_details['name'],'\n',res_details['location']['address'], '\nPrice for 2: ', res_details['average_cost_for_two'], ' Rs\nRating: ', res_details['user_rating']['aggregate_rating'] 
				print "\n"
				try:
					fin.write(res_details['name'] + ","+ " ".join(res_details['cuisines'].split(',')) + "," + " ".join(res_details['location']['locality'].split(',')) + "," + str(res_details['average_cost_for_two']) + ","+ str(res_details['user_rating']['aggregate_rating'] + "\n")) 
				except:
					continue
'''
while(True):
	restaurant_name = raw_input('Enter Restaurant Name (q to exit): ')
Exemplo n.º 23
0
from gtts import gTTS
import speech_recognition as sr
import os
import re
import webbrowser
import smtplib
import requests, json
import urllib
import boto3
import os
import cv2
from pyzomato import Pyzomato
p = Pyzomato('263457c3373e779946164cef05a88eb0')
import paho.mqtt.publish as publish

import pyttsx3


def talkToMe(audio):

    print(audio)
    for line in audio.splitlines():
        engine = pyttsx3.init()
        engine.say("say" + audio)
        engine.runAndWait()
        #os.system("say " + audio)


def currentad():

    send_url = "http://api.ipstack.com/check?access_key=9a86bc5e18df530bd1ded7ff6620187d"
Exemplo n.º 24
0
#!/usr/bin/python3
from geopy.geocoders import GoogleV3
from pymongo import MongoClient
import requests, json
from pyzomato import Pyzomato

if __name__ == "__main__":
    zomato_key = "a27dcc3db4574a4ae90e9852091e736c"

    zomato = Pyzomato(zomato_key)
    geolocator = GoogleV3(api_key="AIzaSyDQ-1MWdP4V8LAqo4CJ6t1gHsa0FZos7aI")
    zip_codes = [
        '94130', '94133', '94111', '94123', '94129', '94121', '94118', '94115',
        '94109', '94108', '94104', '94105', '94102', '94103', '94158', '94107',
        '94110', '94114', '94117', '94124', '94134', '94112', '94127', '94131',
        '94116', '94132', '94122'
    ]
    client = MongoClient('mongodb://localhost:27017/')
    db = client.guiscore

    for zip_code in zip_codes:
        address = geolocator.geocode(zip_code, timeout=7)
        response = (zomato.getByGeocode(lan="{}".format(address.latitude),
                                        lon="{}".format(address.longitude)))
        area_stats = response.get('popularity')
        if area_stats is None:
            continue
        print("------Adding Zomato area stats----------", area_stats)
        area_stats.update({'zip_code': '{}'.format(zip_code)})
        db.tips.update({'zip_code': zip_code}, area_stats, upsert=True)
Exemplo n.º 25
0
def searchRestaurant(request):
    p = Pyzomato('c5515b949415a90fe3c9dfebf2d1b246')
    if request.GET.get('city', False) or request.GET.get('search', False):
        city = request.GET["city"]
        search_key = request.GET["search"]

        city = p.getLocations("query=" + str(city))
        res_id = []
        data = {}

        search_results = p.search(
            entity_id=city['location_suggestions'][0]['entity_id'],
            entity_type=city['location_suggestions'][0]['entity_type'],
            q=search_key)
        # print(search_results['restaurants'][0]['restaurant']['R']['res_id'],search_results['restaurants'][1]['restaurant']['R']['res_id'])
        # search_results = p.search(entity_id=city['location_suggestions'][id]['entity_id'], entity_type=city['location_suggestions'][id]['entity_type'] ,q=search_key)
        try:
            for id in range(0, 10):
                resta_id = search_results['restaurants'][id]['restaurant'][
                    'R']['res_id']
                data[resta_id] = {}
                data[resta_id]['name'] = search_results['restaurants'][id][
                    'restaurant']['name']
                data[resta_id]['cusine'] = search_results['restaurants'][id][
                    'restaurant']['cuisines']
                data[resta_id]['address'] = search_results['restaurants'][id][
                    'restaurant']['location']['address']
                data[resta_id]['average_cost_for_two'] = search_results[
                    'restaurants'][id]['restaurant']['average_cost_for_two']
                data[resta_id]['rating'] = search_results['restaurants'][id][
                    'restaurant']['user_rating']['aggregate_rating']
                res_id.append(resta_id)
        except:
            status = 'failed'
        else:
            status = 'success'
        if status == 'success':
            return render(
                request, 'Restaurant_Search/SearchResults.html', {
                    'res_id': res_id,
                    'data': data,
                    'city': request.GET["city"],
                    'search_key': search_key
                })
        if status == 'failed':
            return render(
                request, 'Restaurant_Search/SearchResults.html', {
                    'res_id': res_id,
                    'data': data,
                    'city': request.GET["city"],
                    'search_key': search_key,
                    'no_results': 'no_results'
                })

    elif request.GET.get('res_id', False):
        res_id = request.GET["res_id"]
        data = p.getRestaurantDetails(restaurant_id=res_id)

        print(data['name'])
        data
        return JsonResponse(data)
#Oleksandr Bihary
#Using Zomato API we obtain resturants names in the Las Vegas area and their Reviews
#API KEY: aa2e170fced5e4de42b96789a76fbd7f

import pprint
from pyzomato import Pyzomato
pp = pprint.PrettyPrinter(indent=2)

p = Pyzomato("aa2e170fced5e4de42b96789a76fbd7f")
p.search(q="las vegas")

categories = p.getCategories()
pp.pprint( categories )

dets = p.getCollectionsViaCityId(282)
pp.pprint( dets )

cus = p.getCuisines(282)
pp.pprint( cus )

estab = p.getEstablishments(282)
pp.pprint( estab )

#need resturant ID
menu = p.getDailyMenu(292)
pp.pprint( menu )

#need resturant ID
info = p.getRestaurantDetails(292)
pp.pprint( info )
Exemplo n.º 27
0
#!/usr/local/bin/python3

import os
from flask import Flask
from flask import request, jsonify
from flask_cors import cross_origin
from pyzomato import Pyzomato

app = Flask(__name__)

p = Pyzomato(os.environ.get('RESTAURANT_API_KEY'))


@app.route('/nearby_restaurants')
@cross_origin()
def nearby_restaurants():
    lat = request.args.get('lat')
    lon = request.args.get('lon')
    result = p.getByGeocode(lat, lon)['nearby_restaurants']
    list_of_restaurants = list(
        map(
            lambda x:
            (x['restaurant']['name'], x['restaurant']['price_range']), result))
    return jsonify(list_of_restaurants)


if __name__ == '__main__':
    app.run(host='0.0.0.0')
Exemplo n.º 28
0
from pyzomato import Pyzomato
import traceback
import re

mykey='7dcf7b79d4c7bdfd5ffe013ae7361388'
p=Pyzomato(mykey)

print ('ZOMATO API OBJECT CREATED:-',p)


def searchRestaurant(details,r):
    f=open('ResDetails','w')
    #print ('RESTAURANT ENTERED:-',r)
    if 'restaurants' in details.keys():
        lstRes=details['restaurants']
        for i in lstRes:
            if 'restaurant' in i.keys():
                d=i['restaurant']
                '''
                f.write('*' * 60)
                f.write('d is:-'+ '\n')
                f.write(str(d))
                f.write('\n\n')
                f.write('d.keys :-'+ str(d.keys()))
                f.write('\n\n')
                '''
                flag=False
                for k,v in d.items():
                    if 'name' in d and 'average_cost_for_two' in d \
                        and 'user_rating' in d and 'location' in d:
Exemplo n.º 29
0
import site
site.addsitedir('/Users/Aditi/miniconda3/lib/python2.7/site-packages')
from pyzomato import Pyzomato
import nltk
import re
import urllib2, json, sys
from textblob import TextBlob
import pymongo
import unicodedata
import sys
from pymongo import MongoClient
#database
client = MongoClient()
client = MongoClient('127.0.0.1', 27017)
db = client.restaurants_database
p = Pyzomato('a54e351eb6f630cb9ed6f8efe31e0c1e')

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
city_name = form.getvalue('city_name')
country_name = form.getvalue('country_name')

city = p.getCityDetails(q=city_name)
location = city['location_suggestions']
tab = db.collection_names()
m = []
for i in tab:
    m.append(i.encode("UTF-8"))
Exemplo n.º 30
0
class Ui_GroupBox(object):
    def setupUi(self, GroupBox):
        GroupBox.setObjectName("GroupBox")
        GroupBox.resize(434, 435)
        GroupBox.setStyleSheet(
            "QGroupBox { background-color: rgb(100, 255,255); border:1px solid rgb(255, 170, 255); }"
        )

        # ADD GRIDS
        self.gridLayout_9 = QtGui.QGridLayout(GroupBox)
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout_2 = QtGui.QGridLayout()
        self.gridLayout_3 = QtGui.QGridLayout()
        self.gridLayout_4 = QtGui.QGridLayout()
        self.gridLayout_5 = QtGui.QGridLayout()
        self.gridLayout_6 = QtGui.QGridLayout()
        self.gridLayout_7 = QtGui.QGridLayout()
        self.gridLayout_8 = QtGui.QGridLayout()

        # ADD THE GRID TO THE LAYOUT USING ADDLAYOUT
        self.gridLayout.addLayout(self.gridLayout_6, 0, 0, 1, 1)
        self.gridLayout_9.addLayout(self.gridLayout, 0, 0, 1, 1)
        self.gridLayout.addLayout(self.gridLayout_7, 4, 0, 1, 1)
        self.gridLayout.addLayout(self.gridLayout_8, 3, 0, 1, 1)

        # SET ALL THE WIDGETS UNDER GROUPBOX
        self.label = QtGui.QLabel(GroupBox)
        self.label_2 = QtGui.QLabel(GroupBox)
        self.label_3 = QtGui.QLabel(GroupBox)
        self.pushButton = QtGui.QPushButton(GroupBox)
        self.lineEdit = QtGui.QLineEdit(GroupBox)
        self.lineEdit_2 = QtGui.QLineEdit(GroupBox)
        self.textEdit = QtGui.QTextEdit(GroupBox)

        # SET EXTRA PROPERTIES OF ALL WIDGETS NOW
        self.label.setTextFormat(QtCore.Qt.RichText)
        self.label.setAlignment(QtCore.Qt.AlignCenter)

        # SET TITLE AND TEXT OF THE WIDGETS
        self.setTitleText(GroupBox)

        # ADD THE WIDGETS TO THE GRIDLAYOUT
        self.gridLayout_6.addWidget(self.label, 0, 0, 1, 1)
        self.gridLayout_2.addWidget(self.label_2, 0, 0, 1, 1)
        self.gridLayout_3.addWidget(self.lineEdit, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.label_3, 0, 0, 1, 1)
        self.gridLayout_5.addWidget(self.lineEdit_2, 0, 0, 1, 1)
        self.gridLayout_8.addWidget(self.pushButton, 0, 0, 1, 1)
        self.gridLayout_7.addWidget(self.textEdit, 0, 0, 1, 1)

        # SET THE HORIZONTAL LAYOUT
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout_2 = QtGui.QHBoxLayout()

        # ADD THE HORIZONTAL LAYOUT TO THE GRID
        self.horizontalLayout.addLayout(self.gridLayout_2)
        self.horizontalLayout.addLayout(self.gridLayout_3)
        self.horizontalLayout_2.addLayout(self.gridLayout_4)
        self.horizontalLayout_2.addLayout(self.gridLayout_5)

        # CLUB THE GRID TOGETHER AND ADD IT IN INSIDE THE HORIZONTAL LAYOUT USING ADDLAYOUT
        self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 1)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)

        # MAKE ADDITIONAL LAYOUT PROPERTIES SIZEPOLICY,HOR/VERTICAL STRETCHES,MAXLENGTH,DRAGENABLE
        sizePolicy_label2 = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                                              QtGui.QSizePolicy.Expanding)
        sizePolicy_label2.setHorizontalStretch(0)
        sizePolicy_label2.setVerticalStretch(0)
        sizePolicy_label2.setHeightForWidth(
            self.label_2.sizePolicy().hasHeightForWidth())
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Expanding)
        sizePolicy_btn = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                           QtGui.QSizePolicy.Fixed)

        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        # APPLY THE PROPERTIES TO THE WIDGETS
        sizePolicy.setHeightForWidth(
            self.lineEdit.sizePolicy().hasHeightForWidth())
        sizePolicy_btn.setHeightForWidth(
            self.pushButton.sizePolicy().hasHeightForWidth())
        sizePolicy.setHeightForWidth(
            self.lineEdit_2.sizePolicy().hasHeightForWidth())

        self.label_2.setSizePolicy(sizePolicy_label2)
        self.lineEdit.setSizePolicy(sizePolicy)
        self.lineEdit_2.setSizePolicy(sizePolicy)
        self.pushButton.setSizePolicy(sizePolicy_btn)

        self.lineEdit.setMaxLength(32791)
        self.lineEdit.setFrame(True)
        self.lineEdit.setDragEnabled(True)

        # SIGNALS AND EVENTS OF THE WIDGETS
        sig1 = QtCore.SIGNAL("textChanged(QString)")
        self.pushButton.clicked.connect(self.searchZomato)
        QtCore.QMetaObject.connectSlotsByName(GroupBox)

    def setTitleText(self, GroupBox):
        GroupBox.setWindowTitle("GroupBox")
        GroupBox.setTitle("GroupBox")
        self.label.setText(" MY ZOMATO APP")
        self.label_2.setText(" NAME OF THE CITY :-")
        self.label_3.setText(" NAME OF THE RESTAURANT/PUB :-")
        self.pushButton.setText("SUBMIT")

    def searchZomato(self):
        self.cityName = str(self.lineEdit.text())
        self.restName = str(self.lineEdit_2.text())
        self.mykey = '7dcf7b79d4c7bdfd5ffe013ae7361388'
        self.p = Pyzomato(self.mykey)
        print(dir(self.p))
        print('*' * 100)
        print('\n\n')
        print('INSIDE FUNCTION:-', inspect.stack()[0][3])
        print('CITY NAME AND RESTAURANT NAME\'S ARE "-', self.cityName,
              self.restName)
        print('THE ZOMATO API OBJECT:=', self.p)
        print('SEARCHING THE DATABASE FOR YOUR QUERY')
        print('\n\n')
        try:
            self.cityId = self.p.getCityDetails(q=self.cityName)
            l = self.cityId['location_suggestions']
            for d in l:
                for k, v in d.items():
                    if k == 'id':
                        self.cityId = d[k]
                        print('CITY ID:-', self.cityId)

            self.details = self.p.search(q=self.restName,
                                         city=self.cityName,
                                         count=10,
                                         entity_id=self.cityId,
                                         entity_type='city')
            print('\n\n THE DETAILS OF THE RESTAURANT ARE AS FOLLOWS:-',
                  self.details)
            self.output = zomato_script.searchRestaurant(
                self.details, self.restName.upper())
            self.processOutput(self.output)
        except Exception as exc:
            print('INVALID DETAILS ENTERED:-', exc)
            print('TRACEBACK :-', traceback.format_exc())

    def processOutput(self, output):
        f = open('zomato_rest_output.txt')
        a = f.read()
        self.textEdit.setText(a)
        f.close()