Esempio n. 1
0
def handle_read(text, mic, profile):
    mic.say(random.choice([
        "I am contacting Apple. Please stand by.",
        "Opening that file. Please wait."
    ]))
    api = app_utils.iCloud(profile)
    rem = api.reminders
    listname = find_list(text, profile, rem)
    if not listname:
        mic.say(random.choice([
            "I'm sorry, I couldn't find that list",
            "That list does not seem to be availble. Please check!"
        ]))
        return

    service = DateService()
    ans = random.choice([
        "I've found the following entries: ",
        "Your " + listname + " list contains ",
        "These are the entries of the " + listname + " list "
    ])
    for i in range(len(rem.lists[listname])):
        reminder = rem.lists[listname][i]
        ans += str(i+1) + ') ' + reminder['title']
        if reminder['due']:
            ans += ', due at ' + service.convertTime(reminder['due'])
        ans += '.'

    ans += random.choice([
        "",
        "That's it.",
        "There is nothing else on your list."
    ])
    mic.say(ans)
Esempio n. 2
0
def handle(text, mic, profile):

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    root = Tk()
    root.wm_title("Mirror")
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.overrideredirect(1)
    root.geometry("%dx%d+0+0" % (w, h))
    root.focus_set()
    root.bind("1", root.quit())
    root.config(background="#000000")

    mainFrame = Frame(root, width=w, height=h)
    mainFrame.grid(row=0, column=0, padx=10, pady=2)
    mainFrame.config(background="#000000")
    customFont = tkFont.Font(family="Helvetica", size=60)

    timeVar = StringVar()
    timeVar.set(response)
    weatherVar = StringVar()
    weatherVar.set("76°")
    timeLabel = Label(mainFrame, textvariable=timeVar, font=customFont, fg="white", bg="black")
    weatherLabel = Label(mainFrame, textvariable=weatherVar, font=customFont, fg="white", bg="black")
    timeLabel.place(relx=1, x=-2, y=2, anchor=NE)
    weatherLabel.place(relx=0, x=-2, y=2, anchor=NW)
    root.mainloop()
Esempio n. 3
0
def handle(text, mic, profile):

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    mic.say("It is %s right now." % response)
Esempio n. 4
0
def handle(text, mic, profile):

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    mic.say("It is %s right now." % response)
Esempio n. 5
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the relevant weather for the requested date (typically, weather
        information will not be available for days beyond tomorrow).

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    if not profile['location']:
        mic.say(
            "I'm sorry, I can't seem to access that information. Please make sure that you've set your location on the dashboard.")
        return

    tz = getTimezone(profile)

    service = DateService(tz=tz)
    date = service.parseDay(text)
    if not date:
        date = datetime.datetime.now(tz=tz)
    weekday = service.__daysOfWeek__[date.weekday()]

    if date.weekday() == datetime.datetime.now(tz=tz).weekday():
        date_keyword = "Today"
    elif date.weekday() == (
            datetime.datetime.now(tz=tz).weekday() + 1) % 7:
        date_keyword = "Tomorrow"
    else:
        date_keyword = "On " + weekday

    forecast = getForecast(profile)

    output = None

    for entry in forecast:
        try:
            date_desc = entry['title'].split()[0].strip().lower()

            weather_desc = entry['summary'].split('-')[1]

            if weekday == date_desc:
                output = date_keyword + \
                    ", the weather will be" + weather_desc + "."
                break
        except:
            continue

    if output:
        output = replaceAcronyms(output)
        mic.say(output)
    else:
        mic.say(
            "I'm sorry. I can't see that far ahead.")
Esempio n. 6
0
def handle(mic):
    c=datetime.datetime.now()
    con = mdb.connect('localhost', 'root', 'whyte', 'jarvis')
    cur=con.cursor()
    cur.execute("select * from notif where date > '"+str(c)+"' order by date limit 5")
    temp=cur.fetchall()
    service = DateService()
    
    for item in temp:
    	time = service.convertTime(item[2])
    	mic.say(str(item[1])+" on "+str(time))
    con.close()
Esempio n. 7
0
def handle(text, sender, receiver, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    sender.say("It is %s right now." % response)
Esempio n. 8
0
    def handle(self, text, teller, mic, profile):
        """
            Reports the current time based on the user's timezone.

            Arguments:
            text -- user-input, typically transcribed speech
            mic -- used to interact with the user (input)
            profile -- contains information related to the user (e.g., phone number)
        """

        tz = getTimezone(profile)
        now = datetime.datetime.now(tz=tz)
        service = DateService()
        response = service.convertTime(now)
        teller.say("Il est %s." % response)
Esempio n. 9
0
def handle(text, mic, profile, house):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    mic.say("It is %s right now." % response)
Esempio n. 10
0
def handle(text, mic, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    try:
        weather_client = yweather.Client()
        weather = weather_client.fetch_weather(profile["location"]["id"], metric=True)

        tz = getTimezone(profile)
        service = DateService(tz=tz)
        date = service.extractDate(text)
        if not date:
            date = datetime.datetime.now(tz=tz)

        weekday = service.__daysOfWeek__[date.weekday()]

        if date.weekday() == datetime.datetime.now(tz=tz).weekday():
            mic.say(
                ("Today, %s at %s degrees with wind speed" + " of %.1f metres per second")
                % (code2desc(weather["condition"]), weather["condition"]["temp"], float(weather["wind"]["speed"]) / 3.6)
            )
            return

        elif date.weekday() == (datetime.datetime.now(tz=tz).weekday() + 1) % 7:
            date_keyword = "Tomorrow"
        else:
            date_keyword = "On " + weekday

        weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
        for fore in weather["forecast"]:
            if weekdays[date.weekday()] == fore["day"]:
                mic.say(
                    ("%s, %s with temperatures raging" + " from %s to %s degrees")
                    % (date_keyword, code2desc(fore), fore["low"], fore["high"])
                )
                break
        else:
            mic.say("I'm sorry. I can't see that far ahead.")
    except:
        mic.say("I'm sorry. I can't see that far ahead.")
Esempio n. 11
0
def handle(text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    #cluetext = " Listen very carefully to the next clue:     The letter P is the start of its name.     The letter R is the end.      It runs at night  but never goes anywhere.     Look inside "
    mic.say("It is %s right now." % response)
Esempio n. 12
0
def handle(text):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = utils.getTimezone(cmInstance.getConfig("timezone"))
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    return _("Now it is %s") % response
Esempio n. 13
0
def handle(text, mic, profile):
    """
        Reports the current date based on the user's location.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    day = (time.strftime("%A")) 
    month = (time.strftime("%B"))   
    num_day = (time.strftime("%d"))  
    message = "It is " + day + "the " + num_day + "today, get over karishma" 
    mic.say(message)
Esempio n. 14
0
def handle(text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    d = datetime.datetime.strptime(response, "%I:%M %p")
    response = d.strftime("%H:%M")
    response = re.sub(r'00:', 'minuit ', response)
    response = re.sub(r'12:', 'midi ', response)
    mic.say("Il est %s." % response)
Esempio n. 15
0
def handle(text, mic, profile, wxbot=None):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
        wxBot -- wechat robot
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    if "AM" in response:
        response = u"上午" + response.replace("AM", "")
    elif "PM" in response:
        response = u"下午" + response.replace("PM", "")
    mic.say(u"现在时间是 %s " % response)
Esempio n. 16
0
def handle(text, mic, profile, wxbot=None):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
        wxBot -- wechat robot
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)
    if "AM" in response:
        response = u"上午" + response.replace("AM", "")
    elif "PM" in response:
        response = u"下午" + response.replace("PM", "")
    mic.say(u"现在时间是 %s " % response)
Esempio n. 17
0
def handle(text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)

    comment = ''
    print("Current hour is " + str(now.hour))
    if now.hour > 19:
        comment = ' It is time to be sleeping.'
    mic.say("It is {0} right now. {1}".format(response, comment) )
Esempio n. 18
0
def handle(self, text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    tz = getTimezone(profile)
    now = datetime.datetime.now(tz=tz)
    service = DateService()
    response = service.convertTime(now)

    self.blittxt(response, 150, white, black)


    
    mic.say("It is %s right now master." % response)
    time.sleep(1)    
Esempio n. 19
0
    def handleHourNotifications(self, nextHour):
        """Announces the time of day
        At each hour annoice the time of day.   
        We need ensure Nexthour occurs at a given hour interval.
        Then test for the next hour change within one hour of last date.
        get the hour now
        determine if time now matches the next hour
        if it is then put a notification onto the queue
        set the next hour increase by one or if 23 then set to 24.
        """
        # get the current time
        tz = getTimezone(self.profile)
        now = datetime.datetime.now(tz=tz)

        #	test to see if this is the first time running the program
        if nextHour == None:
            # set the next hour
            min = now.minute
            sec = now.second
            mic = now.microsecond
            nextHour = now + datetime.timedelta(
                hours=1, seconds=-sec, minutes=-min, microseconds=-mic)

        if now > nextHour:
            service = DateService()
            response = service.convertTime(nextHour)
            styleHour = "It is " + response + " right now."
            self.q.put(styleHour)
            # reset the next hour
            min = now.minute
            sec = now.second
            mic = now.microsecond
            nextHour = now + datetime.timedelta(
                hours=1, seconds=-sec, minutes=-min, microseconds=-mic)

        print(nextHour)
        print("inside the Hour Notification routine")
        return nextHour
Esempio n. 20
0
def _handle(mic, profile):
    """
    Reports the current time based on the user's timezone.

    Arguments:
    mic
      used to interact with the user (for both input and output)

    profile
      contains information related to the user (e.g., phone number)
    """

    now = datetime.datetime.now(tz=get_timezone(profile))
    mic.say("It is {0} right now.".format(DateService().convertTime(now)))
Esempio n. 21
0
  def task(self):
    self.tz = getTimezone(self.profile)
    self.now = datetime.datetime.now(tz=self.tz)
    self.service = DateService()
    self.response = self.service.convertTime(self.now)
    self.timeVar.set(self.response)
    self.numFiles = len([name for name in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, name))])
    if self.numFiles > self.numFileHolder:
      self.showPicture()
      print ("OLD: " + str(self.numFileHolder) + "NEW: " + str(self.numFiles))
      self.numFileHolder = self.numFiles
    self.forecast = None
    if 'wmo_id' in self.profile:
      self.forecast = get_forcast_by_wmo_id(str(self.profile['wmo_id']))
    elif 'location' in self.profile:
      self.forecast = get_forecast_by_name(str(self.profile['location']))

    self.temp = self.forecast[0]['summary_detail']['value'][13:17] + unichr(176)
    self.weatherVar.set(self.temp) 
    self.root.after(2000, self.task)
Esempio n. 22
0
def get_time_windows(entities, profile):
    ds = DateService()
    windows = []
    if u'datetime' in entities:
        parsed_dates = entities.get(u'datetime')
        for date in parsed_dates:
            if date[u'type'] == u'value':
                start_time = dtutil.datetime_from_string(date[u'value'])
                delta = date[u'grain'] + u's' #wit returns singular names of intervals
                end_time = start_time + datetime.timedelta(**{delta: 1})
            elif date[u'type'] == u'interval':
                start_time = dtutil.datetime_from_string(date[u'from'][u'value'])
                end_time = dtutil.datetime_from_string(date[u'to'][u'value'])
            windows.append((start_time, end_time))
    #Need to support looking up commute windows from the profile
    else:
        start_time = datetime.datetime.combine(datetime.datetime.now(), datetime.time())
        end_time = start_time + datetime.timedelta(days=1)
        windows.append((start_time, end_time))
    return windows
Esempio n. 23
0
 def compareTimes(self, input, targets):
     service = DateService()
     results = service.extractDates(input)
     for (result, target) in zip(results, targets):
         self.assertEqual(target.time(), result.time())
Esempio n. 24
0
 def compareTimes(self, input, targets):
     service = DateService()
     results = service.extractDates(input)
     for (result, target) in zip(results, targets):
         self.assertEqual(result.hour, target.hour)
         self.assertEqual(result.minute, target.minute)
Esempio n. 25
0
 def compareDate(self, input, target):
     service = DateService()
     result = service.extractDate(input)
     self.assertEqual(result.month, target.month)
     self.assertEqual(result.day, target.day)
Esempio n. 26
0
 def compareTime(self, input, target):
     service = DateService()
     result = service.extractDate(input)
     self.assertEqual(result.hour, target.hour)
     self.assertEqual(result.minute, target.minute)
Esempio n. 27
0
 def compareDates(self, input, targets):
     service = DateService()
     results = service.extractDates(input)
     for (result, target) in zip(results, targets):
         self.assertEqual(result.month, target.month)
         self.assertEqual(result.day, target.day)
Esempio n. 28
0
def handle(mic):

    now = datetime.datetime.now()
    service = DateService()
    response = service.convertTime(now)
    mic.say("It is %s right now." % response)
import spacy

nlp = spacy.load('en_core_web_sm')

from semantic.numbers import NumberService
from semantic.dates import DateService

number_service = NumberService()
date_service = DateService()
# print("Time now : ", date_service.extractTime("3 o clock"))


def named_entity_extraction(text):
    doc = nlp(text)

    entity = []
    for ent in doc.ents:
        # print("Iterating : ", ent)

        if ent.label_ == 'ORG':
            name = ent.text
            description = "organization"
        elif ent.label_ == 'GPE':
            name = ent.text
            description = "geopolitical area"
        elif ent.label_ == 'MONEY':
            name = ent.text
            description = "monetary value"
        elif ent.label_ == 'PERSON':
            name = ent.text
            description = "public figure"
Esempio n. 30
0
def handle(mic):
    
    now = datetime.datetime.now()
    service = DateService()
    response = service.convertTime(now)
    mic.say("It is %s right now." % response)
Esempio n. 31
0
 def compareTime(self, inp, target):
     service = DateService()
     result = service.extractDate(inp)
     self.assertEqual(result.hour, target.hour)
     self.assertEqual(result.minute, target.minute)
Esempio n. 32
0
 def compareTimes(self, input, targets):
     service = DateService()
     results = service.extractDates(input)
     for (result, target) in zip(results, targets):
         self.assertEqual(target.time(), result.time())
Esempio n. 33
0
class GUI(threading.Thread):

  def __init__(self):

    self.profile_path = jasperpath.config('profile.yml')
    if os.path.exists(self.profile_path):
      with open(self.profile_path, 'r') as f:
        self.profile = yaml.safe_load(f)

    threading.Thread.__init__(self)
    self.start()

  def callback(self):
    self.root.quit()

  def task(self):
    self.tz = getTimezone(self.profile)
    self.now = datetime.datetime.now(tz=self.tz)
    self.service = DateService()
    self.response = self.service.convertTime(self.now)
    self.timeVar.set(self.response)
    self.numFiles = len([name for name in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, name))])
    if self.numFiles > self.numFileHolder:
      self.showPicture()
      print ("OLD: " + str(self.numFileHolder) + "NEW: " + str(self.numFiles))
      self.numFileHolder = self.numFiles
    self.forecast = None
    if 'wmo_id' in self.profile:
      self.forecast = get_forcast_by_wmo_id(str(self.profile['wmo_id']))
    elif 'location' in self.profile:
      self.forecast = get_forecast_by_name(str(self.profile['location']))

    self.temp = self.forecast[0]['summary_detail']['value'][13:17] + unichr(176)
    self.weatherVar.set(self.temp) 
    self.root.after(2000, self.task)
  def showPicture(self):
    self.newest = max(glob.iglob('Pictures/*.jpg'), key = os.path.getctime)
    print ("NEWEST: " + self.newest)
    self.photo = ImageTk.PhotoImage(Image.open(self.newest))
    self.x = self.canvas.create_image(self.w/2, self.h/2, image=self.photo)
    self.canvas.itemconfigure(self.x, state=NORMAL)
    self.canvas.update_idletasks()
    time.sleep(3)
    self.canvas.itemconfigure(self.x, state=HIDDEN)
  def run(self):

    self.root = Tk()
    self.root.protocol("WM_DELETE_WINDOW", self.callback)
    self.w, self.h = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
    #self.w, self.h = 500, 500
    self.root.overrideredirect(1)
    self.root.geometry("%dx%d+0+0" % (self.w, self.h))
    self.root.focus_set()
    self.root.bind("1", self.root.quit())
    self.root.config(background = "#000000")

    mainFrame = Frame(self.root, width=self.w, height=self.h)
    mainFrame.grid(row=0, column=0, padx=10, pady=2)
    mainFrame.config(background= "#000000")
    customFont = tkFont.Font(family="Helvetica", size=60)
    self.timeVar = StringVar()
    self.weatherVar = StringVar()
    self.canvas = Canvas(mainFrame, width=1080, height=1920, highlightthickness=0)
    timeLabel = Label(mainFrame, textvariable=self.timeVar, font=customFont, fg="white", bg="black")
    weatherLabel = Label(mainFrame, textvariable=self.weatherVar, font=customFont, fg="white", bg="black")
 
    self.canvas.config(background="#000000")
    self.canvas.place(relx=0.5, rely=0.5, anchor=CENTER)
    self.directory = '/home/pi/jasper/Pictures'
    self.numFileHolder = len([name for name in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, name))])
    print "NUMFILEHOLDER: " + str(self.numFileHolder)
    timeLabel.place(relx=1, x=-2, y=2, anchor=NE)
    weatherLabel.place(relx=0, x=-2, y=2, anchor=NW)
    self.root.after(2000, self.task)
    self.root.mainloop()
def handle(self, text, mic, profile):
    """
        Reports the current time based on the user's timezone.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    mic.say("clock mode on")
    done = False
    while done == False:

        t = (time.strftime("%m/%d/%Y"))
        a, b, c = t.split('/')

        if a == '01':
            a = 'January'

        if a == '02':
            a = 'February'

        if a == '03':
            a = 'March'

        if a == '04':
            a = 'April'

        if a == '05':
            a = 'May'

        if a == '06':
            a = 'June'

        if a == '07':
            a = 'July'

        if a == '08':
            a = 'August'

        if a == '09':
            a = 'September'

        if a == '10':
            a = 'October'

        if a == '11':
            a = 'November'

        if a == '12':
            a = 'December'

        d, e = b
        if d == '0':
            b = e

        date = ('%s %s %s' % (a, b, c))

        self.background.fill(black)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                done = True
        tz = getTimezone(profile)
        now = datetime.datetime.now(tz=tz)
        service = DateService()
        response = service.convertTime(now)
        self.pygm.blitjtxt(response, 150, 0, 240, 160, white)
        self.pygm.blitjtxt(date, 40, 0, 240, 220, white)

        pygame.display.flip()
        time.sleep(1)
Esempio n. 35
0
#https://pypi.org/project/semantic/
##create virtual env for package installation
#virtualenv semanticenv
##deactivate the existing virtual env
##activate the virtual env
#semanticenv\Scripts\activate

#pip install semantic

from semantic.dates import DateService

from semantic.dates import DateService

service = DateService()
date = service.extractDate("On March 3 at 12:15pm...")

#---------------------------------------------------
#this fails
# from semantic.solver import ConversionService
# service = ConversionService()
# print (service.convert("Seven and a half kilograms to pounds"))
# print (service.convert("Seven and a half pounds per square foot to kilograms per meter squared"))

#--------------
from semantic.numbers import NumberService

service = NumberService()
print(service.parse("Two hundred and six"))
# 206
print(service.parse("Five point one five"))
# 5.15
Esempio n. 36
0
 def compareDate(self, input, target):
     service = DateService()
     result = service.extractDate(input)
     self.assertEqual(target, result)
Esempio n. 37
0
from semantic.dates import DateService

service = DateService()
date = service.extractDate("On March 3 at 12:15pm...")
print(date)
Esempio n. 38
0
def handle(text, speaker, requester, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
		speaker -- used to interact with the user (output)
        requester -- used to interact with the user (input)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    forecast = None
    if 'wmo_id' in profile:
        forecast = get_forecast_by_wmo_id(str(profile['wmo_id']))
    elif 'location' in profile:
        forecast = get_forecast_by_name(str(profile['location']))

    if not forecast:
        speaker.clean_and_say("I'm sorry, I can't seem to access that information. Please " +
                "make sure that you've set your location on the dashboard.")
        return

    tz = getTimezone(profile)

    service = DateService(tz=tz)
    date = service.extractDay(text)
    if not date:
        date = datetime.datetime.now(tz=tz)
    weekday = service.__daysOfWeek__[date.weekday()]

    if date.weekday() == datetime.datetime.now(tz=tz).weekday():
        date_keyword = "Today"
    elif date.weekday() == (
            datetime.datetime.now(tz=tz).weekday() + 1) % 7:
        date_keyword = "Tomorrow"
    else:
        date_keyword = "On " + weekday

    output = None

    for entry in forecast:
        try:
            date_desc = entry['title'].split()[0].strip().lower()
            if date_desc == 'forecast':
                # For global forecasts
                date_desc = entry['title'].split()[2].strip().lower()
                weather_desc = entry['summary']
            elif date_desc == 'current':
                # For first item of global forecasts
                continue
            else:
                # US forecasts
                weather_desc = entry['summary'].split('-')[1]

            if weekday == date_desc:
                output = date_keyword + \
                    ", the weather will be " + weather_desc + "."
                break
        except:
            continue

    if output:
        output = replaceAcronyms(output)
        speaker.clean_and_say(output)
    else:
        speaker.clean_and_say(
            "I'm sorry. I can't see that far ahead.")
Esempio n. 39
0
def handle(text, mic, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    logger = logging.getLogger(__name__)
    logger.debug(text)
    logger.debug("location=" + str(profile['location']))
    forecast = None
    if 'location' in profile:
        forecast = get_forecast_by_name(str(profile['location']))

    if not forecast:
        mic.say(
            "I'm sorry, I can't seem to access weather information right now.")
        # mic.say("Please make sure that you've set your location on the dashboard.")
        return

    # tz = getTimezone(profile)
    # logger.debug(tz)

    date_keyword = 'all'
    for word in text.split():
        logger.debug('word=' + word)
        if word != "WEATHER" and word in WORDS:
            date_keyword = word.lower()

    matchThese = []
    tz = getTimezone(profile)
    service = DateService(tz=tz)
    today_wkday = datetime.datetime.now(tz=tz).weekday()
    today = service.__daysOfWeek__[today_wkday]
    if date_keyword == 'tomorrow':
        tomorrow_wkday = (today_wkday + 1) % 7
        date_keyword = service.__daysOfWeek__[tomorrow_wkday]

    logger.debug("date_keyword=" + date_keyword)

    if date_keyword != '':
        matchThese.append(date_keyword)

    if date_keyword == 'today':
        matchThese.append('current')
        matchThese.append('rest')
        matchThese.append('this')
        # matchThese.append('tonight')

    for entry in matchThese:
        logger.debug('match=' + entry)

    for entry in forecast:
        date_desc = entry['title'].split()[0].strip().lower()
        logger.debug('[' + date_desc + ']: title=' + str(entry['title']))

    # logger.debug(forecast)
    for entry in forecast:
        sayThis = ''
        date_desc = entry['title'].split()[0].strip().lower()
        if (date_desc in matchThese) or (date_keyword == 'all'):
            if date_desc == 'current':
                sayThis = str(entry['title'])
            else:
                sayThis = str(entry['summary'])

        if sayThis != '':
            mic.say(sayThis)
    return
Esempio n. 40
0
 def compareDate(self, input, target):
     service = DateService()
     result = service.extractDate(input)
     self.assertEqual(target, result)
Esempio n. 41
0
 def compareDates(self, inp, targets):
     service = DateService()
     results = service.extractDates(inp)
     for (result, target) in zip(results, targets):
         self.assertEqual(result.month, target.month)
         self.assertEqual(result.day, target.day)
Esempio n. 42
0
 def testIllegalDate(self):
     input = "I have a meeting on February 29 at 12:15pm"
     self.assertRaises(ValueError, lambda: DateService().extractDate(input))
Esempio n. 43
0
def handle(text, mic, profile, logger, modules):
    """
        Responds to user-input, typically speech text, with a summary of
        the relevant weather for the requested date (typically, weather
        information will not be available for days beyond tomorrow).

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    if not profile['location']:
        mic.say(
            "Wybacz, ale nie mogę podać prognozy pogody. Wprowadź proszę w ustawieniach miasto.")
        return
    mic.say("Pobieram prognozę pogody...")
    #str_formater.checkFormat(text, logger)
    text = str_formater.unicodeToUTF8(text, logger)
    tz = getTimezone(profile)

    service = DateService(tz=tz)
    loc = arrow.locales.get_locale('pl')
    #loc.day_name(1).lower()

    #date = service.extractDay(text)
    #if not date:
    dow = parseDayOfWeek(text.lower(), logger)
    if dow:
      now_dow = arrow.utcnow().weekday()
      if dow > now_dow:
        date = arrow.utcnow().replace(days=dow - now_dow)
      else:
        date = arrow.utcnow().replace(days=dow - now_dow + 7)
    if 'dzisiaj' in text.lower():
      date = arrow.utcnow()
    elif 'jutro' in text.lower():
      date = arrow.utcnow().replace(days=+1)
    elif 'pojutrze' in text.lower():
      date = arrow.utcnow().replace(days=+2)
    else:
      date = arrow.utcnow()

    weekday = loc.day_name(date.weekday()+1).lower()
    weekday = str_formater.unicodeToUTF8(weekday, logger).replace('Ś','ś')
    

    if date.weekday() == arrow.utcnow().weekday():
        date_keyword = "dzisiaj"
    elif date.weekday() == arrow.utcnow().replace(days=+1).weekday():
        date_keyword = "jutro"
    else:
        date_keyword = weekday

    #logger.debug("date_keyword %s weekday %s" % (date_keyword, weekday))
    forecast = getForecast(profile)
    output = ""
    #weekday = 'niedziela'
    
    #for entry in forecast:
    #  print entry['title']
    for entry in forecast:
        try:
            entry = str_formater.unicodeToUTF8(entry, logger)
            #str_formater.checkFormat(entry['title'].split()[0].strip().lower(), logger)
            date_desc = entry['title'].split()[0].strip().lower().replace('Ś','ś')
            #logger.debug('date_desc %s' % date_desc)
            if date_desc == 'prognoza': #For global forecasts
              date_desc = entry['title'].split()[2].strip().lower().replace('Ś','ś')
              #logger.debug('date_desc %s' % date_desc)
              weather_desc = entry['summary_detail']['value']

            elif date_desc == 'obecne': #For first item of global forecasts
                output += "Obecne warunki pogodowe:|" + \
                     parseCurrentConditions(entry['summary_detail']['value']) + "| "
                continue
            else:
              weather_desc = entry['summary_detail']['value'].split('|')[1] #US forecasts

            if weekday == date_desc:
                output += "Prognoza pogody na " + \
                     date_keyword + ',| ' + weather_desc
                break
        except:
            logger.error("error parsing forecast", exc_info=True)

    if output:
        output = replaceAcronyms(output)
        mic.say(output)
    else:
        mic.say(
            "Wybacz, ale brak prognozy")
Esempio n. 44
0
 def compareTimes(self, inp, targets):
     service = DateService()
     results = service.extractDates(inp)
     for (result, target) in zip(results, targets):
         self.assertEqual(result.hour, target.hour)
         self.assertEqual(result.minute, target.minute)
Esempio n. 45
0
def handle(text, mic, profile):
    """
    Responds to user-input, typically speech text, with a summary of
    the relevant weather for the requested date (typically, weather
    information will not be available for days beyond tomorrow).

    Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    if not profile['location']:
        mic.say(
            "I'm sorry, I can't seem to access that information. Please make" +
            "sure that you've set your location on the dashboard.")
        return

    tz = getTimezone(profile)

    service = DateService(tz=tz)
    date = service.extractDay(text)
    if not date:
        date = datetime.datetime.now(tz=tz)
    weekday = service.__daysOfWeek__[date.weekday()]

    if date.weekday() == datetime.datetime.now(tz=tz).weekday():
        date_keyword = "Today"
    elif date.weekday() == (datetime.datetime.now(tz=tz).weekday() + 1) % 7:
        date_keyword = "Tomorrow"
    else:
        date_keyword = "On " + weekday

    forecast = getForecast(profile)

    output = None

    for entry in forecast:
        try:
            date_desc = entry['title'].split()[0].strip().lower()
            if date_desc == 'forecast':
                # For global forecasts
                date_desc = entry['title'].split()[2].strip().lower()
                weather_desc = entry['summary']
            elif date_desc == 'current':
                # For first item of global forecasts
                continue
            else:
                # US forecasts
                weather_desc = entry['summary'].split('-')[1]

            if weekday == date_desc:
                output = date_keyword + \
                    ", the weather will be " + weather_desc + "."
                break
        except:
            continue

    if output:
        output = replaceAcronyms(output)
        mic.say(output)
    else:
        mic.say("I'm sorry. I can't see that far ahead.")
Esempio n. 46
0
 def compareDate(self, inp, target):
     service = DateService()
     result = service.extractDate(inp)
     self.assertEqual(result.month, target.month)
     self.assertEqual(result.day, target.day)