Beispiel #1
0
def IvyAbility(command):
    
    #open website function/ability
    if "open reddit" in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        IvyResponse("Your cool shit reddit site has openned for you")
    elif 'open google' in command:
        reg_ex = re.search('open google(.*)', command)
        url = 'https://www.google.co.uk/'
        webbrowser.open(url)
        IvyResponse("Your requested website has opened for you")
    elif 'open' in command:
        reg_ex = re.search('open(.*)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://www.' + domain
            webbrowser.open(url)
            IvyResponse('Opened')
    elif 'google' in command:
        reg_ex = re.search('google(.*)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            url = 'https://www.google.com/search?q=' + domain
            webbrowser.open(url)
            IvyResponse("I has searched your requested on website. Take a look at what I found")
        else:
            pass
        
    #find weather and weather forecast function/ability
    elif 'current weather in' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='37a0944f43b76456cbc580615fe4c676')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            IvyResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))
    elif 'weather forecast in' in command:
        reg_ex = re.search('weather forecast in (.*)', command)
        if reg_ex:
            api_key = 'fb14f083b77e4c99baf4f4b6e1d8c50d'
            api = Api(api_key)
            location = reg_ex.group(1)
            IvyResponse('How many days you want to forecast?')
            day_of_forecast = myCommand()
            forecast = api.get_forecast(days = day_of_forecast, city = location)
            forecast_list = forecast.get_series(['temp','max_temp','min_temp','weather'])
            IvyResponse("The weather forecast for " + str(location))
            weather_data = []
            for forecast in forecast_list:
                weather_data.append(f''' On {forecast['datetime'] : %d %B %Y},
                         the weather is {forecast['weather']['description']}. The temperature will be {forecast['temp']} celsius degree
                         with maximum temperature will be {forecast['max_temp']} and minimum temperature will be {forecast['min_temp']}
                         '''
                         )
            b = ''.join(weather_data)
            IvyResponse(b)
        
    #send email/mail funcion
    elif 'email' in command or 'mail' in command:
        IvyResponse("Who is the recipient?")
        recipient = myCommand()
        if "john" in recipient or "david" in recipient:
            recipient_mail_add = '*****@*****.**'
        elif "mine" in recipient or "my" in recipient:
            IvyResponse("You meant Mai, isn't it?")
            y_n = myCommand()
            if 'yes' in y_n or 'yeah' in y_n:
                recipient_mail_add = '*****@*****.**'
            else:
                pass
        else:
            IvyResponse("What is his or her mail address please?")
            recipient_mail_add = myCommand()
        IvyResponse('What is the subject of this email please?')
        subject_mail = myCommand()
        IvyResponse('What do you want to say in the email?')
        body = myCommand()
        IvyResponse('Do you want to attach anything to the mail?')
        att_ans = myCommand()
        if 'yes' in att_ans or 'yea' in att_ans:
            IvyResponse('What do you want to send sir?')
            file = myCommand()
            if 'song' in file:
                path = '/Users/baileyvu/Desktop/Bad Guy - Billie Eilish_Justin Bieber.m4a'
                file_name = path
                IvyResponse('Sending email through Gmail')
            elif 'ivy' in file:
                path = '/Users/baileyvu/Desktop/test_7.py'
                file_name = path
                IvyResponse('Sending email though gmail')
                try:
                    yag = yagmail.SMTP('*****@*****.**')
                    yag.send(
                            to=recipient_mail_add,
                            subject=subject_mail,
                            contents=body,
                            attachments=file_name)
                    IvyResponse('Mail sent')
                except sr.UnknownValueError:
                    IvyResponse('I can\'t understand what you mean!')
            
        else:
            IvyResponse('Sending your requested Mail')
            try:
                yag = yagmail.SMTP('*****@*****.**')
                yag.send(
                        to=recipient_mail_add,
                        subject=subject_mail,
                        contents=body
                        )
                IvyResponse('Mail sent')
            except sr.UnknownValueError:
                IvyResponse('I can\'t understand what you mean!')
    
    #'tell me about' function
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                detail = ny.content[:1000].encode('utf-8')
                IvyResponse(str(detail))
        except Exception as e:
            IvyResponse(e)
            
    #telling time function
    elif 'time' in command:
        now = datetime.datetime.now()
        format_time = '%I:%M %p'
        ans1 = 'It is ' + now.strftime(format_time) + ' at the moment.'
        ans2 = 'Current time is ' + now.strftime(format_time)
        IvyResponse(random.choice([ans1, ans2]))
    elif 'what day is' in command:
        reg_ex = re.search('what day is (.*)', command)
        try:
            if reg_ex:
                dt = reg_ex.group(1)
                time_format = datetime.datetime.strptime(dt, '%d %B %Y')
                tf = datetime.datetime.strftime(time_format, '%d/%-m/%Y')
                day, month, year = (int(x) for x in tf.split('/'))    
                ans = datetime.date(year, month, day)
                IvyResponse(' It is ' + ans.strftime("%A") + ' on ' + dt)
        except Exception as e:
                now = datetime.datetime.now()
                format_day = '%A %d %B, %Y'
                IvyResponse('Today is ' + now.strftime(format_day))
    
    #open application
    elif 'launch' in command:
        reg_ex = re.search('launch\s(.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)
        IvyResponse("I have launch the application as you wanted, No thanks needed!")
    
    #Using wolframalpha to calculate, tell weather in a specific city + specific day.
    elif 'calculate' in command:
        app_id = "PUK3TX-59QXTTY2EY"
        client = wolframalpha.Client(app_id)
        indx = command.lower().split().index('calculate')
        query = command.split()[indx +1:]
        res = client.query(' '.join(query))
        answer = next(res.results).text
        IvyResponse("The answer is " + answer)
        return
    elif 'information' in command:
        IvyResponse('What do you need to know, ' + name + '?')
        ans = myCommand()
        if 'specific' in str(ans) or 'temperature' in str(ans):
            IvyResponse("Where to, sir?")
            temp_location = myCommand()
            IvyResponse('Which day?')
            temp_time = myCommand()
            IvyResponse('On it! Give me a sec')
            app_id = "PUK3TX-59QXTTY2EY"
            client = wolframalpha.Client(app_id)
            res = client.query('temperture in ' + temp_location + ' on ' + temp_time)
            answer = next(res.results).text
            IvyResponse("It is " + answer)
        else:
            pass
Beispiel #2
0
class weather_report:
    def __init__(self, api_key=None):
        self.weather_condition_templates = {
            "precipitation": {
                "chance": " there is a %s per cent chance of precipitation ",
                "snow": "with a possible % inches of snow "
            },
            "hi_lo": {
                "general":
                " with a high of %s degrees and a low of %s degree celsius",
                "average": " an average temperature of %s degree celsius"
            },
            "conditions": {
                "general": "will be %s",
                "general_hr": "The weather %s will be %s"
            }
        }
        if api_key is None:
            self.api_key = "b09681fb4107467b9563c75a73f1a4a1"
        self.api = Api(self.api_key)

    def query_weather(self, location):
        forecast = self.api.get_forecast(city=location)
        return forecast

    def resolve_time_diff(self, time_delta):
        time_tokens = time_delta.__str__().split(",")
        dd = 0
        hh_mm_ss = time_tokens[0]
        if len(time_tokens) > 1:
            dd = int(time_tokens[0].split(" ")[0])
            hh_mm_ss = time_tokens[1]
        time_split = hh_mm_ss.split(":")
        hh = int(time_split[0])
        return dd, hh

    def get_weather_report(self, location, query_time):
        assert query_time > datetime.datetime.now()
        dd, hh = self.resolve_time_diff(query_time - datetime.datetime.now())

        self.api.set_forecast_granularity('daily')
        dailyForecastPoints = self.query_weather(location).get_series(
            ['datetime', 'weather', 'max_temp', 'min_temp', 'precip'])
        self.api.set_forecast_granularity('3hourly')
        hourlyForecastPoints = self.query_weather(location).get_series(
            ['datetime', 'weather', 'temp', 'precip', 'snow', 'rh'])

        day_forecast_point = dd
        hour_forecast_point = dd * 8 + (hh // 3)
        day_weather = dailyForecastPoints[day_forecast_point]
        hour_weather = hourlyForecastPoints[hour_forecast_point]

        date_term = "today"
        hour_term = " around " + str(hh) + " hours from now"
        if dd > 0:
            date_term = "on " + str(query_time.day) + " " + str(
                query_time.month)

        day_report = self.weather_condition_templates["conditions"][
            "general"] % (day_weather["weather"]["description"])
        day_report += ". " + self.weather_condition_templates["hi_lo"][
            "general"] % (str(
                day_weather["max_temp"]), str(day_weather["min_temp"]))
        day_report += ". And " + self.weather_condition_templates[
            "precipitation"]["chance"] % (str(day_weather["precip"]))
        hour_report = self.weather_condition_templates["conditions"][
            "general_hr"] % (hour_term, hour_weather["weather"]["description"])
        hour_report += ". With " + self.weather_condition_templates["hi_lo"][
            "average"] % (str(hour_weather["temp"]))
        hour_report += ". And " + self.weather_condition_templates[
            "precipitation"]["chance"] % (str(day_weather["precip"]))

        return day_report, hour_report


# wr = weather_report()
# day_rep, hr_rep = wr.get_weather_report("Washington", datetime.datetime(2018, 4, 14, 0, 0))
# text_to_speech(day_rep + ". " + hr_rep)
# print(day_rep + ". " + hr_rep)
Beispiel #3
0
# get datetime column from date and period by mapping time and period with "df_map_HH_Period"
# plt.scatter(x = df_train['pred.GradBoostRegr'], y = df_train['dmd_coeff'])

###################################################################################################################################################
################
#### Step 5 ####
################
from weatherbit.api import Api  # pip install pyweatherbit
api_call = Api(key_API_WeatherFct)
api_call.set_granularity('daily')  # 'hourly', '3hourly'
df_weather_Fct = pd.DataFrame()
for iCity in list_cities:
    print('{}: Downloading Weather Forecast for {}'.format(
        ddt.now().strftime('%d%b%Y %H:%M:%S:'), iCity))
    tmp_df_weather_fct = pd.DataFrame(
        api_call.get_forecast(city=iCity, country='GB').get_series(
            ['temp', 'max_temp', 'min_temp', 'precip']))
    tmp_df_weather_fct['City'] = iCity
    df_weather_Fct = df_weather_Fct.append(tmp_df_weather_fct)
# simple daily average; more accurate would be to have a population- or other-weighted average temperature; other measure for wind speed
df_weather_Fct_avg = df_weather_Fct[[
    'datetime', 'temp'
]].groupby('datetime').mean().reset_index()
df_weather_Fct_avg['date'], df_weather_Fct_avg['time'] = df_weather_Fct_avg[
    'datetime'].dt.date, df_weather_Fct_avg['datetime'].dt.time
df_weather_Fct_avg.rename(columns={'temp': 'tmpc'}, inplace=True)
################
#### Step 6 ####
################
#### Step 6A ###
# DA Forecast Demand from NG; get dmd_coeff and dmd_pk; rename columns
print('{}: Downloading DA Peak Demand and processing'.format(
import time
import calendar

sense = SenseHat()

e = (0, 0, 0)  # empty
o = (255, 128, 0)  # orange
w = (200, 200, 200)  # white
r = (255, 51, 51)  # red
db = (0, 128, 255)  # deep_blue
dg = (96, 96, 96)  # deep_grey

api_key = credentials.weatherbit_api_key
api = Api(api_key)
api.set_granularity('daily')
forecast_Rbg = api.get_forecast(city="Regensburg,DE")
forecast_Ingl = api.get_forecast(city="Ingolstadt,DE")


class Display_Weekdays:
    def __init__(self):
        my_date = date.today()
        self.weekday = calendar.day_name[my_date.weekday()]

    def display_weekday_shortcut(self):
        weekday_shortcut = ((self.weekday)[0:3]).upper()
        sense.show_message(weekday_shortcut)


class Get_Weather:
    def __init__(self):
Beispiel #5
0
class weatherbit(awp): 
  def __init__(self, location, listOfTimePredictions) :
    self.name = "weatherbit"
    self.allowedTimePredictions = "N-N-0"
    
    super(weatherbit, self).__init__(self.name, listOfTimePredictions)

    self.login()
    self.setLocation(location)

  def login(self):
    if self.login_data["apikey"] :
      self.api = Api(self.login_data["apikey"])

    else :
      warnings.warn('MWP_WARNING. The "%s" Weather Package(WP) has not been \
properly activated due to the apikey' % (self.name.upper()))
   
  def setLocation(self,location):
    self.forecast = self.api.get_forecast(lat=location[0],lon=location[1])
  
  def update(self,days=["ALL"]) :
    listOfTimePredictions = self.WD.keys()
    
    for api_periods in self.weather.keys() :
      if api_periods    == "daily" :
        self.api.set_granularity('daily')
        self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd'])
      elif api_periods  == "hourly" :
        self.api.set_granularity('hourly')
        self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd'])
      elif api_periods  == "currently" :
        self.api.set_granularity('hourly')
        self.weather[api_periods] = self.forecast.get_series(['temp','precip','rh','wind_spd'])[0]

    for timePrediction in listOfTimePredictions :
      self.setTemperature(timePrediction)
      self.setWindVelocity(timePrediction)
      self.setRainProbability(timePrediction)
      self.setRainIntensity(timePrediction)
      self.setRelativeHumidity(timePrediction)

  def setTemperature(self,timePrediction="0-0-0"):
    #Units: ºC
    value = self.setWeatherProperty(timePrediction,'temp') 
    self.WD[timePrediction]["Temperature"] = value

  def setWindVelocity(self,timePrediction="0-0-0"):
    #Units: m/s
    value = self.setWeatherProperty(timePrediction,'wind_spd') 
    self.WD[timePrediction]["WindVelocity"] = value

  def setRainProbability(self,timePrediction="0-0-0"):
    #Units: Percentatge [0-1]
    #Warning: Weatherbit does not calculate Weather Prediction
    self.WD[timePrediction]["RainProbability"] = None

  def setRainIntensity(self,timePrediction="0-0-0"):
    #Units: mm/hour
    value = self.setWeatherProperty(timePrediction,'precip') 
    self.WD[timePrediction]["RainIntensity"] = value

  def setRelativeHumidity(self,timePrediction="0-0-0"):
    #Units: Percentatge [0-1]
    value = self.setWeatherProperty(timePrediction,'rh') 
    self.WD[timePrediction]["RelativeHumidity"] = value/100.0 if value else value

  def setWeatherProperty(self,timePrediction,WP) :
    value = None
    day, hour, minute, predictionType = decomposeTimePrediction(timePrediction)

    try :
      if day :
        value = self.weather[predictionType][day][WP]
      elif hour : # N hours
        value = self.weather[predictionType][hour][WP]
      elif not day  and \
           not hour and \
           not minute :
        value = self.weather[predictionType][WP]
    except :
      print("WP[%s]: \"%s\" is not available for \"%s\" prediction. " % (self.name,WP,predictionType))

    return value
Beispiel #6
0
    elif (temperature < 45):
        return "8"
    elif (temperature < 50):
        return "9"
    elif (temperature < 55):
        return "A"
    elif (temperature < 60):
        return "B"
    elif (temperature < 65):
        return "C"
    elif (temperature < 70):
        return "D"
    elif (temperature < 75):
        return "D"
    elif (temperature < 80):
        return "F"


api_key = "388a906c36084818ba4688a859cabee1"
api = Api(api_key)
key_values = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C",
              "D", "E", "F")
rtn_key = ""
for i in range(0, 32):
    lat = random.randrange(-90, 90)
    lon = random.randrange(-180, 80)
    forecast = api.get_forecast(lat=lat, lon=lon)
    temp = forecast.get_series(['temp'])[0]['temp']
    rtn_key += temp_map(temp)
print(rtn_key)
lon = -125.75

api = Api(api_key)

# Set the granularity of the API - Options: ['daily','hourly','3hourly']
# Will only affect forecast requests.
api.set_granularity('daily')

# Query by lat/lon
# forecast = api.get_forecast(lat=lat, lon=lon)

# You can also query by city:
# forecast = api.get_forecast(city="Raleigh,NC")

# Or City, state, and country:
forecast = api.get_forecast(city="Raleigh", state="North Carolina",
                           country="US")

# To get a daily forecast of temperature, and precipitation:
print(forecast.get_series(['temp', 'precip']))

# Get daily history by lat/lon:
api.set_granularity('daily')
history = api.get_history(lat=lat, lon=lon, start_date='2018-02-01',
                          end_date='2018-02-02')

# To get a daily time series of temperature, precipitation, and rh:
print(history.get_series(['precip', 'temp', 'rh']))

# Get hourly history by lat/lon
api.set_granularity('hourly')
history = api.get_history(lat=lat, lon=lon, start_date='2018-02-01',