コード例 #1
0
 def test_extract_ambiguous_time_en(self):
     morning = datetime(2017, 6, 27, 8, 1, 2)
     evening = datetime(2017, 6, 27, 20, 1, 2)
     noonish = datetime(2017, 6, 27, 12, 1, 2)
     self.assertEqual(
         extract_datetime('feed fish at 10 o\'clock', morning)[0],
         datetime(2017, 6, 27, 10, 0, 0))
     self.assertEqual(
         extract_datetime('feed fish at 10 o\'clock', noonish)[0],
         datetime(2017, 6, 27, 22, 0, 0))
     self.assertEqual(
         extract_datetime('feed fish at 10 o\'clock', evening)[0],
         datetime(2017, 6, 27, 22, 0, 0))
コード例 #2
0
 def test_extract_ambiguous_time_it(self):
     mattina = datetime(2017, 6, 27, 8, 1, 2)
     sera = datetime(2017, 6, 27, 20, 1, 2)
     mezzogiorno = datetime(2017, 6, 27, 12, 1, 2)
     self.assertEqual(
         extract_datetime('dai da mangiare ai pesci alle 10 in punto',
                          mattina, lang='it-it')[0],
         datetime(2017, 6, 27, 10, 0, 0))
     self.assertEqual(
         extract_datetime('dai da mangiare ai pesci alle 10 in punto',
                          mezzogiorno, lang='it-it')[0],
         datetime(2017, 6, 27, 22, 0, 0))
     self.assertEqual(
         extract_datetime('dai da mangiare ai pesci alle 10 in punto',
                          sera, lang='it-it')[0],
         datetime(2017, 6, 27, 22, 0, 0))
コード例 #3
0
 def test_extractdatetime_default_pt(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime(
         'marca consulta para 2 semanas e 6 dias depois de Sabado',
         anchor, lang='pt-pt', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #4
0
 def test_extract_datetime_relative_failing(self):
     self.assertEqual(
         extract_datetime("mañana",
                          anchorDate=datetime(1998, 1, 1),
                          lang='es')[0], datetime(1998, 1, 2))
コード例 #5
0
 def extractWithFormat(text):
     date = datetime(2017, 06, 27, 00, 00)
     [extractedDate, leftover] = extract_datetime(text, date)
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #6
0
 def extractWithFormat(text):
     date = datetime(2017, 6, 27, 13, 4)  # Tue June 27, 2017 @ 1:04pm
     [extractedDate, leftover] = extract_datetime(text, date)
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #7
0
 def test_extractdatetime_default_it(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime('Come è il meteo 3 tra giorni?',
                            anchor, lang='it-it', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #8
0
 def extractWithFormat_fr(text):
     date = datetime(2017, 6, 27, 0, 0)
     [extractedDate, leftover] = extract_datetime(text, date,
                                                  lang="fr-fr")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #9
0
 def test_extractdatetime_default_it(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime("Come è il meteo 3 tra giorni?",
                            anchor, lang='it-it', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #10
0
    def handle_set_alarm(self, message):
        """Handler for "set an alarm for..."""
        utt = message.data.get('utterance').lower()
        recur = None

        if message.data.get('Recurring'):
            # Just ignoring the 'Recurrence' now, we support more complex stuff
            # recurrence = message.data.get('Recurrence')
            recur = self._create_day_set(utt)
            # TODO: remove days following an "except" in the utt

            while not recur:
                r = self.get_response('query.recurrence', num_retries=1)
                if not r:
                    return
                recur = self._create_day_set(r)

            if self.voc_match(utt, "Except"):
                # TODO: Support exceptions
                self.speak_dialog("no.exceptions.yet")
                return

        # Get the time
        when, utt_no_datetime = extract_datetime(utt, lang=self.lang) or (None, utt)

        # Get name from leftover string from extract_datetime
        name = self._get_alarm_name(utt_no_datetime)

        # Will return dt of unmatched string
        today = extract_datetime(self.texts.get('today'), lang=self.lang)
        today = today[0]

        # Check the time if it's midnight. This is to check if the user
        # said a recurring alarm with only the Day or if the user did
        # specify to set an alarm on midnight. If it's confirmed that
        # it's for a day only, then get another response from the user
        # to clarify what time on that day the recurring alarm is.
        is_midnight = self._check_if_utt_has_midnight(utt,
                                                      when,
                                                      self.threshold)

        if (when is None or when.time() == today.time()) and not is_midnight:
            r = self.get_response('query.for.when', validator=extract_datetime)
            if not r:
                self.speak_dialog("alarm.schedule.cancelled")
                return
            when_temp = extract_datetime(r, lang=self.lang)
            if when_temp is not None:
                when_temp = when_temp[0]
                # TODO add check for midnight
                # is_midnight = self._check_if_utt_has_midnight(r, when_temp,
                #                                               self.threshold)
                when = when_temp if when is None \
                                 else datetime(tzinfo=when.tzinfo,
                                               year=when.year,
                                               month=when.month,
                                               day=when.day,
                                               hour=when_temp.hour,
                                               minute=when_temp.minute)
            else:
                when = None

        # Verify time
        alarm_time = when
        confirmed_time = False
        while (not when or when == today) and not confirmed_time:
            if recur:
                t = nice_time(alarm_time, use_ampm=not self.use_24hour, use_24hour = self.use_24hour)
                conf = self.ask_yesno('confirm.recurring.alarm',
                                      data={
                                          'time': t,
                                          'recurrence': self._recur_desc(recur)
                                      })
            else:
                t = nice_date_time(alarm_time, now=today, use_ampm= not self.use_24hour, use_24hour = self.use_24hour, lang=self.lang)
                conf = self.ask_yesno('confirm.alarm', data={'time': t})
            if not conf:
                return
            if conf == 'yes':
                when = [alarm_time]
                confirmed_time = True
            else:
                # check if a new (corrected) time was given
                when = extract_datetime(conf, lang=self.lang)
                if when is not None:
                    when = when[0]
                if not when or when == today:
                    # Not a confirmation and no date/time in statement, quit
                    return
                alarm_time = when
                when = None  # reverify

        alarm = {}
        if not recur:
            alarm_time_ts = to_utc(alarm_time).timestamp()
            now_ts = now_utc().timestamp()
            if alarm_time_ts > now_ts:
                alarm = self.set_alarm(alarm_time, name)
            else:
                if (self.texts.get('today') in utt) or (self.texts.get('tonight') in utt):
                    self.speak_dialog('alarm.past')
                    return
                else:
                    # Set the alarm to find the next 24 hour time slot
                    while alarm_time_ts < now_ts:
                        alarm_time_ts += 86400.0
                    alarm_time = datetime.utcfromtimestamp(alarm_time_ts)
                    alarm = self.set_alarm(alarm_time, name)
        else:
            alarm = self.set_alarm(alarm_time, name, repeat=recur)

        if not alarm:
            # none set, it was a duplicate
            return

        # Don't want to hide the animation
        self.enclosure.deactivate_mouth_events()
        if confirmed_time:
            self.speak_dialog("alarm.scheduled")
        else:
            t = self._describe(alarm)
            reltime = nice_relative_time(self.get_alarm_local(alarm), lang=self.lang)
            if recur:
                self.speak_dialog("recurring.alarm.scheduled.for.time",
                                  data={"time": t, "rel": reltime})
            else:
                self.speak_dialog("alarm.scheduled.for.time",
                                  data={"time": t, "rel": reltime})

        self._show_alarm_anim(alarm_time)
        self.enclosure.activate_mouth_events()
コード例 #11
0
ファイル: __init__.py プロジェクト: gras64/calendar-skill
    def handle_add_appoint(self, message):
        event = message.data.get("event")
        while not event:
            #We need to get the event
            event = self.get_response("new.event.name")

        utterance = message.data['utterance']
        date, rest = extract_datetime(utterance, datetime.now(), self.lang)
        while rest == normalize(utterance):
            utterance = self.get_response("new.event.date")
            date, rest = extract_datetime(utterance)

        self.log.info(" Calendar skill new event: date: " + str(date) +
                      " event: " + event)
        #ADD EVENT
        server_type = self.check_server()
        if server_type == "Handled":
            return
        elif server_type == True:
            #Home
            server_address = self.settings.get("server_address")
            port = self.settings.get("port")
            username = self.settings.get("username")
            password = self.settings.get("password")
            #start creating a vevent:
            cal = vobject.iCalendar()
            cal.add("vevent")
            #add name
            cal.vevent.add("summary").value = str(event)
            #add date
            cal.vevent.add('dtstart').value = date
            # add it to the calendar
            url = "http://{}:{}@{}:{}/".format(username, password,
                                               server_address, port)
            try:
                client = caldav.DAVClient(url)
                principal = client.principal()

                #Select calendar
                events = []
                for calendar in principal.calendars():
                    calendar.add_event(str(cal.serialize()))
                self.speak_dialog("new.event.summary",
                                  data={"event": str(event)})
            except:
                self.speak_dialog("error.logging.in")
                return None

        elif server_type is None:
            # Password local
            server_address = self.settings.get("server_address")
            calendar = self.settings.get("calendar")
            port = self.settings.get("port")
            account_config = self.config_core.get("calendar", {})
            username = account_config.get("username")
            password = account_config.get("password")

            # start creating a vevent:
            cal = vobject.iCalendar()
            cal.add("vevent")
            # add name
            cal.vevent.add("summary").value = str(event)
            # add date
            cal.vevent.add('dtstart').value = date
            # add it to the calendar
            url = "http://{}:{}@{}:{}/".format(username, password,
                                               server_address, port)
            try:
                client = caldav.DAVClient(url)
                principal = client.principal()

                # Select calendar
                events = []
                for calendar in principal.calendars():
                    calendar.add_event(str(cal.serialize()))
                self.speak_dialog("new.event.summary",
                                  data={"event": str(event)})
            except:
                self.speak_dialog("error.logging.in")
                return None

        elif server_type == False:
            #Local
            #The calendar is on the device
            #Check if it needs to be made...
            fs = FileSystemAccess(str(self.skill_id))
            if fs.exists("calendar.ics"):
                #YAY! exists
                calendar = self.read_file("calendar.ics")
                c = ics.Calendar(calendar)
                e = ics.Event()
                #add event
                e.name = str(event)
                e.begin = str(arrow.get(date))
                c.events.apaddpend(e)
                self.write_file("calendar.ics", str(c))
                self.speak_dialog("new.event.summary",
                                  data={"event": str(event)})
            else:
                #create calendar
                c = ics.Calendar()
                e = ics.Event()
                #add event
                e.name = str(event)
                e.begin = str(arrow.get(date))
                c.events.add(e)
                self.write_file("calendar.ics", str(c))
                self.speak_dialog("new.event.summary",
                                  data={"event": str(event)})
コード例 #12
0
 def extractWithFormat_fr(text):
     date = datetime(2017, 6, 27, 0, 0)
     [extractedDate, leftover] = extract_datetime(text, date,
                                                  lang="fr-fr")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #13
0
 def test_extractdatetime_default_fr(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime("faire les plantations le 3ème jour de mars",
                            anchor, lang='fr-fr', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #14
0
 def test_extract_datetime(self):
     """Check that extract_datetime returns the expected timezone."""
     tz = default_timezone()
     dt, _ = extract_datetime("today")
     self.assertEqual(tz, dt.tzinfo)
コード例 #15
0
def contains_datetime(utterance, lang='en-us'):
    return extract_datetime(utterance) is not None
コード例 #16
0
    def _get_alarm_matches(self, utt, alarm=None, max_results=1,
                           dialog='ask.which.alarm', is_response=False):
        """Get list of alarms that match based on a user utterance.
        Arguments:
            utt (str): string spoken by the user
            alarm (list): list of alarm to match against
            max_results (int): max number of results desired
            dialog (str): name of dialog file used for disambiguation
            is_response (bool): is this being called by get_response
        Returns:
            (str): ["All", "Matched", "No Match Found", or "User Cancelled"]
            (list): list of matched alarm
        """
        alarms = alarm or self.settings['alarm']
        all_words = self.translate_list('all')
        next_words = self.translate_list('next')
        status = ["All", "Matched", "No Match Found", "User Cancelled", "Next"]

        # No alarms
        if alarms is None or len(alarms) == 0:
            self.log.error("Cannot get match. No active alarms.")
            return (status[2], None)

        # Extract Alarm Time
        when, utt_no_datetime = extract_datetime(utt, lang=self.lang) or (None, None)

        # Will return dt of unmatched string
        today = extract_datetime(self.texts.get('today'), lang=self.lang)
        today = today[0]

        # Check the time if it's midnight. This is to check if the user
        # said a recurring alarm with only the Day or if the user did
        # specify to set an alarm on midnight. If it's confirmed that
        # it's for a day only, then get another response from the user
        # to clarify what time on that day the recurring alarm is.
        is_midnight = self._check_if_utt_has_midnight(utt,
                                                      when,
                                                      self.threshold)

        if when == today and not is_midnight:
            when = None

        time_matches = None
        time_alarm = None
        if when:
            time_alarm = to_utc(when).timestamp()
            if is_midnight:
                time_alarm = time_alarm + 86400.0
            time_matches = [a for a in alarms
                            if abs(a["timestamp"] - time_alarm) <= 60]

        # Extract Recurrence
        recur = None
        recurrence_matches = None
        for word in self.recurrence_dict:
            is_match = self._fuzzy_match(word, utt.lower(), self.threshold)
            if is_match:
                recur = self._create_day_set(utt)
                alarm_recur = self._create_recurring_alarm(when, recur)
                recurrence_matches = [a for a in alarms
                    if a["repeat_rule"] == alarm_recur["repeat_rule"]
                ]
                break

        utt = utt_no_datetime or utt

        # Extract Ordinal/Cardinal Numbers
        number = extract_number(utt, ordinals=True, lang=self.lang)
        if number and number > 0:
            number = int(number)
        else:
            number = None

        # Extract Name
        name_matches = [a for a in alarms if a["name"] and
                        self._fuzzy_match(a["name"], utt, self.threshold)]

        # Match Everything
        alarm_to_match = None
        if when:
            if recur:
                alarm_to_match = alarm_recur
            else:
                alarm_to_match = {"timestamp": time_alarm, "repeat_rule": ""}

        # Find the Intersection of the Alarms list and all the matched alarms
        orig_count = len(alarms)
        if when and time_matches:
            alarms = [a for a in alarms if a in time_matches]
        if recur and recurrence_matches:
            alarms = [a for a in alarms if a in recurrence_matches]
        if name_matches:
            alarms = [a for a in alarms if a in name_matches]

        # Utterance refers to all alarms
        if utt and any(self._fuzzy_match(i, utt, 1) for i in all_words):
            return (status[0], alarms)
        # Utterance refers to the next alarm to go off
        elif utt and any(self._fuzzy_match(i, utt, 1) for i in next_words):
            return (status[4], [alarms[0]])

        # Given something to match but no match found
        if ((number and number > len(alarms)) or
                (recur and not recurrence_matches) or
                (when and not time_matches)):
            return (status[2], None)
        # If number of alarms filtered were the same, assume user asked for
        # All alarms
        if (len(alarms) == orig_count and max_results > 1 and
                not number and not when and not recur):
            return (status[0], alarms)
        # Return immediately if there is ordinal
        if number and number <= len(alarms):
            return (status[1], [alarms[number - 1]])
        # Return immediately if within maximum results
        elif alarms and len(alarms) <= max_results:
            return (status[1], alarms)
        # Ask for reply from user and iterate the function
        elif alarms and len(alarms) > max_results:
            desc = []
            for alarm in alarms:
                desc.append(self._describe(alarm))

            items_string = ''
            if desc:
                items_string = join_list(desc, self.translate('and'))

            reply = self.get_response(dialog, data={
                                                    'number': len(alarms),
                                                    'list': items_string,
                                                    }, num_retries=1)
            if reply:
                return self._get_alarm_matches(reply,
                                               alarm=alarms,
                                               max_results=max_results,
                                               dialog=dialog,
                                               is_response=True)
            else:
                return (status[3], None)

        # No matches found
        return (status[2], None)
コード例 #17
0
    def handle_add_event_intent(self, message):
        utt = message.data['utterance']
        time_delta, remaining_utt = extract_duration(
            utt)  # get time duration from utterance
        start_time, remaining_utt = extract_datetime(
            remaining_utt)  # get time from utterance
        owner = message.data.get('Owner')  # get calendar owner
        utt = normalize(utt).replace("'s",
                                     "")  # normalize and drop 's in utterance
        parsed_utt = asjson(
            self.PEGParser.parse(utt))  # parse utterance for owner
        owner = parsed_utt.get('calendar_owner')
        if owner is None:  # if parser failed to get owner, prompt user
            owner = self.get_response('ask.calendar.owner')

        self.log.info('using owner: {}'.format(owner))

        try:  # get the calendar belonging to owner
            calName = self.nameToCalendar[owner]  # throw error if none found
        except KeyError:
            self.speak_dialog('no.calendar.found.error', {'name': owner})
            return

        if start_time is None:  # if start time not found
            start_time, _ = extract_datetime(
                self.get_response('ask.start.time'))  # ask the user

        if time_delta is None:  # if duration not found
            time_delta, _ = extract_duration(
                self.get_response('ask.duration'))  # ask the user

        if time_delta is None or start_time is None:  # if duration of start time STILL unkonwn
            self.speak(
                'sorry. i was not able to understand. please start over.'
            )  # fail
            return

        end_time = start_time + time_delta  # calculate end time

        eventName = self.get_response(
            'ask.event.name').title()  # ask for event name

        confirmation = self.ask_yesno(
            'confirm.event',  # confirm details
            {
                'event_name': eventName,
                'confirmation_text': self.confirmEventDetails(
                    start_time, end_time),
                'owner': self.calendarToName[calName]
            })
        if confirmation == 'no':
            self.speak_dialog('confirmation.failed')

        elif confirmation == 'yes':
            url, user, password = self.getConfigs()  # get  configs
            if url is None:  # if getConfigs returned None, it failed and
                pass  # already spoke to user
            else:
                calendar = self.getCalendar(
                    calName, url, user,
                    password)  # get calendar and create the event
                self.makeEvent(calendar,
                               start_time,
                               end_time,
                               eventName,
                               owner=self.calendarToName[calName])
        else:
            self.speak('sorry i did not understand.')
コード例 #18
0
 def test_extractdatetime_default_fr(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime("faire les plantations le 3ème jour de mars",
                            anchor, lang='fr-fr', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #19
0
    def convertSpokenTimeRangeToDT(self, time_range_string):
        time_range_list = time_range_string.split(' ')
        # attempt to get starting datetime directly
        try:
            extracted_dt = extract_datetime(
                time_range_string
            )  # try using mycroft's parser to get the start time
            if extracted_dt is None:  # is likely 'this week' or 'this weekend'
                if 'week' in time_range_list:
                    start = dt.now(
                    )  # start at current time so as to ignore any of todays
                    self.log.info(
                        'got this week')  # events that have allready passed
                elif 'weekend' in time_range_list:
                    self.log.info('got weekend')
                    now = dt.now(
                    )  # for 'this weekend' start should be the upcoming sat
                    current_dow = now.weekday(
                    )  # unless it is already sat or sun. It it is sat or sun
                    offset = 5 - current_dow  # start at current time
                    if offset <= 0:
                        offset = 0

                    if 'next' in time_range_list:  # for 'next weekend', add 7 to the calculated offset
                        offset += 7  # from above

                    start = dt(now.year, now.month,
                               now.day) + timedelta(offset)
                else:  # all other key words for time range should be captured
                    self.speak("i could not parse the given time range"
                               )  # in the other conditional blocks
                    assert False, "key word not supported."

            else:
                if time_range_string == "next week":  # 'next week' will get parsed incorrectly by
                    self.log.info('got next week')  # extract_datetime
                    now = dt.now()
                    current_dow = now.weekday(
                    )  # get the upcoming sunday; if it is currently sunday
                    offset = 6 - current_dow  # get the following one
                    if offset == 0:
                        offset = 7
                    start = dt(now.year, now.month,
                               now.day) + timedelta(offset)

                else:  # otherwise use the datetime provided by extract_datetime
                    self.log.info('got something else')
                    start = extracted_dt[0]

            # now that the start time is found get the end time from the time string
            if 'day' in time_range_string or 'tomorrow' in time_range_string:  # handles day, today, monday, tuesday, etc
                end = dt(start.year, start.month, start.day, 23,
                         59)  # end on 11:59pm of same day

            elif 'weekend' in time_range_string:  # start is saturday morn, so end on last min of sunday
                end = dt(start.year, start.month, start.day, 23,
                         59) + timedelta(1)

            elif 'week' in time_range_string:
                starting_dow = start.weekday(
                )  # end on the saturday of the given week
                if starting_dow == 6:  # if it is sunday, +6 days 23h 59m
                    end = dt(start.year, start.month, start.day, 23,
                             59) + timedelta(6)
                else:  # if it is not sunday, add the required days + 23:59 to reach sat
                    end = dt(start.year, start.month, start.day, 23,
                             59) + timedelta(5 - starting_dow)
            else:  # afternoon, evening, morning resutls in 4h ranges
                end = start + timedelta(hours=4)

            self.log.info("start: {}".format(start))
            self.log.info("end: {}".format(end))
            return start, end

        except Exception as e:  # log and notify of any errors
            self.speak("i could not parse given time range")
            self.log.error(e)
コード例 #20
0
    def handle_cinema_deckchair(self, message):
        try:
            now_date = datetime.now()
            # 1. Scrape website for movie on this date
            try:
                program_tr_list = self.cinema_program.fetch(
                    cache=[join(self.file_system.path), now_date])
            except (exceptions.ConnectionError or exceptions.HTTPError
                    or exceptions.Timeout or exceptions.TooManyRedirects) as e:
                self.log.error('Error: {0}'.format(e))
                self.speak_dialog('error.http')
                return

            # 2. Extract date from utterance, or default to today
            when = extract_datetime(message.data.get('utterance'))[0]
            if self.testing_date is not None:
                when = self.testing_date

            # 3. Test if date is in deckchair program range
            first_date = self._get_date_from_list(program_tr_list, 'first')
            last_date = self._get_date_from_list(program_tr_list, 'last')
            if when < first_date or last_date < when:
                self.speak_dialog(
                    'error.datenotfound', {
                        'when': nice_date(when, now=now_date),
                        'first_date': nice_date(first_date, now=now_date),
                        'last_date': nice_date(last_date, now=now_date)
                    })
                return False

            # 4. Find movie on provided date
            try:
                date_row = next(
                    (x for x in program_tr_list
                     if x.getchildren()[0].text == when.strftime('%A %-d %B')))
            except StopIteration:
                self.log.info('Date note found: {}'.format(
                    when.strftime('%A %-d %B')))
                return self.speak_dialog(
                    'error.datenotfound', {
                        'when': nice_date(when, now=now_date),
                        'first_date': nice_date(first_date, now=now_date),
                        'last_date': nice_date(last_date, now=now_date)
                    })
            movies_on_date = self._add_movie_from_date(date_row,
                                                       movies_on_date=[])

            # 5. Construct message to return
            movie_details_dialog = []
            for movie in movies_on_date:
                if len(movie_details_dialog) > 0:
                    movie_details_dialog.append(self.translate('and'))
                movie_title = movie.getchildren()[0].getchildren()[0].text
                movie_time = nice_time(
                    when.replace(hour=int(movie.getchildren()[1].text[0:-5]),
                                 minute=int(
                                     movie.getchildren()[1].text[-4:-2])))
                movie_details_dialog.append(
                    self.translate('movie.at.time', {
                        'title': movie_title,
                        'time': movie_time
                    }))

            self.speak_dialog(
                'whats.on', {
                    'when': nice_date(when, now=datetime.now()),
                    'movie_details': ', '.join(movie_details_dialog)
                })

            # 6. Fetch data and set context for follow up questions
            # Reset data from previous requests.
            self._movies_on_requested_date = []
            self._current_movie_context = ''
            for movie in movies_on_date:
                movie_details = self._fetch_movie_details(movie)
                self._movie_dict[movie_details['title']] = movie_details
                self._movies_on_requested_date.append(
                    movie.getchildren()[0].getchildren()[0].text)
            self.set_context('DeckchairContext', 'True')

        except Exception as e:
            self.log.exception(format(e))
            self.speak_dialog('error')
コード例 #21
0
    def handle_current_weather(self, message):
        try:
            # Get a date from requests like "weather for next Tuesday"
            today = extract_datetime(" ")[0]
            when, _ = extract_datetime(message.data.get('utterance'),
                                       lang=self.lang)
            if today != when:
                LOG.info("Doing a forecast" + str(today) + " " + str(when))
                return self.handle_forecast(message)

            report = self.__initialize_report(message)

            # Get current conditions
            currentWeather = self.owm.weather_at_place(
                report['full_location'], report['lat'],
                report['lon']).get_weather()
            condition = self.__translate(currentWeather.get_detailed_status())
            report['condition'] = condition
            report['temp'] = self.__get_temperature(currentWeather, 'temp')
            report['icon'] = currentWeather.get_weather_icon_name()

            # Get forecast for the day
            # can get 'min', 'max', 'eve', 'morn', 'night', 'day'
            # Set time to 12 instead of 00 to accomodate for timezones
            forecastWeather = self.__get_forecast(today.replace(hour=12),
                                                  report['full_location'],
                                                  report['lat'], report['lon'])
            report['temp_min'] = self.__get_temperature(forecastWeather, 'min')
            report['temp_max'] = self.__get_temperature(forecastWeather, 'max')
            weather_code = str(report['icon'])
            img_code = self.CODES[weather_code]
            futureWeather = self.owm.daily_forecast(report['full_location'],
                                                    report['lat'],
                                                    report['lon'],
                                                    limit=5)
            f = futureWeather.get_forecast()
            forecastDump = {}
            forecastList = []
            days = [
                "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
                "Saturday", "Sunday"
            ]
            unit = self.__get_temperature_unit()
            for weather in f.get_weathers():
                result_temp = weather.get_temperature(unit)
                result_temp_day = days[datetime.weekday(
                    datetime.fromtimestamp(weather.get_reference_time()))]
                forecastList.append({
                    "weathercode":
                    self.CODES[weather.get_weather_icon_name()],
                    "max":
                    result_temp['max'],
                    "min":
                    result_temp['min'],
                    "date":
                    result_temp_day
                })
            forecastList.pop(0)
            forecastDump['forecast'] = forecastList
            LOG.info(forecastDump['forecast'])
            self.enclosure.bus.emit(
                Message(
                    "metadata", {
                        "type": "mycroft-weather",
                        "current": report["temp"],
                        "min": report["temp_min"],
                        "max": report["temp_max"],
                        "location": report["full_location"],
                        "condition": report["condition"],
                        "icon": report["icon"],
                        "weathercode": img_code,
                        "forecastDump": forecastDump
                    }))
            self.__report_weather("current", report)
        except HTTPError as e:
            self.__api_error(e)
        except Exception as e:
            LOG.error("Error: {0}".format(e))
コード例 #22
0
 def extractWithFormat(text):
     date = datetime(2017, 6, 27, 10, 1, 2)
     [extractedDate, leftover] = extract_datetime(text, date,
                                                  lang='it-it')
     extractedDate = extractedDate.strftime('%Y-%m-%d %H:%M:%S')
     return [extractedDate, leftover]
コード例 #23
0
 def extractWithFormat(text):
     date = datetime(2018, 1, 13, 0, 0)
     [extractedDate, leftover] = extract_datetime(text, date, lang="it")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #24
0
    def handle_update_end_date(self):
        # Getting the credentials for G.People API
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run_flow(FLOW, storage)

        http = httplib2.Http()
        http = credentials.authorize(http)

        people_service = build(serviceName='people', version='v1', http=http)

        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='emailAddresses,names').execute()
        connections = results.get('connections', [])

        # Get credentials for google calendar with [email protected]
        # and token management
        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)
        # Getting the event you want to update
        title = self.get_response('what\'s the name of the event')
        events_result = service.events().list(calendarId='primary',
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=title).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak('event not found')
        for event in events:
            eventid = event['id']

        # Getting inputs
        end = self.get_response('when does it end?')
        et = extract_datetime(end)
        event['start'] = et
        # Updating the Event
        service.events().update(calendarId='primary',
                                eventId=eventid,
                                body=event).execute()
        self.speak_dialog('successful.update')
コード例 #25
0
    def handle_device(self, message):
        storage1 = Storage(
            '/opt/mycroft/skills/devicereservation.hanabouzid/info.dat')
        credentials = storage1.get()
        if credentials is None or credentials.invalid == True:
            credentials = tools.run_flow(FLOW, storage1)
        print(credentials)
        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our good Credentials.
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('calendar', 'v3', http=http)
        people_service = build(serviceName='people', version='v1', http=http)
        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=100,
            personFields='names,emailAddresses',
            fields='connections,totalItems,nextSyncToken').execute()
        connections = results.get('connections', [])
        print("authorized")
        listdiv = []
        utt = message.data.get("utterance", None)
        liste1 = utt.split(" a ")
        liste2 = liste1[1].split(" for ")
        if ("and") in liste2[0]:
            listdiv = liste2[0].split(" and ")
        else:
            listdiv.append(liste2[0])
        print(listdiv)
        date1 = liste2[1]
        st = extract_datetime(date1)
        st = st[0] - self.utc_offset
        datestart = st.strftime('%Y-%m-%dT%H:%M:00')
        datestart += UTC_TZ
        print(datestart)
        date2 = self.get_response('when will you return the device?')
        et = extract_datetime(date2)
        et = et[0] - self.utc_offset
        dater = et.strftime('%Y-%m-%dT%H:%M:00')
        dater += UTC_TZ
        print(dater)

        nameListe = []
        adsmails = []
        # attendee est la liste des invités qui sont disponibles
        attendees = []

        for person in connections:
            emails = person.get('emailAddresses', [])
            names = person.get('names', [])
            adsmails.append(emails[0].get('value'))
            nameListe.append(names[0].get('displayName'))
        print(nameListe)
        print(adsmails)
        nameEmp = self.get_response('What is your name please?')
        mailEmp = self.recherche(nameListe, adsmails, nameEmp)
        #service.list(customer='my_customer' , orderBy=None, pageToken=None, maxResults=None, query=None)
        #.get(customer=*, calendarResourceId=*)
        listD = ['pcfocus']
        listDmails = [
            '*****@*****.**'
        ]
        freeDevices = []
        freemails = []
        for i in range(len(listDmails)):
            x = self.freebusy(i, datestart, dater, service)
            if x == True:
                freeDevices.append(listD[i])
                freemails.append(listDmails[i])
        print(freemails)
        print(freeDevices)

        s = ",".join(freeDevices)
        print('free devices' + s)
        for device in listdiv:
            l = []
            for i in freeDevices:
                print(i)
                if device in i.lower():
                    l.append(i)
                    print(l)
            if l != []:
                self.speak_dialog('free', data={"device": device, "s": s})
                choice = self.get_response('what is your choice?')
                email = self.recherche(freeDevices, freemails, choice)
                attendees.append({'email': email})
                summary = choice + "reservation for Mr/Ms" + nameEmp
                description = "Mr/Ms" + nameEmp + "'s email:" + mailEmp
                reservation = {
                    'summary': summary,
                    'description': description,
                    'location': 'Focus corporation',
                    'start': {
                        'dateTime': datestart,
                        'timeZone': 'America/Los_Angeles',
                    },
                    'end': {
                        'dateTime': dater,
                        'timeZone': 'America/Los_Angeles',
                    },
                    'recurrence': ['RRULE:FREQ=DAILY;COUNT=1'],
                    'attendees': attendees,
                    'reminders': {
                        'useDefault':
                        False,
                        'overrides': [
                            {
                                'method': 'email',
                                'minutes': 24 * 60
                            },
                            {
                                'method': 'popup',
                                'minutes': 10
                            },
                        ],
                    },
                }
                reservation = service.events().insert(
                    calendarId='primary',
                    sendNotifications=True,
                    body=reservation).execute()
                print('Event created: %s' % (reservation.get('htmlLink')))
                self.speak_dialog('deviceReserved', data={"device": device})
            else:
                self.speak_dialog('busy', data={"device": device})
コード例 #26
0
    def handle_windy(self, message):
        report = self.__initialize_report(message)

        when = extract_datetime(message.data.get('utterance'))[0]
        if when == extract_datetime(" ")[0]:
            weather = self.owm.weather_at_place(report['full_location'],
                                                report['lat'],
                                                report['lon']).get_weather()
        else:
            # Get forecast for that day
            weather = self.__get_forecast(when, report['full_location'],
                                          report['lat'], report['lon'])
        if not weather or weather.get_wind() == 0:
            self.speak_dialog("do not know")
            return

        wind = weather.get_wind()

        speed = wind["speed"]
        # get speed
        if self.__get_speed_unit() == "mph":
            speed *= 2.23694
            unit = self.__translate("miles per hour")
        else:
            unit = self.__translate("meters per second")
        speed = round(speed)

        # get direction, convert compass degrees to named direction
        if "deg" in wind:
            deg = wind["deg"]
            if deg < 22.5:
                dir = "N"
            elif deg < 67.5:
                dir = "NE"
            elif deg < 112.5:
                dir = "E"
            elif deg < 157.5:
                dir = "SE"
            elif deg < 202.5:
                dir = "S"
            elif deg < 247.5:
                dir = "SW"
            elif deg < 292.5:
                dir = "W"
            elif deg < 337.5:
                dir = "NW"
            else:
                dir = "N"
            dir = self.__translate(dir)
            value = self.__translate("wind.speed.dir",
                                     data={
                                         "dir": dir,
                                         "speed": nice_number(speed),
                                         "unit": unit
                                     })
        else:
            value = self.__translate("wind.speed",
                                     data={
                                         "speed": nice_number(speed),
                                         "unit": unit
                                     })

        self.__report_condition(self.__translate("winds"), value, when)
コード例 #27
0
 def test_extractdatetime_default_da(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime("lad os mødes på fredag klokken 9 om morgenen",
                            anchor, lang='da-dk', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #28
0
    def test_extract_datetime_relative(self):
        self.assertEqual(
            extract_datetime("esta noche",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es'),
            [datetime(1998, 1, 1, 21, 0, 0), 'esta'])
        self.assertEqual(
            extract_datetime("ayer noche",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1997, 12, 31, 21))
        self.assertEqual(
            extract_datetime("el noche anteayer",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1997, 12, 30, 21))
        self.assertEqual(
            extract_datetime("el noche ante ante ayer",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1997, 12, 29, 21))
        self.assertEqual(
            extract_datetime("mañana en la mañana",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1998, 1, 2, 8))
        self.assertEqual(
            extract_datetime("ayer en la tarde",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1997, 12, 31, 15))

        self.assertEqual(
            extract_datetime("que año es",
                             anchorDate=datetime(1998, 1, 1),
                             lang='es')[0], datetime(1998, 1, 1))

        self.assertEqual(
            extract_datetime("hoy 2 a.m.",
                             lang='es',
                             anchorDate=datetime(1998, 1, 1))[0],
            datetime(1998, 1, 1, 2))
        self.assertEqual(
            extract_datetime("hoy 2 am",
                             lang='es',
                             anchorDate=datetime(1998, 1, 1))[0],
            datetime(1998, 1, 1, 2))
        self.assertEqual(
            extract_datetime("hoy 2 p.m.",
                             lang='es',
                             anchorDate=datetime(1998, 1, 1))[0],
            datetime(1998, 1, 1, 14))
        self.assertEqual(
            extract_datetime("hoy 2 pm",
                             lang='es',
                             anchorDate=datetime(1998, 1, 1))[0],
            datetime(1998, 1, 1, 14))
コード例 #29
0
    def updateevent(self, message):
        #AUTHORIZE
        storage1 = Storage(
            '/opt/mycroft/skills/updateeventskill.hanabouzid/info3.dat')
        credentials = storage1.get()
        if credentials is None or credentials.invalid == True:
            credentials = tools.run_flow(FLOW, storage1)
        print(credentials)
        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our good Credentials.
        http = httplib2.Http()
        http = credentials.authorize(http)

        # Build a service object for interacting with the API. To get an API key for
        # your application, visit the Google API Console
        # and look at your application's credentials page.
        service = build('calendar', 'v3', http=http)
        people_service = build(serviceName='people', version='v1', http=http)
        print("authorized")
        # To get the person information for any Google Account, use the following code:
        # profile = people_service.people().get('people/me', pageSize=100, personFields='names,emailAddresses').execute()
        # To get a list of people in the user's contacts,
        # results = service.people().connections().list(resourceName='people/me',personFields='names,emailAddresses',fields='connections,totalItems,nextSyncToken').execute()
        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=100,
            personFields='names,emailAddresses,events',
            fields='connections,totalItems,nextSyncToken').execute()
        connections = results.get('connections', [])
        print("connections:", connections)
        utt = message.data.get("utterance", None)

        # extract the location
        #location = message.data.get("Location", None)
        print(utt)
        #listname1=utt.split(" named ")
        #listname2=listname1[1].split(" with ")
        #title =listname2[0]
        lister = utt.split(" starts ")
        lister2 = lister[1].split(" in ")
        location = lister2[1]
        print(location)
        strtdate = lister2[0]
        st = extract_datetime(strtdate)
        st = st[0] - self.utc_offset
        datestart = st.strftime('%Y-%m-%dT%H:%M:00')
        datestart += UTC_TZ
        print(datestart)
        lister3 = lister[0].split(" the event ")
        title = lister3[1]
        print(title)
        # liste de contacts
        nameliste = []
        adsmails = []
        for person in connections:
            emails = person.get('emailAddresses', [])
            adsmails.append(emails[0].get('value'))
            names = person.get('names', [])
            nameliste.append(names[0].get('displayName'))
        # liste of meeting rooms
        namerooms = [
            'midoune room', 'aiguilles room', 'barrouta room', 'kantaoui room',
            'gorges room', 'ichkeul room', 'khemir room', 'tamaghza room',
            'friguia room', 'ksour room', 'medeina room', 'thyna room'
        ]
        emailrooms = [
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**",
            "*****@*****.**"
        ]

        events_result = service.events().list(calendarId='primary',
                                              timeMin=datestart,
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=location).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak_dialog("notEvent")

        for event in events:
            eventid = event['id']
            eventend = event['end']['dateTime']
            attendees = event['attendees']

        # freerooms
        freemails = []
        freerooms = []
        for i in range(0, len(emailrooms)):
            if self.freebusy(emailrooms[i], datestart, eventend, service):
                # la liste freerooms va prendre  les noms des salles free
                freerooms.append(namerooms[i])
                freemails.append(emailrooms[i])
        suggroom = freerooms[0]
        suggmail = freemails[0]
        ask = self.get_response('what do you want to update')
        if ask == "update title":
            newtitle = self.get_response('what is the new title?')
            eventup = {
                'summary': newtitle,
            }
        elif ask == "update description":
            newdesc = self.get_response('what is the new description?')
            eventup = {
                'description': newdesc,
            }
        elif ask == "update start date time ":
            newdatestrt = self.get_response('what is the new start date time?')
            st1 = extract_datetime(newdatestrt)
            st1 = st1[0] - self.utc_offset
            newdatestart = st1.strftime('%Y-%m-%dT%H:%M:00')
            newdatestart += UTC_TZ
            eventup = {
                'start': {
                    'dateTime': newdatestart,
                    'timeZone': 'America/Los_Angeles',
                },
            }
        elif ask == "update end date time ":
            newdatd = self.get_response('what is the new start date time?')
            et1 = extract_datetime(newdatd)
            et1 = et1[0] - self.utc_offset
            newdateend = et1.strftime('%Y-%m-%dT%H:%M:00')
            newdateend += UTC_TZ
            eventup = {
                'end': {
                    'dateTime': newdateend,
                    'timeZone': 'America/Los_Angeles',
                },
            }

        elif ask == "update location":
            for j, e in enumerate(namerooms):
                if location == e:
                    deletemail = emailrooms[j]
                    email = {'email': deletemail}
                    print(email)
            for i in attendees:
                if i == email:
                    print(i)
                    attendees.remove(i)
            newlocation = self.get_response('what is the new location?')
            roommail = self.recherche(namerooms, emailrooms, newlocation)
            x = self.freebusy(roommail, datestart, eventend, service)
            if x == True:
                self.speak_dialog('roomfree',
                                  data={"newlocation": newlocation})
                email = {'email': roommail}
                attendees.append(email)
                eventup = {
                    'location': newlocation,
                    'attendees': attendees,
                }

            else:
                self.speak_dialog('roombusy',
                                  data={"newlocation": newlocation})
                self.speak_dialog("suggestionroom",
                                  data={"suggroom": suggroom})
                x = self.get_response(
                    "Do you agree making a reservation for this meeting room")
                if x == "yes":
                    newlocation = suggroom
                    email = {'email': suggmail}
                    attendees.append(email)
                else:
                    s = ",".join(freerooms)
                    # print("les salles disponibles a cette date sont", freerooms)
                    self.speak_dialog("freerooms", data={"s": s})
                    room = self.get_response(
                        'which Room do you want to make a reservation for??')
                    for i in range(0, len(freerooms)):
                        if (freerooms[i] == room):
                            # ajouter l'email de room dans la liste des attendees
                            newlocation = room
                            email = {'email': freemails[i]}
                            attendees.append(email)
                eventup = {
                    'location': newlocation,
                    'attendees': attendees,
                }
        elif ask == "delete attendee":
            name = self.get_response("what is the attendee's name?")
            for j, e in enumerate(nameliste):
                if name == e:
                    deletemail = adsmails[j]
                    email = {'email': deletemail}
                    print(email)
            for i in attendees:
                if i == email:
                    print(i)
                    attendees.remove(i)
            eventup = {
                'attendees': attendees,
            }
        elif ask == "add attendee":
            name = self.get_response("what is the attendee's name?")
            for j, e in enumerate(nameliste):
                if name == e:
                    addemail = adsmails[j]
                    email = {'email': addemail}
                    print(email)
            x = self.freebusy(addemail, datestart, eventend, service)
            if x == True:
                self.speak_dialog('attfree', data={"name": name})
                email = {'email': addemail}
                attendees.append(email)
                eventup = {
                    'attendees': attendees,
                }

            else:
                self.speak_dialog('attbusy', data={"name": name})

        print(eventup)
        service.events().patch(calendarId='primary',
                               eventId=eventid,
                               sendNotifications=True,
                               body=eventup).execute()
        self.speak_dialog("eventUpdated")
コード例 #30
0
    def handle_query_date(self, message, response_type="simple"):
        utt = message.data.get('utterance', "").lower()
        try:
            extract = extract_datetime(utt)
        except Exception:
            self.speak_dialog('date.not.found')
            return
        day = extract[0] if extract else now_local()

        # check if a Holiday was requested, e.g. "What day is Christmas?"
        year = extract_number(utt)
        if not year or year < 1500 or year > 3000:  # filter out non-years
            year = day.year
        all_holidays = {}
        # TODO: How to pick a location for holidays?
        for st in holidays.US.STATES:
            holiday_dict = holidays.US(years=[year], state=st)
            for d, name in holiday_dict.items():
                if name not in all_holidays:
                    all_holidays[name] = d
        for name in all_holidays:
            d = all_holidays[name]
            # Uncomment to display all holidays in the database
            # self.log.info("Day, name: " +str(d) + " " + str(name))
            if name.replace(" Day", "").lower() in utt:
                day = d
                break

        location = self._extract_location(utt)
        today = to_local(now_utc())
        if location:
            # TODO: Timezone math!
            if (day.year == today.year and day.month == today.month
                    and day.day == today.day):
                day = now_utc()  # for questions ~ "what is the day in sydney"
            day = self.get_local_datetime(location, dtUTC=day)
        if not day:
            return  # failed in timezone lookup

        speak_date = nice_date(day, lang=self.lang)
        # speak it
        if response_type == "simple":
            self.speak_dialog("date", {"date": speak_date})
        elif response_type == "relative":
            # remove time data to get clean dates
            day_date = day.replace(hour=0, minute=0, second=0, microsecond=0)
            today_date = today.replace(hour=0,
                                       minute=0,
                                       second=0,
                                       microsecond=0)
            num_days = (day_date - today_date).days
            if num_days >= 0:
                speak_num_days = nice_duration(num_days * 86400)
                self.speak_dialog("date.relative.future", {
                    "date": speak_date,
                    "num_days": speak_num_days
                })
            else:
                # if in the past, make positive before getting duration
                speak_num_days = nice_duration(num_days * -86400)
                self.speak_dialog("date.relative.past", {
                    "date": speak_date,
                    "num_days": speak_num_days
                })

        # and briefly show the date
        self.answering_query = True
        self.show_date(location, day=day)
        time.sleep(10)
        mycroft.audio.wait_while_speaking()
        if self.platform == "mycroft_mark_1":
            self.enclosure.mouth_reset()
            self.enclosure.activate_mouth_events()
        self.answering_query = False
        self.displayed_time = None
コード例 #31
0
 def test_extractdatetime_default_de(self):
     default = time(9, 0, 0)
     anchor = datetime(2017, 6, 27, 0, 0)
     res = extract_datetime("lass uns treffen am freitag",
                            anchor, lang='de-de', default_time=default)
     self.assertEqual(default, res[0].time())
コード例 #32
0
 def extractWithFormat(text):
     date = datetime(2017, 6, 27, 13, 4)  # Tue June 27, 2017 @ 1:04pm
     [extractedDate, leftover] = extract_datetime(text, date)
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #33
0
    def deleteEvent(self, message):
        storage1 = Storage(
            '/opt/mycroft/skills/deleteeventskill.hanabouzid/info3.dat')
        credentials = storage1.get()
        if credentials is None or credentials.invalid == True:
            credentials = tools.run_flow(FLOW, storage1)
        print(credentials)
        # Create an httplib2.Http object to handle our HTTP requests and
        # authorize it with our good Credentials.
        http = httplib2.Http()
        http = credentials.authorize(http)
        service = build('calendar', 'v3', http=http)
        people_service = build(serviceName='people', version='v1', http=http)
        print("authorized")
        # To get a list of people in the user's contacts,
        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=100,
            personFields='names,emailAddresses',
            fields='connections,totalItems,nextSyncToken').execute()
        connections = results.get('connections', [])

        # Call the Calendar API
        now = datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
        print('Getting the upcoming 10 events')
        events_result = service.events().list(calendarId='primary',
                                              timeMin=now,
                                              maxResults=10,
                                              singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])

        if not events:
            print('No upcoming events found.')
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'])
        #extraire la date et le titre
        utt = message.data.get("utterance", None)

        # extract the location
        # location = message.data.get("Location", None)
        print(utt)
        # listname1=utt.split(" named ")
        # listname2=listname1[1].split(" with ")
        # title =listname2[0]
        lister = utt.split(" starts ")
        lister2 = lister[1].split(" in ")
        location = lister2[1]
        print(location)
        strtdate = lister2[0]
        st = extract_datetime(strtdate)
        st = st[0] - self.utc_offset
        datestart = st.strftime('%Y-%m-%dT%H:%M:00')
        datestart += UTC_TZ
        print(datestart)
        lister3 = lister[0].split(" the event ")
        title = lister3[1]
        print(title)
        events_result = service.events().list(calendarId='primary',
                                              timeMin=datestart,
                                              maxResults=1,
                                              singleEvents=True,
                                              orderBy='startTime',
                                              q=location).execute()
        events = events_result.get('items', [])
        if not events:
            self.speak_dialog("notEvent")

        for event in events:
            eventid = event['id']
            service.events().delete(calendarId='primary',
                                    eventId=eventid,
                                    sendUpdates='all').execute()
            self.speak_dialog("eventdeleted", data={"title": title})
コード例 #34
0
 def extractWithFormat(text):
     date = datetime(2018, 1, 13, 0, 0)
     [extractedDate, leftover] = extract_datetime(text, date,
                                                  lang="it")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #35
0
 def extractWithFormatNoDate_fr(text):
     [extractedDate, leftover] = extract_datetime(text, lang="fr-fr")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #36
0
 def extractWithFormatNoDate_fr(text):
     [extractedDate, leftover] = extract_datetime(text, lang="fr-fr")
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #37
0
    def test_extractdatetime_fr(self):
        def extractWithFormat_fr(text):
            date = datetime(2017, 6, 27, 0, 0)
            [extractedDate, leftover] = extract_datetime(text,
                                                         date,
                                                         lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtract_fr(text, expected_date, expected_leftover):
            res = extractWithFormat_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        def extractWithFormatDate2_fr(text):
            date = datetime(2017, 6, 30, 17, 0)
            [extractedDate, leftover] = extract_datetime(text,
                                                         date,
                                                         lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtractDate2_fr(text, expected_date, expected_leftover):
            res = extractWithFormatDate2_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        def extractWithFormatNoDate_fr(text):
            [extractedDate, leftover] = extract_datetime(text, lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtractNoDate_fr(text, expected_date, expected_leftover):
            res = extractWithFormatNoDate_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        testExtract_fr("Planifier l'embûche dans 5 jours",
                       "2017-07-02 00:00:00", "planifier embûche")
        testExtract_fr("Quel temps fera-t-il après-demain ?",
                       "2017-06-29 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Met un rappel à 10:45 du soir", "2017-06-27 22:45:00",
                       "met 1 rappel")
        testExtract_fr("quel temps est prévu pour vendredi matin ?",
                       "2017-06-30 08:00:00", "quel temps est prévu pour")
        testExtract_fr("quel temps fait-il demain", "2017-06-28 00:00:00",
                       "quel temps fait-il")
        testExtract_fr(
            "rappelle-moi d'appeler maman dans 8 semaines et"
            " 2 jours", "2017-08-24 00:00:00", "rappelle-moi appeler maman")
        testExtract_fr("Jouer des musiques de Beyonce 2 jours après vendredi",
                       "2017-07-02 00:00:00", "jouer musiques beyonce")
        testExtract_fr("Commencer l'invasion à 15 heures 45 jeudi",
                       "2017-06-29 15:45:00", "commencer invasion")
        testExtract_fr("Lundi, commander le gâteau à la boulangerie",
                       "2017-07-03 00:00:00", "commander gâteau à boulangerie")
        testExtract_fr("Jouer la chanson Joyeux anniversaire dans 5 ans",
                       "2022-06-27 00:00:00", "jouer chanson joyeux"
                       " anniversaire")
        testExtract_fr("Skyper Maman à 12 heures 45 jeudi prochain",
                       "2017-07-06 12:45:00", "skyper maman")
        testExtract_fr("Quel temps fera-t-il jeudi prochain ?",
                       "2017-07-06 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi matin ?",
                       "2017-06-30 08:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi soir",
                       "2017-06-30 19:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi après-midi",
                       "2017-06-30 15:00:00", "quel temps fera-t-il")
        testExtract_fr("rappelle-moi d'appeler maman le 3 août",
                       "2017-08-03 00:00:00", "rappelle-moi appeler maman")
        testExtract_fr("Acheter des feux d'artifice pour le 14 juil",
                       "2017-07-14 00:00:00", "acheter feux artifice pour")
        testExtract_fr("Quel temps fera-t-il 2 semaines après vendredi",
                       "2017-07-14 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il mercredi à 7 heures",
                       "2017-06-28 07:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il mercredi à 7 heures",
                       "2017-06-28 07:00:00", "quel temps fera-t-il")
        testExtract_fr("Prendre rendez-vous à 12:45 jeudi prochain",
                       "2017-07-06 12:45:00", "prendre rendez-vous")
        testExtract_fr("Quel temps fait-il ce jeudi ?", "2017-06-29 00:00:00",
                       "quel temps fait-il")
        testExtract_fr(
            "Organiser une visite 2 semaines et 6 jours après"
            " samedi", "2017-07-21 00:00:00", "organiser 1 visite")
        testExtract_fr("Commencer l'invasion à 3 heures 45 jeudi",
                       "2017-06-29 03:45:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion à 20 heures jeudi",
                       "2017-06-29 20:00:00", "commencer invasion")
        testExtract_fr("Lancer la fête jeudi à 8 heures du soir",
                       "2017-06-29 20:00:00", "lancer fête")
        testExtract_fr("Commencer l'invasion à 4 heures de l'après-midi jeudi",
                       "2017-06-29 16:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à midi",
                       "2017-06-29 12:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à minuit",
                       "2017-06-29 00:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à dix-sept heures",
                       "2017-06-29 17:00:00", "commencer invasion")
        testExtract_fr("rappelle-moi de me réveiller dans 4 années",
                       "2021-06-27 00:00:00", "rappelle-moi me réveiller")
        testExtract_fr("rappelle-moi de me réveiller dans 4 ans et 4 jours",
                       "2021-07-01 00:00:00", "rappelle-moi me réveiller")
        testExtract_fr("Quel temps fera-t-il 3 jours après demain ?",
                       "2017-07-01 00:00:00", "quel temps fera-t-il")
        testExtract_fr("3 décembre", "2017-12-03 00:00:00", "")
        testExtract_fr("retrouvons-nous à 8:00 ce soir", "2017-06-27 20:00:00",
                       "retrouvons-nous")
        testExtract_fr("retrouvons-nous demain à minuit et demi",
                       "2017-06-28 00:30:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi et quart",
                       "2017-06-27 12:15:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi moins le quart",
                       "2017-06-27 11:45:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi moins dix",
                       "2017-06-27 11:50:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi dix", "2017-06-27 12:10:00",
                       "retrouvons-nous")
        testExtract_fr("retrouvons-nous à minuit moins 23",
                       "2017-06-27 23:37:00", "retrouvons-nous")
        testExtract_fr("mangeons à 3 heures moins 23 minutes",
                       "2017-06-27 02:37:00", "mangeons")
        testExtract_fr("mangeons aussi à 4 heures moins le quart du matin",
                       "2017-06-27 03:45:00", "mangeons aussi")
        testExtract_fr("mangeons encore à minuit moins le quart",
                       "2017-06-27 23:45:00", "mangeons encore")
        testExtract_fr("buvons à 4 heures et quart", "2017-06-27 04:15:00",
                       "buvons")
        testExtract_fr("buvons également à 18 heures et demi",
                       "2017-06-27 18:30:00", "buvons également")
        testExtract_fr("dormons à 20 heures moins le quart",
                       "2017-06-27 19:45:00", "dormons")
        testExtract_fr("buvons le dernier verre à 10 heures moins 12 du soir",
                       "2017-06-27 21:48:00", "buvons dernier verre")
        testExtract_fr("s'échapper de l'île à 15h45", "2017-06-27 15:45:00",
                       "s'échapper île")
        testExtract_fr("s'échapper de l'île à 3h45min de l'après-midi",
                       "2017-06-27 15:45:00", "s'échapper île")
        testExtract_fr("décale donc ça à 3h48min cet après-midi",
                       "2017-06-27 15:48:00", "décale donc ça")
        testExtract_fr("construire un bunker à 9h42min du matin",
                       "2017-06-27 09:42:00", "construire 1 bunker")
        testExtract_fr("ou plutôt à 9h43 ce matin", "2017-06-27 09:43:00",
                       "ou plutôt")
        testExtract_fr("faire un feu à 8h du soir", "2017-06-27 20:00:00",
                       "faire 1 feu")
        testExtract_fr("faire la fête jusqu'à 18h cette nuit",
                       "2017-06-27 18:00:00", "faire fête jusqu'à")
        testExtract_fr("cuver jusqu'à 4h cette nuit", "2017-06-27 04:00:00",
                       "cuver jusqu'à")
        testExtract_fr("réveille-moi dans 20 secondes aujourd'hui",
                       "2017-06-27 00:00:20", "réveille-moi")
        testExtract_fr("réveille-moi dans 33 minutes", "2017-06-27 00:33:00",
                       "réveille-moi")
        testExtract_fr("tais-toi dans 12 heures et 3 minutes",
                       "2017-06-27 12:03:00", "tais-toi")
        testExtract_fr("ouvre-la dans 1 heure 3", "2017-06-27 01:03:00",
                       "ouvre-la")
        testExtract_fr("ferme-la dans 1 heure et quart", "2017-06-27 01:15:00",
                       "ferme-la")
        testExtract_fr("scelle-la dans 1 heure et demi", "2017-06-27 01:30:00",
                       "scelle-la")
        testExtract_fr("zippe-la dans 2 heures moins 12",
                       "2017-06-27 01:48:00", "zippe-la")
        testExtract_fr("soude-la dans 3 heures moins le quart",
                       "2017-06-27 02:45:00", "soude-la")
        testExtract_fr("mange la semaine prochaine", "2017-07-04 00:00:00",
                       "mange")
        testExtract_fr("bois la semaine dernière", "2017-06-20 00:00:00",
                       "bois")
        testExtract_fr("mange le mois prochain", "2017-07-27 00:00:00",
                       "mange")
        testExtract_fr("bois le mois dernier", "2017-05-27 00:00:00", "bois")
        testExtract_fr("mange l'an prochain", "2018-06-27 00:00:00", "mange")
        testExtract_fr("bois l'année dernière", "2016-06-27 00:00:00", "bois")
        testExtract_fr("reviens à lundi dernier", "2017-06-26 00:00:00",
                       "reviens")
        testExtract_fr("capitule le 8 mai 1945", "1945-05-08 00:00:00",
                       "capitule")
        testExtract_fr("rédige le contrat 3 jours après jeudi prochain",
                       "2017-07-09 00:00:00", "rédige contrat")
        testExtract_fr("signe le contrat 2 semaines après jeudi dernier",
                       "2017-07-06 00:00:00", "signe contrat")
        testExtract_fr("lance le four dans un quart d'heure",
                       "2017-06-27 00:15:00", "lance four")
        testExtract_fr("enfourne la pizza dans une demi-heure",
                       "2017-06-27 00:30:00", "enfourne pizza")
        testExtract_fr("arrête le four dans trois quarts d'heure",
                       "2017-06-27 00:45:00", "arrête four")
        testExtract_fr("mange la pizza dans une heure", "2017-06-27 01:00:00",
                       "mange pizza")
        testExtract_fr("bois la bière dans 2h23", "2017-06-27 02:23:00",
                       "bois bière")
        testExtract_fr("faire les plantations le 3ème jour de mars",
                       "2018-03-03 00:00:00", "faire plantations")
        testExtract_fr("récolter dans 10 mois", "2018-04-27 00:00:00",
                       "récolter")
        testExtract_fr("point 6a: dans 10 mois", "2018-04-27 06:00:00",
                       "point")
        testExtract_fr("l'après-midi démissionner à 4:59",
                       "2017-06-27 16:59:00", "démissionner")
        testExtract_fr("cette nuit dormir", "2017-06-27 02:00:00", "dormir")
        testExtract_fr("ranger son bureau à 1700 heures",
                       "2017-06-27 17:00:00", "ranger son bureau")

        testExtractDate2_fr("range le contrat 2 semaines après lundi",
                            "2017-07-17 00:00:00", "range contrat")
        testExtractDate2_fr("achète-toi de l'humour à 15h",
                            "2017-07-01 15:00:00", "achète-toi humour")
        # Disabling test until French Extract-date incorporates the fixes for
        # UTC / Local timezones.  Until then this test fails periodically
        # whenever test is run and the date in the local timezone (where the
        # test is being run) is a different than the date in UTC.
        #
        # testExtractNoDate_fr("tais-toi aujourd'hui",
        #                   datetime.now().strftime("%Y-%m-%d") + " 00:00:00",
        #                   "tais-toi")
        self.assertEqual(extract_datetime("", lang="fr-fr"), None)
        self.assertEqual(extract_datetime("phrase inutile", lang="fr-fr"),
                         None)
        self.assertEqual(
            extract_datetime("apprendre à compter à 37 heures", lang="fr-fr"),
            None)
コード例 #38
0
    def test_extractdatetime_fr(self):
        def extractWithFormat_fr(text):
            date = datetime(2017, 6, 27, 0, 0)
            [extractedDate, leftover] = extract_datetime(text, date,
                                                         lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtract_fr(text, expected_date, expected_leftover):
            res = extractWithFormat_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        def extractWithFormatDate2_fr(text):
            date = datetime(2017, 6, 30, 17, 0)
            [extractedDate, leftover] = extract_datetime(text, date,
                                                         lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtractDate2_fr(text, expected_date, expected_leftover):
            res = extractWithFormatDate2_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        def extractWithFormatNoDate_fr(text):
            [extractedDate, leftover] = extract_datetime(text, lang="fr-fr")
            extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
            return [extractedDate, leftover]

        def testExtractNoDate_fr(text, expected_date, expected_leftover):
            res = extractWithFormatNoDate_fr(text)
            self.assertEqual(res[0], expected_date)
            self.assertEqual(res[1], expected_leftover)

        testExtract_fr("Planifier l'embûche dans 5 jours",
                       "2017-07-02 00:00:00", "planifier embûche")
        testExtract_fr("Quel temps fera-t-il après-demain ?",
                       "2017-06-29 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Met un rappel à 10:45 du soir",
                       "2017-06-27 22:45:00", "met 1 rappel")
        testExtract_fr("quel temps est prévu pour vendredi matin ?",
                       "2017-06-30 08:00:00", "quel temps est prévu pour")
        testExtract_fr("quel temps fait-il demain",
                       "2017-06-28 00:00:00", "quel temps fait-il")
        testExtract_fr("rappelle-moi d'appeler maman dans 8 semaines et"
                       " 2 jours", "2017-08-24 00:00:00",
                       "rappelle-moi appeler maman")
        testExtract_fr("Jouer des musiques de Beyonce 2 jours après vendredi",
                       "2017-07-02 00:00:00", "jouer musiques beyonce")
        testExtract_fr("Commencer l'invasion à 15 heures 45 jeudi",
                       "2017-06-29 15:45:00", "commencer invasion")
        testExtract_fr("Lundi, commander le gâteau à la boulangerie",
                       "2017-07-03 00:00:00", "commander gâteau à boulangerie")
        testExtract_fr("Jouer la chanson Joyeux anniversaire dans 5 ans",
                       "2022-06-27 00:00:00", "jouer chanson joyeux"
                       " anniversaire")
        testExtract_fr("Skyper Maman à 12 heures 45 jeudi prochain",
                       "2017-07-06 12:45:00", "skyper maman")
        testExtract_fr("Quel temps fera-t-il jeudi prochain ?",
                       "2017-07-06 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi matin ?",
                       "2017-06-30 08:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi soir",
                       "2017-06-30 19:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il vendredi après-midi",
                       "2017-06-30 15:00:00", "quel temps fera-t-il")
        testExtract_fr("rappelle-moi d'appeler maman le 3 août",
                       "2017-08-03 00:00:00", "rappelle-moi appeler maman")
        testExtract_fr("Acheter des feux d'artifice pour le 14 juil",
                       "2017-07-14 00:00:00", "acheter feux artifice pour")
        testExtract_fr("Quel temps fera-t-il 2 semaines après vendredi",
                       "2017-07-14 00:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il mercredi à 7 heures",
                       "2017-06-28 07:00:00", "quel temps fera-t-il")
        testExtract_fr("Quel temps fera-t-il mercredi à 7 heures",
                       "2017-06-28 07:00:00", "quel temps fera-t-il")
        testExtract_fr("Prendre rendez-vous à 12:45 jeudi prochain",
                       "2017-07-06 12:45:00", "prendre rendez-vous")
        testExtract_fr("Quel temps fait-il ce jeudi ?",
                       "2017-06-29 00:00:00", "quel temps fait-il")
        testExtract_fr("Organiser une visite 2 semaines et 6 jours après"
                       " samedi",
                       "2017-07-21 00:00:00", "organiser 1 visite")
        testExtract_fr("Commencer l'invasion à 3 heures 45 jeudi",
                       "2017-06-29 03:45:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion à 20 heures jeudi",
                       "2017-06-29 20:00:00", "commencer invasion")
        testExtract_fr("Lancer la fête jeudi à 8 heures du soir",
                       "2017-06-29 20:00:00", "lancer fête")
        testExtract_fr("Commencer l'invasion à 4 heures de l'après-midi jeudi",
                       "2017-06-29 16:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à midi",
                       "2017-06-29 12:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à minuit",
                       "2017-06-29 00:00:00", "commencer invasion")
        testExtract_fr("Commencer l'invasion jeudi à dix-sept heures",
                       "2017-06-29 17:00:00", "commencer invasion")
        testExtract_fr("rappelle-moi de me réveiller dans 4 années",
                       "2021-06-27 00:00:00", "rappelle-moi me réveiller")
        testExtract_fr("rappelle-moi de me réveiller dans 4 ans et 4 jours",
                       "2021-07-01 00:00:00", "rappelle-moi me réveiller")
        testExtract_fr("Quel temps fera-t-il 3 jours après demain ?",
                       "2017-07-01 00:00:00", "quel temps fera-t-il")
        testExtract_fr("3 décembre",
                       "2017-12-03 00:00:00", "")
        testExtract_fr("retrouvons-nous à 8:00 ce soir",
                       "2017-06-27 20:00:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous demain à minuit et demi",
                       "2017-06-28 00:30:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi et quart",
                       "2017-06-27 12:15:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi moins le quart",
                       "2017-06-27 11:45:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi moins dix",
                       "2017-06-27 11:50:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à midi dix",
                       "2017-06-27 12:10:00", "retrouvons-nous")
        testExtract_fr("retrouvons-nous à minuit moins 23",
                       "2017-06-27 23:37:00", "retrouvons-nous")
        testExtract_fr("mangeons à 3 heures moins 23 minutes",
                       "2017-06-27 02:37:00", "mangeons")
        testExtract_fr("mangeons aussi à 4 heures moins le quart du matin",
                       "2017-06-27 03:45:00", "mangeons aussi")
        testExtract_fr("mangeons encore à minuit moins le quart",
                       "2017-06-27 23:45:00", "mangeons encore")
        testExtract_fr("buvons à 4 heures et quart",
                       "2017-06-27 04:15:00", "buvons")
        testExtract_fr("buvons également à 18 heures et demi",
                       "2017-06-27 18:30:00", "buvons également")
        testExtract_fr("dormons à 20 heures moins le quart",
                       "2017-06-27 19:45:00", "dormons")
        testExtract_fr("buvons le dernier verre à 10 heures moins 12 du soir",
                       "2017-06-27 21:48:00", "buvons dernier verre")
        testExtract_fr("s'échapper de l'île à 15h45",
                       "2017-06-27 15:45:00", "s'échapper île")
        testExtract_fr("s'échapper de l'île à 3h45min de l'après-midi",
                       "2017-06-27 15:45:00", "s'échapper île")
        testExtract_fr("décale donc ça à 3h48min cet après-midi",
                       "2017-06-27 15:48:00", "décale donc ça")
        testExtract_fr("construire un bunker à 9h42min du matin",
                       "2017-06-27 09:42:00", "construire 1 bunker")
        testExtract_fr("ou plutôt à 9h43 ce matin",
                       "2017-06-27 09:43:00", "ou plutôt")
        testExtract_fr("faire un feu à 8h du soir",
                       "2017-06-27 20:00:00", "faire 1 feu")
        testExtract_fr("faire la fête jusqu'à 18h cette nuit",
                       "2017-06-27 18:00:00", "faire fête jusqu'à")
        testExtract_fr("cuver jusqu'à 4h cette nuit",
                       "2017-06-27 04:00:00", "cuver jusqu'à")
        testExtract_fr("réveille-moi dans 20 secondes aujourd'hui",
                       "2017-06-27 00:00:20", "réveille-moi")
        testExtract_fr("réveille-moi dans 33 minutes",
                       "2017-06-27 00:33:00", "réveille-moi")
        testExtract_fr("tais-toi dans 12 heures et 3 minutes",
                       "2017-06-27 12:03:00", "tais-toi")
        testExtract_fr("ouvre-la dans 1 heure 3",
                       "2017-06-27 01:03:00", "ouvre-la")
        testExtract_fr("ferme-la dans 1 heure et quart",
                       "2017-06-27 01:15:00", "ferme-la")
        testExtract_fr("scelle-la dans 1 heure et demi",
                       "2017-06-27 01:30:00", "scelle-la")
        testExtract_fr("zippe-la dans 2 heures moins 12",
                       "2017-06-27 01:48:00", "zippe-la")
        testExtract_fr("soude-la dans 3 heures moins le quart",
                       "2017-06-27 02:45:00", "soude-la")
        testExtract_fr("mange la semaine prochaine",
                       "2017-07-04 00:00:00", "mange")
        testExtract_fr("bois la semaine dernière",
                       "2017-06-20 00:00:00", "bois")
        testExtract_fr("mange le mois prochain",
                       "2017-07-27 00:00:00", "mange")
        testExtract_fr("bois le mois dernier",
                       "2017-05-27 00:00:00", "bois")
        testExtract_fr("mange l'an prochain",
                       "2018-06-27 00:00:00", "mange")
        testExtract_fr("bois l'année dernière",
                       "2016-06-27 00:00:00", "bois")
        testExtract_fr("reviens à lundi dernier",
                       "2017-06-26 00:00:00", "reviens")
        testExtract_fr("capitule le 8 mai 1945",
                       "1945-05-08 00:00:00", "capitule")
        testExtract_fr("rédige le contrat 3 jours après jeudi prochain",
                       "2017-07-09 00:00:00", "rédige contrat")
        testExtract_fr("signe le contrat 2 semaines après jeudi dernier",
                       "2017-07-06 00:00:00", "signe contrat")
        testExtract_fr("lance le four dans un quart d'heure",
                       "2017-06-27 00:15:00", "lance four")
        testExtract_fr("enfourne la pizza dans une demi-heure",
                       "2017-06-27 00:30:00", "enfourne pizza")
        testExtract_fr("arrête le four dans trois quarts d'heure",
                       "2017-06-27 00:45:00", "arrête four")
        testExtract_fr("mange la pizza dans une heure",
                       "2017-06-27 01:00:00", "mange pizza")
        testExtract_fr("bois la bière dans 2h23",
                       "2017-06-27 02:23:00", "bois bière")
        testExtract_fr("faire les plantations le 3ème jour de mars",
                       "2018-03-03 00:00:00", "faire plantations")
        testExtract_fr("récolter dans 10 mois",
                       "2018-04-27 00:00:00", "récolter")
        testExtract_fr("point 6a: dans 10 mois",
                       "2018-04-27 06:00:00", "point")
        testExtract_fr("l'après-midi démissionner à 4:59",
                       "2017-06-27 16:59:00", "démissionner")
        testExtract_fr("cette nuit dormir",
                       "2017-06-27 02:00:00", "dormir")
        testExtract_fr("ranger son bureau à 1700 heures",
                       "2017-06-27 17:00:00", "ranger son bureau")

        testExtractDate2_fr("range le contrat 2 semaines après lundi",
                            "2017-07-17 00:00:00", "range contrat")
        testExtractDate2_fr("achète-toi de l'humour à 15h",
                            "2017-07-01 15:00:00", "achète-toi humour")
        # Disabling test until French Extract-date incorporates the fixes for
        # UTC / Local timezones.  Until then this test fails periodically
        # whenever test is run and the date in the local timezone (where the
        # test is being run) is a different than the date in UTC.
        #
        # testExtractNoDate_fr("tais-toi aujourd'hui",
        #                   datetime.now().strftime("%Y-%m-%d") + " 00:00:00",
        #                   "tais-toi")
        self.assertEqual(extract_datetime("", lang="fr-fr"), None)
        self.assertEqual(extract_datetime("phrase inutile", lang="fr-fr"),
                         None)
        self.assertEqual(extract_datetime(
            "apprendre à compter à 37 heures", lang="fr-fr"), None)
コード例 #39
0
 def extractWithFormat_it(text):
     date = datetime(2018, 1, 13, 13, 4)  # Sab 13 Gen, 2018 @ 13:04
     [extractedDate, leftover] = extract_datetime(text, date,
                                                  lang='it-it')
     extractedDate = extractedDate.strftime('%Y-%m-%d %H:%M:%S')
     return [extractedDate, leftover]
コード例 #40
0
ファイル: test_parse.py プロジェクト: antlarr/mycroft-core
 def extractWithFormat(text):
     date = datetime(2017, 06, 27, 00, 00)
     [extractedDate, leftover] = extract_datetime(text, date)
     extractedDate = extractedDate.strftime("%Y-%m-%d %H:%M:%S")
     return [extractedDate, leftover]
コード例 #41
0
    def handle_create_event(self):

        # Getting the credentials for G.People API
        storage = Storage('info.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid is True:
            credentials = tools.run_flow(FLOW, storage)

        http = httplib2.Http()
        http = credentials.authorize(http)

        people_service = build(serviceName='people', version='v1', http=http)

        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=10,
            personFields='emailAddresses,names').execute()
        connections = results.get('connections', [])

        # Get credentials for google calendar with [email protected]
        # and token management
        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server()
            # Save the credentials for the next run
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)

        # Getting information about the event
        title = self.get_response('what\'s the name of the new event')
        description = self.get_response('can you tell me more about it ?')
        reservation = self.get_response('do you need to make a reservation for a meeting room? Yes or No?')
        if reservation == 'yes':
            r = self.get_response('which Room do you want to make a reservation for? ')
            maxattendees = 10
            if r == "Midoun meeting room":
                room = "*****@*****.**"
            elif r == "Aiguilles Meeting Room":
                room = "*****@*****.**"
            elif r == "Barrouta Meeting Room":
                room = "*****@*****.**"
            elif r == "Kantaoui Meeting Room":
                room = "*****@*****.**"
            elif r == "Gorges Meeting Room":
                room = "*****@*****.**"
            elif r == "Ichkeul Meeting Room":
                room = "*****@*****.**"
            elif r == "Khemir Meeting Room":
                room = "*****@*****.**"
            elif r == "Tamaghza Meeting Room":
                room = "*****@*****.**"
            elif r == "Friguia Meeting Room":
                room = "*****@*****.**"
                maxattendees = 15
            elif r == "Ksour Meeting Room":
                room = "*****@*****.**"
            elif r == "Medeina Meeting Room":
                room = "*****@*****.**"
            elif r == "Thyna Meeting Room":
                room = "*****@*****.**"
        else:
            # needs to be verified !!!!!!!
            room = ""

        mr = {'email': room}
        start = self.get_response('when does it start?')
        end = self.get_response('when does it end?')
        st = extract_datetime(start)
        et = extract_datetime(end)
        invitation = self.get_response('would you like to invite an other employees to this meeting? Yes or No?')
        if invitation == 'yes':
            # getting the attendees
            atto = []
            noms = []
            f = 0
            i = 1
            g = 0
            found = False
            found2 = False
            attendees = ['blabla@blabla'] * maxattendees
            for person in connections:
                emailAddresses = person.get('emailAddresses', [])
                names = person.get('names', [])
                atto.append(emailAddresses[0].get('value'))
                noms.append(names[0].get('displayName'))
            p = len(noms)
            # first attendee
            a = self.get_response('who do you want to invite first?')
            if a != '':
                while (g != p) & (found is False):
                    # if the name in the input matches the a name in the list we add the email of that person to the
                    # attendees list which will be treated later to delete the examples '*****@*****.**'
                    if noms[g] == a:
                        attendees[0] = atto[g]
                        g = g + 1
                        found = True
                    else:
                        g = g + 1
                if found is False:
                    print('contact not found try again please')
            else:
                print('no attendees added')
            # other attendees to add less then max
            while i != maxattendees:
                a = input()
                if a == '':
                    break
                else:
                    while (f != p) | (found2 is False):
                        if noms[f] == a:
                            attendees[i] = atto[f]
                            found2 = True
                        f = f + 1
                i = i + 1
            # until this stage we have a list of attendees + blanks filled with [email protected]
            # print(attendees)
            l = len(attendees)
            # print(l)
            # in this part we are going to get the attendees without the blanks
            t = 0
            att = []
            while t != l:
                if attendees[t] != 'blabla@blabla':
                    att.append(attendees[t])
                    t = t + 1
                else:
                    t = t + 1
            l2 = len(att)
            # print(att)
            # print(l2)

            attendee = []
            for r in range(l2):
                email = {'email': att[r]}
                attendee.append(email)
            attendee.append(mr)

        # Add an event
        event = {
            'summary': title,
            'location': r,
            'description': description,
            'start': {
                'dateTime': st,
                'timeZone': 'Tunisia/Tunis',
            },
            'end': {
                'dateTime': et,
                'timeZone': 'Tunisia/Tunis',
            },
            'recurrence': [
                'RRULE:FREQ=DAILY;COUNT=2'
            ],
            'attendees': attendee,
            'reminders': {
                'useDefault': False,
                'overrides': [
                    {'method': 'email', 'minutes': 24 * 60},
                    {'method': 'popup', 'minutes': 10},
                ],
            },
        }

        event = service.events().insert(calendarId='primary', sendNotifications=True, body=event).execute()
        print
        'Event created: %s' % (event.get('htmlLink'))
        self.speak_dialog('eventAdded')