Example #1
0
def getData():
	cities = pywapi.get_cities_from_google('de') # or (country = 'fr', hl = 'de')
	locidparis = pywapi.get_loc_id_from_weather_com("Paris")
	locidbs = pywapi.get_loc_id_from_weather_com("Braunschweig")
	locidlondon = pywapi.get_loc_id_from_weather_com("London")

	Bs = pywapi.get_weather_from_weather_com("GMXX0013")
	Paris = pywapi.get_weather_from_weather_com("FRXX0076")
	London = pywapi.get_weather_from_weather_com("UKXX0085")

	datetime = time.strftime("Date: %d-%B-%Y  Time: %H:%M:%S")

	tempBs = str(Bs['current_conditions']['temperature'])
	tempLondon = str(London['current_conditions']['temperature'])
	tempParis = str(Paris['current_conditions']['temperature'])

##	pp.pprint(datetime)
##	pp.pprint("Aktuelle Temperatur in Braunschweig: " + tempBs +" Grad")
##	pp.pprint("Aktuelle Temperatur in London: " + tempLondon +" Grad")
##	pp.pprint("Aktuelle Temperatur in Paris: " + tempParis +" Grad")

	werte = [('Braunschweig', tempBs, str(datetime)),
                 ('London', tempLondon, str(datetime)),
                 ('Paris', tempParis, str(datetime))]
	cursor.executemany("INSERT INTO temperatures VALUES (?,?,?)", werte)
	connection.commit()
Example #2
0
def recommend_action(location, fp):
    import pywapi
    import random
    import json

    #location = raw_input("enter your location : ")
    location_id = pywapi.get_loc_id_from_weather_com(location)
    location_id = location_id[0][0]

    weather = pywapi.get_weather_from_weather_com(location_id)
    print weather['current_conditions']['station'], 'is', weather[
        'current_conditions']['text']

    weather_condition = weather['current_conditions']['text']

    conditions = weather['current_conditions']['text']
    conditions_list = conditions.split()

    with open(fp) as data:
        todo = json.load(data)

    hit = list(set(conditions_list).intersection(todo))

    if hit:
        weather_action = random.choice(todo[random.choice(hit)])

    else:
        weather_action = "Sorry! not smart enough to recommend!"

    return (weather_condition, weather_action)
Example #3
0
 def get_id_by_location(self, location):
     """
     enter a city name and retrieve the top ID result from weather.com
     can enter just a city name (Portland),
     or a city name and State code code example:( Portland, OR)
     or a city name and full state name example: (Portland, Oregon)
     """
     self.given_location = location
     locations = pywapi.get_loc_id_from_weather_com(
         location)  # this returns a dictionary
     # returns: {0: (u'USOR0275', u'Portland, OR'), 'count': 1}
     # returns {'count': 0}
     for x in locations:
         if locations['count'] == '0':
             location_id = '0000'
             return location_id
     else:
         location_list = locations[
             0]  # get the first item out of the dict, the key is 0 - this returns a tuple
         location_list = str(location_list)  # change it to a string
         location_list = location_list.split(
         )  # split the string into a list
         location_id = location_list[
             0]  # pull first element out of the list
         location_id = location_id[
             3:-2]  # strip the u'\ off the front and ', ' off the end.
         return location_id
def fetch_weather():
    try:
         # find the city_id from weather.com
        city_list = pywapi.get_loc_id_from_weather_com(CITY_NAME)
        city_id = city_list[0][0]
        
        # retrive weather data from weather.com
        weather_info = pywapi.get_weather_from_weather_com(city_id)

        # print raw data (debug only)
        print('\nRaw Retrived Data:')
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(weather_info)

        # get units
        units = {}
        units['distance'] = weather_info['units']['distance']
        units['pressure'] = weather_info['units']['pressure'] 
        units['rainfall'] = weather_info['units']['rainfall']
        units['speed'] = weather_info['units']['speed']
        units['temperature'] = weather_info['units']['temperature']

        # output current condition
        print('[City]')
        print(weather_info['location']['name'])
        print('\n[Current]')
        print('Description: ' + weather_info['current_conditions']['text'])
        print('Temperature: ' + weather_info['current_conditions']['temperature'] \
				+ ' ' + units['temperature'])
        print('Humidity: ' + weather_info['current_conditions']['humidity'] +'%')
        print(weather_info['current_conditions']['wind'])

        # forecasts
        print('\n[Forecast]')
        for i in weather_info['forecasts']:
                print(i['date'] + ',' + i['day_of_week'] + ': ' \
                    + i['day']['brief_text'] + ', ' \
                    + i['low'] + '-' + i['high'] + ' ' + units['temperature'])

        # package data into a string
        weather_str = weather_info['location']['name'] + ';' \
                + 'Now: ' + weather_info['current_conditions']['text'] + ';' \
                + 'Temp: ' + weather_info['current_conditions']['temperature'] + ' C;' \
                + 'Humid: ' + weather_info['current_conditions']['humidity'] + ' %;' \
                + 'Today: ' + weather_info['forecasts'][0]['low'] + ' - ' \
                + weather_info['forecasts'][0]['high'] + ';\n'

        return weather_str
		
	
    except:
        pass
Example #5
0
def location_id_weather(request,busqueda):

     #Sin permisos
     ip='80.59.169.236' #simulo otra ip
     #ip = get_ip(request)
     info_ip=get_info_ip()
     #obtengo la zona horaria y separo en dos con la barra para quedarme con la ciudad
     time_zone=info_ip['time_zone'].split("/")
     #junto ciudad con country_name para buscar el id en la bbdd de weather.com
     city_time=','.join([list(time_zone[1])[0],info_ip['country_name']])
     city_time1=','.join([time_zone[1],info_ip['country_name']])
     #busco id de la ciudad+pais en weather.com
     #pywapi.get_loc_id_from_weather_com('M,Spain')
     loc_id_weather_com1=pywapi.get_loc_id_from_weather_com(city_time)
     loc_id_weather_com2=pywapi.get_loc_id_from_weather_com(city_time1)
     loc_id_weather_com = dict(loc_id_weather_com1.items() + loc_id_weather_com2.items()) 
     n_stat_yahoo=len(loc_id_weather_com)
     for i in range(0,len(loc_id_weather_com1)-1):
           loc_id_weather_com[i]=loc_id_weather_com1[i]  
           loc_id_weather_com[i+10]=loc_id_weather_com2[i] 
             
     return loc_id_weather_com
Example #6
0
def set_city_in_session(intent, session):
    """ Sets the color in the session and prepares the speech to reply to the
    user.
    """

    card_title = intent['name']
    session_attributes = {}
    status = False
    op = "Please Enter Country first"
    print("after getting city")
    if 'Cityname' in intent['slots']:
        city_name = intent['slots']['Cityname']['value']
        session_attributes = city_name_attribute(city_name, session)
        print(session_attributes['city'])
        if city_name == session_attributes['city']:
            if session.get('attributes', {}) and "country" in session.get(
                    'attributes', {}):
                country_name = session['attributes']['country']
                mystr = city_name + ',' + country_name
                lookup = get_loc_id_from_weather_com(mystr)
                if lookup['count'] == 0:
                    print("city " + city_name + " Not in " + country_name)
                    op = "city name " + city_name + " not present in the given country  "
                    should_end_session = False
                else:
                    city_id = lookup[0][0]
                    weather_com_result = get_weather_from_weather_com(city_id)
                    op ="Weather of " + city_name + " in " + session['attributes']['country'] +" country - " + \
                    " day : " + weather_com_result['forecasts'][0]['day_of_week'] + " , "  + \
                    " sunrise : " + weather_com_result['forecasts'][0]['sunrise'] +  " , "  + \
                    " sunset : " + weather_com_result['forecasts'][0]['sunset'] +  "," + \
                    " max : " + weather_com_result['forecasts'][0]['high'] + "," + \
                    "min : " +  weather_com_result['forecasts'][0]['low'] + "," + \
                    "weather is : " + weather_com_result['current_conditions']['text'].lower() + \
                    " and " + weather_com_result['current_conditions']['temperature'] + " C. Good Bye "

        else:
            op = "Invalid City name please retry by giving country and city names"
            status = False
    else:
        op = "City name not present in intent"
    speech_output = op
    reprompt_text = op
    should_end_session = status

    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
 def get_id_by_location(self, location):
     """
     enter a city name and retrieve the top ID result from weather.com
     can enter just a city name (Portland),
     or a city name and State code code example:( Portland, OR)
     or a city name and full state name example: (Portland, Oregon)
     """
     self.given_location = location
     locations = pywapi.get_loc_id_from_weather_com(location) # this returns a dictionary looking item
     # This is ugly, is there a better way?
     location_list = locations[0]  # get the first item out of the dict, the key is 0 - this returns a tuple!
     location_list = str(location_list)  # change it to a string
     location_list = location_list.split()  # split the string into a list
     location_id = location_list[0]  # pull first element out of the list
     location_id = location_id[3:-2]  # strip the u'\ off the front and ', ' off the end.
     return location_id
Example #8
0
    def check_weather(self,location,token,current):
        # current=True: give current weather
        day=0
        if 'tomorrow' in token:
            day=1
            current=0
            token.remove('tomorrow')
        if 'in' in token:
            try:
                location=' '.join(token[token.index('in')+1:])
            except:
                pass
        location_id=pywapi.get_loc_id_from_weather_com(location)
        city=location.split(',')[0]
        if type(location_id) is dict:
            try:
                city=location_id[0][1].split(',')[0]
                location_id=location_id[0][0]
            except:
                pass

        try:
            data=pywapi.get_weather_from_weather_com( location_id , units = 'metric' )
            rain=data['forecasts'][day]['day']['chance_precip']
            uv=data['current_conditions']['uv']['index']
            if current:
                self.speak('Currently it has ' + data['current_conditions']['temperature'] + ' degrees in ' + city + ' and it\'s ' + data['current_conditions']['text'])
                if int(uv)>=5:
                    self.speak('Attention! The current UV index is '+uv+', so don\'t forget the sunscreen.')
            if day==1:
                msg='Tomorrow\'s high in ' +city+' is ' + data['forecasts'][day]['high'] + ' degrees, low temperature is ' + data['forecasts'][day]['low']
                if (data['forecasts'][day]['day']['text']!=""):
                    msg+=', and it will be ' +data['forecasts'][day]['day']['text']
                self.speak(msg)
            else:
                msg='Today\'s high is ' + data['forecasts'][day]['high'] + ' degrees, low temperature is ' + data['forecasts'][day]['low']
                if (data['forecasts'][day]['day']['text']!=""):
                    msg+=', and it will be ' +data['forecasts'][day]['day']['text']
                self.speak(msg)
            if int(rain)>=50:
                self.speak('Attention! The probability of rain is '+rain+'%, so better take an umbrella.')
        except:
            self.speak('Sorry, I do not know the weather in '+city)
Example #9
0
def get_weather():
    city_list = pywapi.get_loc_id_from_weather_com(CITY_NAME)
    city_id = city_list[0][0]

    # main loop
    try:
        # retrive weather data from weather.com
        weather_info = pywapi.get_weather_from_weather_com(city_id)
    except:
        return

    # get units
    units = {}
    units['distance'] = weather_info['units']['distance']
    units['pressure'] = weather_info['units']['pressure']
    units['rainfall'] = weather_info['units']['rainfall']
    units['speed'] = weather_info['units']['speed']
    units['temperature'] = weather_info['units']['temperature']

    # output current condition
    print '[Current]</br>'
    print weather_info['location']['name'] + '</br>'
    print 'Description: ' + weather_info['current_conditions']['text'] + '</br>'
    print 'Temperature: ' + weather_info['current_conditions']['temperature'] + \
       ' ' + units['temperature'] + '</br>'
    print 'Humidity: ' + weather_info['current_conditions'][
        'humidity'] + '%' + '</br>'

    # forecasts
    print '</br>[Forecast] </br>'
    for i in weather_info['forecasts']:
        print i['date'] + ',' + i['day_of_week'] + ': ' \
         + i['day']['brief_text'] + ', ' \
         + i['low'] + '-' + i['high'] + ' ' + units['temperature'] + '</br>'

        # package data into a string
    weather_str = weather_info['location']['name'] + ';' \
     + weather_info['current_conditions']['text'] + ';' \
     + weather_info['current_conditions']['temperature'] + ';' \
     + weather_info['current_conditions']['humidity'] + ';' \
     + weather_info['forecasts'][0]['high'] + ';' \
     + weather_info['forecasts'][0]['low'] + ';</br>'
Example #10
0
def f_weather(self, command):
    """.weather <location> - Show the weather at the given location."""

    query = command.group(2)
    if not query: 
        return self.msg(command.sender, 'Try .weather London, for example?')

    locations = pywapi.get_loc_id_from_weather_com(query)

    if 'count' not in locations or locations['count'] == 0:
        return self.msg(command.sender, "Couldn't find location for {0}".format(query))
      
    result = pywapi.get_weather_from_weather_com(locations[0][0])
    output = "{0} and {1}{2} in {3}".format(
        string.capitalize(result['current_conditions']['text']),
        result['current_conditions']['temperature'],
        result['units']['temperature'],
        locations[0][1])

    return self.msg(command.sender, output.encode('utf-8'))
Example #11
0
 def get_id_by_location(self, location):
     """
     enter a city name and retrieve the top ID result from weather.com
     can enter just a city name (Portland),
     or a city name and State code code example:( Portland, OR)
     or a city name and full state name example: (Portland, Oregon)
     """
     self.given_location = location
     locations = pywapi.get_loc_id_from_weather_com(location)  # this returns a dictionary
     # returns: {0: (u'USOR0275', u'Portland, OR'), 'count': 1}
     # returns {'count': 0}
     for x in locations:
         if locations["count"] == "0":
             location_id = "0000"
             return location_id
     else:
         location_list = locations[0]  # get the first item out of the dict, the key is 0 - this returns a tuple
         location_list = str(location_list)  # change it to a string
         location_list = location_list.split()  # split the string into a list
         location_id = location_list[0]  # pull first element out of the list
         location_id = location_id[3:-2]  # strip the u'\ off the front and ', ' off the end.
         return location_id
Example #12
0
        if (phrase[i+1] != "CLINTON" or phrase[i+2] != "NY"): # clinton ny special case
            locale = phrase[i+1]
    elif phrase[i] == "ON":
        if phrase[i+1] in months:
            day = " ".join(phrase[i+1:i+3])
        else: 
            day = phrase[i+1]
    elif phrase[i] in months:
        day = " ".join(phrase[i:i+2])
    elif re.match("\d?\d\/\d?\d", phrase[i]):
        day = phrase[i]
    elif phrase[i] in ['TODAY', 'TOMORROW', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']:
        day = phrase[i]


loc_id_list = pywapi.get_loc_id_from_weather_com(locale)

ans = 0

if locale != "13323" and loc_id_list['count'] > 1:
    for i in range(loc_id_list['count']):
        yn = raw_input("Did you mean, " + loc_id_list[i][1] + "? ")
        if re.match("[yY](es|)?", yn):
            ans = i
            break
    

loc_id = loc_id_list[ans][0]
loc_name = loc_id_list[ans][1]

weather_com_result = pywapi.get_weather_from_weather_com(loc_id)
Example #13
0
import pywapi
import pprint
import time

# -- Confiurations  ------------------------------------------------------------
# the city name you want to search
CITY_NAME = 'York, YOR, United Kingdom'

# this defines the update time (s) of the weather data
UPDATE_TIME = 30

# -- Main Program  -------------------------------------------------------------
# (no need to change contents below this line)

# find the city_id from weather.com
city_list = pywapi.get_loc_id_from_weather_com(CITY_NAME)

cnt = city_list['count']
print 'Warning: we found ' + str(cnt) + ' possible cities, ' + \
      'We will use the first one!'
for i in range(cnt):
    print city_list[i]
city_id = city_list[0][0]

# main loop
while True:
    try:
        # retrive weather data from weather.com
        weather_info = pywapi.get_weather_from_weather_com(city_id)

        # print raw data (debug only)
Example #14
0
def profile_populator():
    def empty(variable):
        if variable:
            return False
        else:
            return True

    tts_local('Welcome to Melissa. Let us generate your profile!')
    print('Welcome to Melissa. Let us generate your profile!')
    print('Press Enter for using default values.')

    va_name = raw_input('What would you like to name me?: ')
    if empty(va_name):
        va_name = 'Melissa'

    while (True):
        va_gender = raw_input('What is my gender ((m)ale/(f)emale)?: ')
        if va_gender in ('male', 'm', 'female', 'f', ''):
            if empty(va_gender):
                va_gender = 'female'
            elif va_gender == 'm':
                va_gender = 'male'
            elif va_gender == 'f':
                va_gender = 'female'
            break
        print('Invalid input, please enter male, female or <ENTER>.')

    name = raw_input('Your name: ')
    if empty(name):
        name = 'Tanay'

    while (True):
        stt = raw_input(
            'STT Engine ((g)oogle/(s)phinx/(t)elegram/(k)eyboard): ').lower()
        if stt in ('g', 'google', 's', 'sphinx', 'k', 'keyboard', 't',
                   'telegram', ''):
            if empty(stt) or stt == 'g':
                stt = 'google'
            elif stt == 's':
                stt = 'sphinx'
            elif stt == 't':
                stt = 'telegram'
            elif stt == 'k':
                stt = 'keyboard'
            break
        print('Invalid input, please enter(g)oogle, (s)phinx, (t)elegram,' +
              '(k)eyboard or < ENTER > .')

    telegram_username = raw_input('Your username at Telegram: ')
    if empty(telegram_username):
        telegram_username = ''

    city_name = raw_input('Name of city where you live: ')
    if empty(city_name):
        city_name = 'New Delhi'

    city_code = raw_input('Code of city from weather.com\
 or <ENTER> for a search based on the name\
 of the city you live in: ')
    if empty(city_code):
        city_list = pywapi.get_loc_id_from_weather_com(unicode(city_name))
        if city_list['count'] == 0:
            print 'Sorry, search results were empty.'
            city_code = 'INXX0096'
        else:
            print 'Cities returned are: '
            for city_list_i in range(city_list['count']):
                print str(city_list_i + 1) + ": " + city_list[city_list_i][1]
            while (True):
                city_choice_i = ''
                city_choice_i = raw_input('Enter the index of \
the city of your choice: ')
                if empty(city_choice_i):
                    city_code = 'INXX0096'
                    break
                city_choice_i = int(city_choice_i)
                if 1 <= city_choice_i <= city_list['count']:
                    city_code = city_list[city_choice_i - 1][0]
                    break
                else:
                    print 'Enter an index from one of the choices.\
 Try again!'

    while (True):
        degrees = raw_input('(c)elsius/(f)ahrenheit): ').lower()
        if degrees in ('c', 'celsius', 'f', 'fahrenheit', ''):
            if empty(degrees) or degrees == 'c':
                degrees = 'celsius'
            elif degrees == 'f':
                degrees = 'fahrenheit'
            break
        print('Invalid input, please enter(c)elsius, (f)ahrenheit) or' +
              '<ENTER > .')

    tts = 'telegram'

    hotword_detection = 'off'

    access_key = 'xxxx'
    secret_key = 'xxxx'

    access_token = 'xxxx'
    access_token_secret = 'xxxx'
    consumer_key = 'xxxx'
    consumer_secret = 'xxxx'

    client_id = 'xxxx'
    client_secret = 'xxxx'

    telegram_token = 'xxxx'

    modeldir = './data/model/'
    hmm = 'hmm/en_us/hub4wsj_sc_8k'
    lm = 'lm/sphinx.lm'
    dic = 'lm/sphinx.dic'

    modules = 'melissa.actions'
    actions_db_file = ':memory:'
    memory_db = './data/memory.db'

    profile_data = {
        'va_name': va_name,
        'va_gender': va_gender,
        'name': name,
        'stt': stt,
        'tts': tts,
        'hotword_detection': hotword_detection,
        'telegram_username': telegram_username,
        'telegram_token': telegram_token,
        'city_name': city_name,
        'city_code': city_code,
        'degrees': degrees,
        'pocketsphinx': {
            'modeldir': modeldir,
            'hmm': hmm,
            'lm': lm,
            'dic': dic
        },
        'ivona': {
            'access_key': access_key,
            'secret_key': secret_key
        },
        'modules': modules,
        'actions_db_file': actions_db_file,
        'memory_db': memory_db
    }

    with open('profile.json', 'w') as outfile:
        json.dump(profile_data, outfile, indent=4)
Example #15
0
def getWeather(city):
	id = pywapi.get_loc_id_from_weather_com(city)
	result = pywapi.get_weather_from_weather_com(id[0][0], 'metric')
	cur = result['current_conditions']
	res = [city, cur['temperature'], cur['text'], cur['visibility']]
	return res
Example #16
0
    elif phrase[i] == "ON":
        if phrase[i + 1] in months:
            day = " ".join(phrase[i + 1:i + 3])
        else:
            day = phrase[i + 1]
    elif phrase[i] in months:
        day = " ".join(phrase[i:i + 2])
    elif re.match("\d?\d\/\d?\d", phrase[i]):
        day = phrase[i]
    elif phrase[i] in [
            'TODAY', 'TOMORROW', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY',
            'FRIDAY', 'SATURDAY', 'SUNDAY'
    ]:
        day = phrase[i]

loc_id_list = pywapi.get_loc_id_from_weather_com(locale)

ans = 0

if locale != "13323" and loc_id_list['count'] > 1:
    for i in range(loc_id_list['count']):
        yn = raw_input("Did you mean, " + loc_id_list[i][1] + "? ")
        if re.match("[yY](es|)?", yn):
            ans = i
            break

loc_id = loc_id_list[ans][0]
loc_name = loc_id_list[ans][1]

weather_com_result = pywapi.get_weather_from_weather_com(loc_id)
def profile_populator():
    def empty(variable):
        if variable:
            return False
        else:
            return True

    tts_local('Welcome to Melissa. Let us generate your profile!')
    print('Welcome to Melissa. Let us generate your profile!')
    print('Press Enter for using default values.')

    va_name = raw_input('What would you like to name me?: ')
    if empty(va_name):
        va_name = 'Melissa'

    while (True):
        va_gender = raw_input('What is my gender ((m)ale/(f)emale)?: ')
        if va_gender in ('male', 'm', 'female', 'f', ''):
            if empty(va_gender):
                va_gender = 'female'
            elif va_gender == 'm':
                va_gender = 'male'
            elif va_gender == 'f':
                va_gender = 'female'
            break
        print('Invalid input, please enter male, female or <ENTER>.')

    name = raw_input('Your name: ')
    if empty(name):
        name = 'Tanay'

    while (True):
        stt = raw_input(
            'STT Engine ((g)oogle/(s)phinx/(t)elegram/(k)eyboard): ').lower()
        if stt in ('g', 'google', 's', 'sphinx', 'k', 'keyboard', 't',
                   'telegram', ''):
            if empty(stt) or stt == 'g':
                stt = 'google'
            elif stt == 's':
                stt = 'sphinx'
            elif stt == 't':
                stt = 'telegram'
            elif stt == 'k':
                stt = 'keyboard'
            break
        print('Invalid input, please enter(g)oogle, (s)phinx, (t)elegram,' +
              '(k)eyboard or < ENTER > .')

    telegram_username = input('Your username at Telegram: ')
    if empty(telegram_username):
        telegram_username = '******'

    while (True):
        music_path = raw_input('Path to your music directory: ')
        if empty(music_path):
            music_path = '.'
            break
        if os.path.isdir(music_path):
            break
        print('Invalid input, please enter a valid directory path or <ENTER>.')

    while (True):
        images_path = raw_input('Path to your images directory: ')
        if empty(images_path):
            images_path = '.'
            break
        if os.path.isdir(images_path):
            break
        print('Invalid input, please enter a valid directory path or <ENTER>.')

    city_name = raw_input('Name of city where you live: ')
    if empty(city_name):
        city_name = 'New Delhi'

    city_code = raw_input('Code of city from weather.com\
    or <ENTER> for a search based on the name\
    of the city you live in: ')
    if empty(city_code):
        city_list = pywapi.get_loc_id_from_weather_com(unicode(city_name))
        if city_list['count'] == 0:
            print('Sorry, search results were empty.')
            city_code = 'INXX0096'
        else:
            print('Cities returned are: ')
            for city_list_i in range(city_list['count']):
                print(str(city_list_i + 1) + ": " + city_list[city_list_i][1])
            while (True):
                city_choice_i = ''
                city_choice_i = raw_input('Enter the index of \
the city of your choice: ')
                if empty(city_choice_i):
                    city_code = 'INXX0096'
                    break
                city_choice_i = int(city_choice_i)
                if 1 <= city_choice_i <= city_list['count']:
                    city_code = city_list[city_choice_i - 1][0]
                    break
                else:
                    print('Enter an index from one of the choices.\
 Try again!')

    while (True):
        degrees = raw_input('(c)elsius/(f)ahrenheit): ').lower()
        if degrees in ('c', 'celsius', 'f', 'fahrenheit', ''):
            if empty(degrees) or degrees == 'c':
                degrees = 'celsius'
            elif degrees == 'f':
                degrees = 'fahrenheit'
            break
        print('Invalid input, please enter(c)elsius, (f)ahrenheit) or' +
              '<ENTER > .')

    gmail_address = raw_input('Enter your gmail address ([email protected]): ')
    gmail_password = ''
    if len(gmail_address) > 0:
        gmail_password = getpass()

    icloud_username = raw_input(
        'Enter your icloud username/address (???@???.com): ')
    icloud_password = ''
    if len(icloud_username) > 0:
        icloud_password = getpass()

    while (True):
        push_bullet = raw_input('Enter your Pushbullet token: ')
        if empty(push_bullet):
            break
        elif not isinstance(push_bullet, str):
            print("Invalid token")
        elif push_bullet[0:2] != "o.":
            print("Invalid token")
        else:
            break

    tts = 'xxxx'

    hotword_detection = 'on'

    access_key = 'xxxx'
    secret_key = 'xxxx'

    access_token = 'xxxx'
    access_token_secret = 'xxxx'
    consumer_key = 'xxxx'
    consumer_secret = 'xxxx'

    client_id = 'xxxx'
    client_secret = 'xxxx'

    telegram_token = 'xxxx'

    modeldir = './data/model/'
    hmm = 'hmm/en_us/hub4wsj_sc_8k'
    lm = 'lm/sphinx.lm'
    dic = 'lm/sphinx.dic'

    modules = 'melissa.actions'
    actions_db_file = ':memory:'
    memory_db = './data/memory.db'

    profile_data = {
        'va_name': va_name,
        'va_gender': va_gender,
        'name': name,
        'stt': stt,
        'tts': tts,
        'hotword_detection': hotword_detection,
        'telegram_username': telegram_username,
        'telegram_token': telegram_token,
        'music_path': music_path,
        'images_path': images_path,
        'city_name': city_name,
        'city_code': city_code,
        'degrees': degrees,
        'pocketsphinx': {
            'modeldir': modeldir,
            'hmm': hmm,
            'lm': lm,
            'dic': dic
        },
        'twitter': {
            'access_token': access_token,
            'access_token_secret': access_token_secret,
            'consumer_key': consumer_key,
            'consumer_secret': consumer_secret
        },
        'imgur': {
            'client_id': client_id,
            'client_secret': client_secret
        },
        'ivona': {
            'access_key': access_key,
            'secret_key': secret_key
        },
        'gmail': {
            'address': gmail_address,
            'password': gmail_password
        },
        'icloud': {
            'username': icloud_username,
            'password': icloud_password
        },
        'pushbullet': push_bullet,
        'modules': modules,
        'actions_db_file': actions_db_file,
        'memory_db': memory_db
    }

    with open('profile.json', 'w') as outfile:
        json.dump(profile_data, outfile, indent=4)
Example #18
0
#import requests

#url = "http://weather.yahooapis.com/forecastrss?w=26804118&u=c"
#response = requests.get(url)
#print response.content
import pprint
import pywapi
id = pywapi.get_loc_id_from_weather_com("oklahoma city, ok")
print id

result = pywapi.get_weather_from_weather_com(id[0][0], 'metric')
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
def fetch_weather(session_id, context):
    location = context['loc']
    location_id = pywapi.get_loc_id_from_weather_com(location)[0][0]
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)
    context['forecast'] = weather_com_result["current_conditions"]["text"]
    return context
def profile_populator():
    def empty(variable):
        if variable:
            return False
        else:
            return True

    tts_local('Welcome to Melissa. Let us generate your profile!')
    print('Welcome to Melissa. Let us generate your profile!')
    print('Press Enter for using default values.')

    va_name = raw_input('What would you like to name me?: ')
    if empty(va_name):
        va_name = 'Melissa'

    while(True):
        va_gender = raw_input('What is my gender ((m)ale/(f)emale)?: ')
        if va_gender in ('male', 'm', 'female', 'f', ''):
            if empty(va_gender):
                va_gender = 'female'
            elif va_gender == 'm':
                va_gender = 'male'
            elif va_gender == 'f':
                va_gender = 'female'
            break
        print('Invalid input, please enter male, female or <ENTER>.')

    name = raw_input('Your name: ')
    if empty(name):
        name = 'Tanay'

    while(True):
        stt = raw_input(
            'STT Engine ((g)oogle/(s)phinx/(t)elegram/(k)eyboard): ').lower()
        if stt in ('g', 'google', 's', 'sphinx', 'k',
                   'keyboard', 't', 'telegram', ''):
            if empty(stt) or stt == 'g':
                stt = 'google'
            elif stt == 's':
                stt = 'sphinx'
            elif stt == 't':
                stt = 'telegram'
            elif stt == 'k':
                stt = 'keyboard'
            break
        print('Invalid input, please enter(g)oogle, (s)phinx, (t)elegram,' +
              '(k)eyboard or < ENTER > .')

    telegram_username = raw_input('Your username at Telegram: ')
    if empty(telegram_username):
        telegram_username = '******'

    while(True):
        music_path = raw_input('Path to your music directory: ')
        if empty(music_path):
            music_path = '.'
            break
        if os.path.isdir(music_path):
            break
        print('Invalid input, please enter a valid directory path or <ENTER>.')

    while(True):
        images_path = raw_input('Path to your images directory: ')
        if empty(images_path):
            images_path = '.'
            break
        if os.path.isdir(images_path):
            break
        print('Invalid input, please enter a valid directory path or <ENTER>.')

    city_name = raw_input('Name of city where you live: ')
    if empty(city_name):
        city_name = 'New Delhi'

    city_code = raw_input('Code of city from weather.com\
 or <ENTER> for a search based on the name\
 of the city you live in: ')
    if empty(city_code):
        city_list = pywapi.get_loc_id_from_weather_com(unicode(city_name))
        if city_list['count'] == 0:
            print 'Sorry, search results were empty.'
            city_code = 'INXX0096'
        else:
            print 'Cities returned are: '
            for city_list_i in range(city_list['count']):
                print str(city_list_i+1) + ": " + city_list[city_list_i][1]
            while(True):
                city_choice_i = ''
                city_choice_i = raw_input('Enter the index of \
the city of your choice: ')
                if empty(city_choice_i):
                    city_code = 'INXX0096'
                    break
                city_choice_i = int(city_choice_i)
                if 1 <= city_choice_i <= city_list['count']:
                    city_code = city_list[city_choice_i-1][0]
                    break
                else:
                    print 'Enter an index from one of the choices.\
 Try again!'

    while(True):
        degrees = raw_input('(c)elsius/(f)ahrenheit): ').lower()
        if degrees in ('c', 'celsius', 'f', 'fahrenheit', ''):
            if empty(degrees) or degrees == 'c':
                degrees = 'celsius'
            elif degrees == 'f':
                degrees = 'fahrenheit'
            break
        print('Invalid input, please enter(c)elsius, (f)ahrenheit) or' +
              '<ENTER > .')

    gmail_address = raw_input('Enter your gmail address ([email protected]): ')
    gmail_password = ''
    if len(gmail_address) > 0:
        gmail_password = getpass()

    icloud_username = raw_input(
        'Enter your icloud username/address (???@???.com): ')
    icloud_password = ''
    if len(icloud_username) > 0:
        icloud_password = getpass()

    while(True):
        push_bullet = raw_input('Enter your Pushbullet token: ')
        if empty(push_bullet):
            break
        elif not isinstance(push_bullet, str):
            print("Invalid token")
        elif push_bullet[0:2] != "o.":
            print("Invalid token")
        else:
            break

    tts = 'xxxx'

    hotword_detection = 'on'

    access_key = 'xxxx'
    secret_key = 'xxxx'

    access_token = 'xxxx'
    access_token_secret = 'xxxx'
    consumer_key = 'xxxx'
    consumer_secret = 'xxxx'

    client_id = 'xxxx'
    client_secret = 'xxxx'

    telegram_token = 'xxxx'

    modeldir = './data/model/'
    hmm = 'hmm/en_us/hub4wsj_sc_8k'
    lm = 'lm/sphinx.lm'
    dic = 'lm/sphinx.dic'

    modules = 'melissa.actions'
    actions_db_file = ':memory:'
    memory_db = './data/memory.db'

    profile_data = {
        'va_name': va_name,
        'va_gender': va_gender,
        'name': name,
        'stt': stt,
        'tts': tts,
        'hotword_detection': hotword_detection,
        'telegram_username': telegram_username,
        'telegram_token': telegram_token,
        'music_path': music_path,
        'images_path': images_path,
        'city_name': city_name,
        'city_code': city_code,
        'degrees': degrees,
        'pocketsphinx': {
            'modeldir': modeldir,
            'hmm': hmm,
            'lm': lm,
            'dic': dic
        },
        'twitter': {
            'access_token': access_token,
            'access_token_secret': access_token_secret,
            'consumer_key': consumer_key,
            'consumer_secret': consumer_secret
        },
        'imgur': {
            'client_id': client_id,
            'client_secret': client_secret
        },
        'ivona': {
            'access_key': access_key,
            'secret_key': secret_key
        },
        'gmail': {
            'address': gmail_address,
            'password': gmail_password
        },
        'icloud': {
            'username': icloud_username,
            'password': icloud_password
        },
        'pushbullet': push_bullet,
        'modules': modules,
        'actions_db_file': actions_db_file,
        'memory_db': memory_db
    }

    with open('profile.json', 'w') as outfile:
        json.dump(profile_data, outfile, indent=4)
def fetch_weather(session_id, context):
    location = context['loc']
    location_id = pywapi.get_loc_id_from_weather_com(location)[0][0]
    weather_com_result = pywapi.get_weather_from_weather_com(location_id)
    context['forecast'] = weather_com_result["current_conditions"]["text"]
    return context
Example #22
0
import pywapi
import iot_yahoo_codes
#import serial
import pprint
from dashboard_emulation import Forecasts

pp = pprint.PrettyPrinter()

pp.pprint (pywapi.get_where_on_earth_ids("Stockholm, AB, Sweden"))
pp.pprint(pywapi.get_where_on_earth_ids("Krakow, MA, Polska"))
pp.pprint(pywapi.get_where_on_earth_ids("Istanbul, 34, Turkey"))

pp.pprint (pywapi.get_loc_id_from_weather_com("Stockholm")) #{'count': 2, 0: (LOCID1, Placename1), 1: (LOCID2, Placename2)}
pp.pprint (pywapi.get_loc_id_from_weather_com("Krakow")) #{'count': 2, 0: (LOCID1, Placename1), 1: (LOCID2, Placename2)}
pp.pprint (pywapi.get_loc_id_from_weather_com("Istanbul")) #{'count': 2, 0: (LOCID1, Placename1), 1: (LOCID2, Placename2)}

print "======================="
my_town_id, my_town_name = pywapi.get_loc_id_from_weather_com("Stockholm")[0]
pp.pprint(pywapi.get_weather_from_weather_com(my_town_id,'metric')) #input: my_town_id e.g. = 'PLXX0012'

print "======================="
my_town_id = pywapi.get_where_on_earth_ids("Stockholm").keys()[0]
pp.pprint(pywapi.get_weather_from_yahoo(my_town_id, 'metric')) #input: my_town_id e.g. = u'2500064'


forecastsObj = Forecasts()