Пример #1
0
    def _get_slot_value_map(self, slotname):
        #-----------------------------------------------------------------------
        # Private  member function of class applicationslots
        # Parameters
        #  - slotname (string): name of a slot to be checked
        # Returns: (dict) a map with all the canonical/literal values for a slot
        #        - the key is the canonical
        #        - the values are all possible literals
        #        - the first value is the generic output entry
        #-----------------------------------------------------------------------
        if slotname not in self._slotdefinitions:
            myask_log.error("_get_slot_value_map: unknown slotname '" +
                            slotname + "'")
            return []
        slottype = self._slotdefinitions[slotname]

        if slottype not in self._slottypedefs:
            if slottype == "AMAZON.NUMBER":
                return [["AMAZON.NUMBER"]]
            elif slottype == "AMAZON.DE_REGION":
                return [["AMAZON.DE_REGION"]]
            elif slottype == "AMAZON.DATE":
                return [["AMAZON.DATE"]]
            elif slottype == "AMAZON.DE_FIRST_NAME":
                return [["AMAZON.DE_FIRST_NAME"]]
            else:
                myask_log.error("_get_slot_value_map: unknown slottype '" +
                                slottype + "' found for slot '" + slotname +
                                "'")
                return [[]]

        return self._slottypedefs[slottype]
Пример #2
0
    def GetSlotOutputName(self, slotname, canonical):
        #-----------------------------------------------------------------------
        #  Public member function of class applicationslots
        # Parameters
        #  - slotname (string): name of the slot
        #  - canonical (string): normalized internal identifier for a slot value
        # Returns: (string) generic (spekable) output name for the canonical value
        #              if the value cannot be mapped, return canonical
        #-----------------------------------------------------------------------
        slotmap = self._get_slot_value_map(slotname)
        if len(slotmap) == 0:
            myask_log.error("GetSlotOuputName: No slotmap found for slot'" +
                            slotname + "' using canonical '" + canonical + "'")
            return canonical
        elif len(slotmap) == 1 and slotmap[0][0].startswith("AMAZON"):
            return canonical

        for entry in slotmap:
            if len(entry) < 2:
                myask_log.error(
                    "gen_GetOuputName: incorrect format for dictionary entry '"
                    + str(entry) + "'")
                return "ERROR"
            if entry[0].lower() == str(canonical).lower():  # we got a match
                return entry[1][0]

        # if we are here, we did not find a match
        myask_log.warning("GetOuputName: No match found for'" +
                          str(canonical) + "'")
        return canonical
Пример #3
0
 def GetValueLiterals(self, slotname, value):
     #-----------------------------------------------------------------------
     #  Public member function of class applicationslots
     # Returns a list of all possible literals for a given slot canonical
     # Parameters
     #  'slotname' name of the slot under investigation
     #  'value' canonical value
     # Returns: list of all registered literal for the given canonical as array of strings
     # if the slotname is not known or does not have a custom list , returns []
     #-----------------------------------------------------------------------
     slotmap = self._get_slot_value_map(slotname)
     if len(slotmap) == 0:
         myask_log.error("GetSlotCanonical: no slotmap found for slot'" +
                         slotname + "'")
         return []
     elif len(slotmap) == 1 and slotmap[0][0].startswith("AMAZON"):
         return []
     #OK, let's look for the canonical value
     for entry in slotmap:
         if len(entry) < 2:
             myask_log.error(
                 "gen_GetOuputName: incorrect format for dictionary entry '"
                 + str(entry) + "'")
             return []
         if entry[0] == value:
             return entry[1]
Пример #4
0
 def FetchUserProfile(self, userid):
     #-----------------------------------------------------------------------
     # returns the "profile" part of a given user profile
     # if the user profile does not exist, profile is {}
     #-----------------------------------------------------------------------
     if self._table == "": 
         myask_log.error("fetchUserProfile: attempted without valid table")
         return {}
     try:
         response = self._table.get_item(Key={'UserID': userid})
     except ClientError as e:
         myask_log.error("fetchUserProfile: Error: "+e.response['Error']['Message'])
         return {}
     else:
         if 'Item' in response:
             if 'Item' in response and 'Profile' in response['Item']:
                 profile = response['Item']['Profile']
                 if 'debuguser' in response['Item']:
                     myask_log.debug(5, "DEBUGUSER: '******'Item']['debuguser']) +"'")
                     profile['debuguser'] = response['Item']['debuguser']
                 myask_log.debug(5,"fetchUserProfile: User profile found:"+ str(userid))
                 # update access log for this user profile
                 self._touchProfile(userid)
                 return profile
             else :
                 myask_log.debug(5,"fetchUserProfile: Invalid response format: "+ str(response))
                 return {}
         else:
             myask_log.debug(5,"fetchUserProfile: User profile NOT found:"+ str(userid))
             return {}
Пример #5
0
def readAmazonDate(date_str):
    #check for exact date e.g. 2015-11-25.
    if re.match("\d\d\d\d-\d\d-\d\d$", date_str): 
        start_date = datetime.strptime(date_str, "%Y-%m-%d").date()
        duration = 1
    #check for weekend e.g. 2015-W49-WE
    elif re.match("\d\d\d\d-W\d\d-WE$", date_str): 
        tmp_str = date_str[:-3]
        tmp_str = tmp_str+ ":6"
        start_date = datetime.strptime(tmp_str, "%Y-W%W:%w").date()
        duration = 2
    #check for week e.g. 2015-W49
    elif re.match("\d\d\d\d-W\d+$", date_str): 
        tmp_str= date_str+":0"
        start_date = datetime.strptime(tmp_str, "%Y-W%W:%w").date()
        duration = 7
    #check for month e.g. 2015-12
    elif re.match("\d\d\d\d-\d+$", date_str): 
        tmp_str= date_str +"-01"
        start_date = datetime.strptime(tmp_str, "%Y-%m-%d").date()
        duration = 30
    #check for year e.g. 2015
    elif re.match("\d\d\d\d$", date_str): 
        tmp_str= date_str+"-01-01"
        start_date = datetime.strptime(tmp_str, "%Y-%m-%d").date()
        duration = 365
    #handle unknown dates
    else:
        myask_log.error(" unknown date format '" + date_str +"'")
        start_date = date.today() 
        duration = CONST_UNDEF_DURATION
    return (start_date, duration)
Пример #6
0
    def isBuiltinType(self, slotname):
        #----------------------------------------------------------------------
        # returns True if the slot 'slotname' is of a built-in type
        # (starting with 'AMAZON'
        #----------------------------------------------------------------------

        if slotname not in self._slotdefinitions:
            myask_log.error("getSlottype: unknown slotname '" + slotname + "'")
            return False
        return str(self._slotdefinitions[slotname]).startswith("AMAZON.")
Пример #7
0
 def getSlottype(self, slotname):
     #-----------------------------------------------------------------------
     #  Public member function of class applicationslots
     # Parameters
     #  - slotname (string): name of a slot to be checked
     # Returns: (string) Type of the slot or "" if not defined
     #-----------------------------------------------------------------------
     if slotname not in self._slotdefinitions:
         myask_log.error("getSlottype: unknown slotname '" + slotname + "'")
         return ""
     return self._slotdefinitions[slotname]
Пример #8
0
def checkslots(slots, checklist, functionname):
#-------------------------------------------------------------------------------
# checks if all slots in checklist are contained in the slots data structure
# returns False and prints an error message if not
    
    for check in checklist:
        if check not in slots:
            myask_log.error ("ERROR in function "+ functionname+ ": missing slot '" + check + "' in slotlist \n" +\
                  "Slots: "+ str(slots) + "\n")
            return False
    return True
Пример #9
0
 def DeleteUserProfile(self, userid):
     #----------------------------------------------------------------------
     # delete a specific user profile from the table
     #----------------------------------------------------------------------
     
     try:
         self._table.delete_item(Key={'UserID': userid})
     except ClientError as e:
         myask_log.error("DeleteUserProfile: Error: "+e.response['Error']['Message'])
         return False
     else:
         print("DeleteItem succeeded")
         return True
Пример #10
0
 def GetExistingOneTimeCode(self,userid):
     if self._table == "": 
         myask_log.error("GetStatistics: attempted without valid table")
     try:
         response = self._table.get_item(Key={'UserID': userid})
     except ClientError as e:
         myask_log.error("GetStatistics: Error: "+e.response['Error']['Message'])
     else:
         if 'Item' in response:
             if 'access_code' in response['Item']: 
                 code = response['Item']['access_code']
                 if code != "": return code
                 
     return ""
Пример #11
0
def SetDbType(dbtype, resource=""):
    global DBTYPE
    global DBRESOURCE
    
    myask_log.debug(3, "myadk_dynamodb.SetDbType: dbtype='"+dbtype+"' resource='"+resource+"'")
    DBRESOURCE = resource
    if dbtype == "online": # use dynamo online db
        DBTYPE = "online"
        return True
    elif dbtype == "offline": # use dynamo  db installed locally
        DBTYPE = "offline"
        return True
    else:
        myask_log.error("myadk_dynamodb.SetDbType: invalid dbtype '"+dbtype+"'")
        return False
Пример #12
0
    def UpdateUserProfile(self, userid, profile):
        #-----------------------------------------------------------------------
        # Updates an existing user profile with the information in "profile"
        # If the user profile does not exist or cannot beupdated, returns False
        #-----------------------------------------------------------------------
        try:
            response = self._table.update_item(
                            Key={'UserID': userid},
                            UpdateExpression="set Profile = :p",
                            ExpressionAttributeValues = {':p':  profile},
                            ReturnValues="UPDATED_NEW")
        except ClientError as e:
            myask_log.error("UpdateUserProfile: Error: "+e.response['Error']['Message'])
            return False
        else:
            myask_log.debug(2, "UpdateUserProfile: " + str(response))

        return True
Пример #13
0
    def IsValidSlotCanonical(self, slotname, value):
        slotmap = self._get_slot_value_map(slotname)
        if len(slotmap) == 0:
            myask_log.error("GetSlotCanonical: no slotmap found for slot'" +
                            slotname + "'")
            return False
        elif len(slotmap) == 1 and slotmap[0][0].startswith("AMAZON"):
            return True
        #OK, let's look for the canonical value
        for entry in slotmap:
            if len(entry) < 2:
                myask_log.error(
                    "gen_GetOuputName: incorrect format for dictionary entry '"
                    + str(entry) + "'")
                return "?"
            if entry[0] == value:
                return True

        return False
Пример #14
0
    def GetStatistics(self, userid):
        created = ""
        num_queries = -1
        last_query = ""
        
        if self._table == "": 
            myask_log.error("GetStatistics: attempted without valid table")
        try:
            response = self._table.get_item(Key={'UserID': userid})
        except ClientError as e:
            myask_log.error("GetStatistics: Error: "+e.response['Error']['Message'])
        else:
            if 'Item' in response:
                if 'Created' in response['Item']: created = response['Item']['Created']
                if 'NumQueries' in response['Item']: num_queries = response['Item']['NumQueries']
                if 'LastQuery' in response['Item']: last_query = response['Item']['LastQuery']
            else:
                myask_log.debug(5,"GetStatistics: User profile NOT found:"+ str(userid))

        return [created,num_queries,last_query]
Пример #15
0
    def GenerateOneTimeCode(self,userid):
        #-----------------------------------------------------------------------
        # Creates a one-time passcode (6-digit number) that allows to 
        # access the user profile on dynamodb.
        # The function stores the code in the dynamodb database.
        # A Web service uses the one-time code to access the database.
        # Once the code has been used, the web client should remove it from 
        # the database
        #-----------------------------------------------------------------------
        myask_log.debug(10, "GenerateOneTimeCode: called for user '"+userid+"'")
        
        # check if user profile entry exists
        if self._table == "": 
            myask_log.error("GetStatistics: attempted without valid table")
        try:
            response = self._table.get_item(Key={'UserID': userid})
        except ClientError as e:
            myask_log.error("GetStatistics: Error: "+e.response['Error']['Message'])
        else:
            if 'Item' in response: # profile exists
                myask_log.debug(10, "GenerateOneTimeCode: Item found for user '"+userid+"'")
                if 'access_code' in response['Item']: 
                    existing_code = response['Item']['access_code']
                    myask_log.debug(10, "GenerateOneTimeCode: Existing code "+str(existing_code)+"  found for user '"+userid+"' reusing")
                    if existing_code != "": return existing_code
            else: # profile does not exist
                myask_log.debug(10, "GenerateOneTimeCode: Creating new user entry")
                self.CreateNewUserProfile(userid, {})
    
        #now create a random code that is not yet used
        count = 1 # just to have something with len >0
        while (count != 0):
            code = random.randint(100000,999999)
            myask_log.debug(9, "Checking if code is unique: "+str(code))
            # check if code number is already in use
            response = self._table.query(
                IndexName='access_code-index',
                KeyConditionExpression=Key('access_code').eq(str(code))
            )        
            if 'Count' in response: count = response['Count']
            else: count = 0
        # store code number in user profile
        try:
            response = self._table.update_item(
                            Key={'UserID': userid},
                            UpdateExpression="set access_code = :p, code_created = :t",
                            ExpressionAttributeValues = {
                                ':p':  str(code),
                                ':t' : get_date_str()
                                },
                            ReturnValues="UPDATED_NEW")
        except ClientError as e:
            myask_log.error("UpdateUserProfile: Error: "+e.response['Error']['Message'])
            return 0
        else:
            myask_log.debug(2, "Added code: " + str(code)+ " to user profile")

        return code
Пример #16
0
def readMyYear(date_canon):
    this_year =  int(date.today().strftime("%Y"))
    
    # translates a canonicalized relative date into a date + duration information
    if(date_canon =="?"):
        myask_log.warning("undefined relative date canonical '?'. Using current date")
        year = this_year
    elif  (date_canon =="THIS_YEAR"):
        year = this_year
    elif(date_canon =="NEXT_YEAR"):
        year = this_year+1
    elif(date_canon =="TWO_YEARS"):
        year = this_year+2     
    elif(re.match("\d\d\d\d$", date_canon)): 
        year = date_canon       
    else:
        myask_log.error("invalid relative date canonical '"+date_canon+"'")
        year = this_year

    tmp_str= str(year)+"-01-01"
    start_date = datetime.strptime(tmp_str, "%Y-%m-%d").date()
    duration = 365     
    return (start_date, duration)
Пример #17
0
    def GetSlotCanonical(self, slotname, literal, strict=False):
        #-----------------------------------------------------------------------
        #  Public member function of class applicationslots
        # Parameters
        #  - slotname (string): name of the slot
        #  - literal (string):slot value as spoken by the user
        #  - strict If True, '?' is returned if no match was found
        # Returns: (string) canonical, i.e. normalized internal identifier for a slot value
        #              if the value cannot be mapped, and strict is False, return literal
        #-----------------------------------------------------------------------
        slotmap = self._get_slot_value_map(slotname)
        if len(slotmap) == 0:
            myask_log.error("GetSlotCanonical: no slotmap found for slot'" +
                            slotname + "'")
            return literal
        elif len(slotmap) == 1 and slotmap[0][0].startswith("AMAZON"):
            return literal

        #OK, let's look for the canonical value
        literal = literal.lower()
        literal.encode("utf-8")
        for entry in slotmap:
            if len(entry) < 2:
                myask_log.error(
                    "gen_GetOuputName: incorrect format for dictionary entry '"
                    + str(entry) + "'")
                return "?"
            for value in entry[1]:
                value = value.lower()
                value.encode("utf-8")
                if value == literal:
                    return entry[0]

        myask_log.warning("GetSlotCanonical: No match found for'" + literal +
                          "'")
        if strict == True: return "?"
        else: return literal
Пример #18
0
def createSampleUtterancesFromGrammar(inputfile):
    #---------------------------------------------------------------------------
    # reads a generation grammar from 'iputfile' and returns
    # an array of sample utterances created from that grammar
    #---------------------------------------------------------------------------
    input_utterances = {}
    non_terminal_list = {}
    #    fin = codecs.open(inputfile, "r", "utf-8")
    fin = open(inputfile, "r")
    content = fin.readlines()

    # --------------------------------------------------------------------------
    # 1st step: parse input file
    # parse the input file and create
    # a dictionary of non-terminals (non_terminal_list)
    # a list of input utterances (input_utterances)
    # --------------------------------------------------------------------------

    linecount = 0
    myask_log.debug(3, "---->>>Parsing input file" + inputfile)
    for line in content:
        linecount += 1
        line = StripComments(line)

        if re.match("^\s*$", line):
            continue

        blocks = re.match("^\s*(.*)\s*::=\s*(.*)$", line)
        if blocks:
            leftside = blocks.group(1)
            leftside = leftside.strip()
            rightside = blocks.group(2)
            rightside = rightside.strip()
        else:
            myask_log.error("Invalid Syntax in line '" + line + "'")
            return ()

        if re.match("<.*>", leftside):  # non terminal rule found
            myask_log.debug(
                7, "NON-TERMINAL '" + leftside + "' found in line " +
                str(linecount))
            AddNonterminalRule(leftside, rightside, non_terminal_list)
        else:
            AddIntentRule(leftside, rightside, input_utterances)

    myask_log.debug(3,
                    "---->>>Parsing done. " + str(linecount) + " lines read")
    fin.close()

    # --------------------------------------------------------------------------
    # 1nd step: create all possible output sentence
    # loop over all input utterances
    # For each inout utterance, create variants for all possible (combinations of)
    # non-terminal symbols and optional phrases
    # --------------------------------------------------------------------------
    training_corpus = {}
    linecount = 0
    for intent in input_utterances:
        training_corpus[intent] = []
        for input_sentence in input_utterances[intent]:
            linecount += 1
            myask_log.debug(
                3, "Processing line (" + intent + ") '" + str(input_sentence) +
                "'")
            input_words = input_sentence.split(" ")
            line_alternatives = ProcessLine(input_words, non_terminal_list)
            for training_sentence in line_alternatives:
                myask_log.debug(5, "-> " + training_sentence)
            training_corpus[intent].extend(line_alternatives)

    return training_corpus
Пример #19
0
def main():
    myask_log.error("This module does not offer command line functionality")
Пример #20
0
def parse_slots(intent, session, continue_session, input_locale, appdef):
    #---------------------------------------------------------------------------
    # parse the slots from the intent structure 
    # and combine it with the session attributes if requested
    # PARAMETERS:
    # - intent: Alexa intent structure including 'slots' data 
    # - session: Alexa session structure, including 'attributes' data
    # - continue_session: If True,session_attributes are used 
    # - input_locale: used to set locale and language correctly
    # - appdef
    # RETURN:
    # data structure with all application slots.
    # slots are provided as canonicals with an additional SLOTNAME.literal field
    #---------------------------------------------------------------------------
    slots = {}
    if input_locale in ["de-DE", "deu_deu"] : 
        lang = "de-DE"
        utc_offset = 1
    else:
        myask_log.error("Unsupported input locale '"+ input_locale +"'")
        lang = input_locale
        utc_offset = 0

    slots['lang'] = lang
    slots['utc_offset'] = utc_offset

    if continue_session == True: 
        if  'attributes' in session: 
            myask_log.debug(3, "SESSION_ATTRIBUTES: "+ str(session) )    
            session_attributes = session['attributes']
            for sessionslot in session_attributes:
                if re.match("DATE:\d\d\d\d-\d+-\d+$", session_attributes[sessionslot]): 
                    tmp_str= session_attributes[sessionslot]
                    slots[sessionslot] = datetime.strptime(tmp_str, "DATE:%Y-%m-%d").date()
                else: slots[sessionslot] = session_attributes[sessionslot]
        else:
            myask_log.error("SESSION_ATTRIBUTES: ERROR NO ATTRIBUTES FOUND \n"+ str(session) +"\nEND_SESSION_ATTRIBUTES")

    if 'slots' in intent:        
        for inputslot in intent['slots']:
            if 'value' not in intent['slots'][inputslot]:
                continue
            if appdef.isApplicationSlot(inputslot):
                literal = intent['slots'][inputslot]['value']
                if appdef.getSlottype(inputslot) == "MY_RELATIVE_DATE": 
                    canonical_date = appdef.GetSlotCanonical(inputslot,literal, strict=True)              
                    (slots[inputslot],slots[inputslot+'.duration']) = readMyRelativeDate(canonical_date)
                    slots[inputslot+'.literal'] = literal
                elif appdef.getSlottype(inputslot) == "MY_YEARS": 
                    canonical_date = appdef.GetSlotCanonical(inputslot,literal, strict=True)              
                    (slots[inputslot],slots[inputslot+'.duration']) = readMyYear(canonical_date)
                    slots[inputslot+'.literal'] = literal
                elif appdef.getSlottype(inputslot) == "AMAZON.DATE":                
                    (slots[inputslot],slots[inputslot+'.duration']) = readAmazonDate(literal)
                    slots[inputslot+'.literal'] = literal
                elif appdef.getSlottype(inputslot) == "AMAZON.NUMBER":
                    slots[inputslot] = literal
                elif appdef.getSlottype(inputslot) == "AMAZON.DE_FIRST_NAME":
                    slots[inputslot] = literal
                else:
                    slots[inputslot] = appdef.GetSlotCanonical(inputslot,literal, strict=True)
                    slots[inputslot+".literal"] = literal
    else:
        myask_log.debug(2, "No slots section found")
    myask_log.debug(5, "SLOTS: "+ str(slots))    
    return slots
Пример #21
0
def error_slots_missing(function_name):
    myask_log.error("Slot missing in function " + function_name)
    return "ERROR: Sorry, da fehlt irgendeine Information in " + function_name
Пример #22
0
def readMyRelativeDate(date_canon):
    today =  date.today()
    # translates a canonicalized relative date into a date + duration information
    if(date_canon =="?"):
        myask_log.warning("undefined relative date canonical '?'. Using current date")
        start_date = today
        duration = CONST_UNDEF_DURATION
    elif  (date_canon =="TODAY"):
        start_date = today
        duration = 1       
    elif(date_canon =="TOMORROW"):
        start_date = today + timedelta(1)
        duration = 1       
    elif(date_canon =="DAY_AFTER_TOMORROW"):
        start_date = today+ timedelta(2)
        duration = 1       
    elif(date_canon =="THIS_WEEK"):
        # define this week as today + <= 7days
        start_date = today
        duration = 7       
    elif(date_canon =="NEXT_WEEK"):
        # return next sunday +- 1 week later
        start_date = this_weekday(today, 0)
        duration = 7               
    elif(date_canon =="WEEK_AFTER_NEXT"):
        # return next sunday+7 +- 1 week later
        start_date = this_weekday(today+timedelta(7), 0)
        duration = 7               
    elif(date_canon =="MONDAY"):
        start_date = this_weekday(today, 0)
        duration = 1               
    elif(date_canon =="TUESDAY"):
        start_date = this_weekday(today, 1)
        duration = 1               
    elif(date_canon =="WEDNESDAY"):
        start_date = this_weekday(today, 2)
        duration = 1               
    elif(date_canon =="THURSDAY"):
        start_date = this_weekday(today, 3)
        duration = 1               
    elif(date_canon =="FRIDAY"):
        start_date = this_weekday(today, 4)
        duration = 1               
    elif(date_canon =="SATURDAY"):
        start_date = this_weekday(today, 5)
        duration = 1               
    elif(date_canon =="SUNDAY"):
        start_date = this_weekday(today, 6)
        duration = 1               
    elif(date_canon =="NEXT_MONDAY"):
        start_date = next_weekday(today, 0)
        duration = 1               
    elif(date_canon =="NEXT_TUESDAY"):
        start_date = next_weekday(today, 1)
        duration = 1               
    elif(date_canon =="NEXT_WEDNESDAY"):
        start_date = next_weekday(today, 2)
        duration = 1               
    elif(date_canon =="NEXT_THURSDAY"):
        start_date = next_weekday(today, 3)
        duration = 1               
    elif(date_canon =="NEXT_FRIDAY"):
        start_date = next_weekday(today, 4)
        duration = 1               
    elif(date_canon =="NEXT_SATURDAY"):
        start_date = next_weekday(today, 5)
        duration = 1               
    elif(date_canon =="NEXT_SUNDAY"):
        start_date = next_weekday(today, 6)
        duration = 1               
    elif(date_canon =="MONDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 0)
        duration = 1               
    elif(date_canon =="TUESDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 1)
        duration = 1               
    elif(date_canon =="WEDNESDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 2)
        duration = 1               
    elif(date_canon =="THURSDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 3)
        duration = 1               
    elif(date_canon =="FRIDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 4)
        duration = 1               
    elif(date_canon =="SATURDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 5)
        duration = 1               
    elif(date_canon =="SUNDAY_NEXTWEEK"):
        start_date = weekday_nextweek(today, 6)
        duration = 1               
    elif(date_canon =="MONTH_JAN"):
        start_date = get_startofmonth(1)
        duration = 31               
    elif(date_canon =="MONTH_FEB"):
        start_date = get_startofmonth(2)
        duration = 29               
    elif(date_canon =="MONTH_MAR"):
        start_date = get_startofmonth(3)
        duration = 31               
    elif(date_canon =="MONTH_APR"):
        start_date = get_startofmonth(4)
        duration = 30               
    elif(date_canon =="MONTH_MAY"):
        start_date = get_startofmonth(5)
        duration = 31               
    elif(date_canon =="MONTH_JUN"):
        start_date = get_startofmonth(6)
        duration = 30               
    elif(date_canon =="MONTH_JUL"):
        start_date = get_startofmonth(7)
        duration = 31               
    elif(date_canon =="MONTH_AUG"):
        start_date = get_startofmonth(8)
        duration = 31               
    elif(date_canon =="MONTH_SEP"):
        start_date = get_startofmonth(9)
        duration = 30               
    elif(date_canon =="MONTH_OCT"):
        start_date = get_startofmonth(10)
        duration = 31               
    elif(date_canon =="MONTH_NOV"):
        start_date = get_startofmonth(11)
        duration = 30              
    elif(date_canon =="MONTH_DEC"):
        start_date = get_startofmonth(12)
        duration = 31               
    else:
        myask_log.error("invalid relative date canonical '"+date_canon+"'")
        start_date = date.today() 
        duration = CONST_UNDEF_DURATION
     
    return (start_date, duration)
Пример #23
0
def main():
    # parse command line options
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbosity", type=int,
                        help="define output verbosity")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-create", "--create_table", action="store_true",
                        help="Creates new database table")
    group.add_argument("-scan", "--scan_items", action="store_true",
                        help="Prints summary of complete scan of profiles")
    group.add_argument("-get", "--get_item", type=str,
                        help="Returns profile for given user ID")
    group.add_argument("-stat", "--item_statistics", type=str,
                        help="Returns access statistics for given user ID")
    group.add_argument("-add", "--add_item", type=str,
                        help="Add item with given ID to the database")
    group.add_argument("-upd", "--update_item", type=str,
                        help="Update item with given ID in the database")
    group.add_argument("-del", "--delete_item", type=str,
                        help="Delete item with given ID from the database")
    parser.add_argument("-profile", "--Profile_JSON_FILE", type=str, 
                        help="JSON file with user profile structure")
    parser.add_argument("-offline", "--offline_port", type=int, 
                        help="Use local database on the given port on localhost")
    parser.add_argument("table", help="database table name")

    args = parser.parse_args()    
    
    if  args.table: tablename = args.table
    else: tablename = "TABLE"
    

    if args.verbosity:
        myask_log.SetDebugLevel(args.verbosity)
        
    if args.offline_port:
        offline_endpoint  = "http://localhost:"+str(args.offline_port)
        SetDbType("offline", offline_endpoint)
        
    if args.create_table:
        CreateNewTable(tablename)    
    else:
        databasetable = dynamoDB(tablename)
        if args.scan_items:
            myask_log.debug(5, "Printing statistics")
            databasetable.ScanAllProfiles(["source"])
        elif args.get_item:
            user_id = str(args.get_item)
            myask_log.debug(5, "Fetching item '"+user_id+"'")
            profile = databasetable.FetchUserProfile(user_id)
            print("Profile for user "+user_id+":")
            print(profile)
        elif args.item_statistics:
            user_id = str(args.item_statistics)
            (created,num_queries,last_query) =  databasetable.GetStatistics(user_id)
            print ("Created    : "+created)
            print ("Last Query : "+last_query)
            print ("Num queries: "+str(num_queries))
        elif args.add_item:
            user_id = str(args.add_item)
            myask_log.debug(5, "Adding new item '"+str(user_id)+"'")
            if args.Profile_JSON_FILE:
                profile = readJsonProfileFromFile(args.Profile_JSON_FILE)
            else:
                profile = {}
            databasetable.CreateNewUserProfile(user_id, profile)
        elif args.update_item:
            user_id = str(args.update_item)
            myask_log.debug(5, "Updating item '"+str(user_id)+"'")
            if args.Profile_JSON_FILE:
                profile = readJsonProfileFromFile(args.Profile_JSON_FILE)
            else:
                profile = {}
            databasetable.UpdateUserProfile(user_id, profile)
        elif args.delete_item:
            user_id = str(args.delete_item)
            myask_log.debug(5, "Deleting item '"+user_id+"'")
            databasetable.DeleteUserProfile(user_id)
        else:
            myask_log.error("Missing command")
            parser.print_help()
Пример #24
0
    def getRandomResponse(self, intentlist):
        #-----------------------------------------------------------------------
        # returns a random input for one of the intents in the intent list
        # if the intentlist is emty any intent can be TestActionsReturned
        # the response consists of a data structure that represents the
        # 'intents' part of a Alexa resonse, e.g.
        #  "intent": {
        #               "name": "NextBus",
        #               "slots": {
        #                  "Destination": {
        #                     "name": "Destination",
        #                     "value": "elisenbrunnen"
        #                   },
        #                   "Buslinie": {
        #                      "name": "Buslinie"
        #                   },
        #               }
        #           }

        # select random slot
        resulstructure = {}
        if len(intentlist
               ) == 0 or intentlist[0] == "*":  # select from all slots
            intentname = random.choice(self._intentdef.keys())
        else:  # select from the list
            intentname = random.choice(intentlist)
        myask_log.debug(5, "Intent: " + intentname)
        resulstructure["name"] = intentname
        if intentname not in self._intentdef:
            myask_log.error("Invalid random intent name '" + intentname + "'")
            return resulstructure

        slotlist = self._intentdef[intentname]
        slotstructure = {}
        #now loop over all slots forr this intent and decide if we assign a value and which one
        for slotname in slotlist:
            slotstructure[slotname] = {}
            slotstructure[slotname]['name'] = slotname
            # decide if we assign a value to this slot or not
            if random.choice([True, False]) == False:  # no value for this slot
                # append it as empty value
                myask_log.debug(5,
                                "Slot '" + slotname + "' does not get a value")
            else:  # we want to get a random value for this slot
                # append it as em
                slottype = self.getSlottype(slotname)
                if str(slottype).startswith("AMAZON"):
                    # Amazon internal slot
                    if slottype == "AMAZON.NUMBER":
                        slotvalue = 47
                        literal = str(slotvalue)
                    elif slottype == "AMAZON.DATE":
                        slotvalue = datetime.today()
                        literal = slotvalue.strftime('%Y-%m-%d')
                    elif slottype == "AMAZON.DE_REGION":
                        literal = random.choice(["nrw", "bayern"])
                    elif slottype == "AMAZON.DE_FIRST_NAME":
                        literal = random.choice([
                            "Katharina", "Konstantin", "Karina", "?",
                            "friedhelm"
                        ])
                    else:
                        myask_log.error("_getRandomRespons: Built-in type " +
                                        str(slottype) + " not yet handled")
                        literal = "UNKNOWN_AMAZON_TYPE"
                else:  # custom type
                    if slottype not in self._slottypedefs:
                        myask_log.error(
                            "_getRandomRespons: no slot definition found for slot "
                            + str(slottype))
                        literal = "UNKNOWN_USER_TYPE"
                    else:
                        slotvalue_list = self._slottypedefs[slottype]
                        slotvalue = random.choice(slotvalue_list)
                        # ok, we got the vlaue (literal,canonicals, let's pick a literal
                        literal_list = slotvalue[1]
                        literal = unicode(random.choice(literal_list))

                slotstructure[slotname]['value'] = literal
                myask_log.debug(
                    5, "Using value' " + literal + "' for slot '" + slotname +
                    "'")

        resulstructure["slots"] = slotstructure
        return resulstructure
Пример #25
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v",
                        "--verbosity",
                        type=int,
                        help="define output verbosity")

    parser.add_argument("-out",
                        "--outputfile_root",
                        type=str,
                        help="basename for output files")
    parser.add_argument("inputfile", help="grammar file as input")

    args = parser.parse_args()

    if args.verbosity:
        myask_log.SetDebugLevel(args.verbosity)

    if args.inputfile: inputfile = args.inputfile
    else: inputfile = "input.py"  # dummy, we will never get here

    if inputfile.endswith('.py'):
        inputfile = inputfile[:-3]
    else:
        myask_log.error(
            "application definition file muyst end with #.py'. Got " +
            inputfile + "'")
        return

    if args.outputfile_root: output_root = args.outputfile_root
    else: output_root = ""

    # now import the application definition from that file
    try:
        appdef_module = __import__(inputfile)
    except ImportError:
        # Display error message
        myask_log.error("Could not import appdef file '" + inputfile + "'")
    else:
        myask_log.debug(
            3, "Application definition importet from '" + inputfile + ".py'")

        myask_log.debug(5, "Initializing application definition")

        appdef = applicationdef(appdef_module.APPNAME, appdef_module.APPID,
                                appdef_module.INTENTS, appdef_module.SLOTS,
                                appdef_module.SLOTTYPES)

        myask_log.debug(5, "Creating ASK intent structure")
        intent_json = appdef.CreateIntentDef()

        if output_root == "":
            # print to standard outpt
            print(
                "=======BEGIN INTENT DEF=====================================\n\n"
            )
            print intent_json
            print(
                "\n=======END INTENT DEF=====================================\n\n"
            )
        else:
            intentfile = output_root + "_intentstruct_generated.js"
            myask_log.debug(
                3, "Writing intent structure to file '" + intentfile + "'")
            intentout = open(intentfile, 'w+')
            intentout.write(intent_json)
            intentout.close()

        typeinfo = appdef.GetAllSlotLiterals()
        if output_root == "":
            # print to standard outpt
            print(
                "=======BEGIN CUSTOM_TYPE DEFINITIONS========================\n\n"
            )
            for (slottype, slotliterals) in typeinfo:
                print("\n--- " + slottype + " ---")
                for literal in slotliterals:
                    print literal
            print(
                "\n=======END CUSTOM_TYPE DEFINITIONS========================\n\n"
            )
        else:
            typefile = output_root + "_customtypes_generated.txt"
            myask_log.debug(
                3, "Writing custom data type definitions to file '" +
                typefile + "'")
            typeout = open(typefile, 'w+')
            for (slottype, slotliterals) in typeinfo:
                typeout.write("\n--- " + slottype + " ---\n")
                for literal in slotliterals:
                    typeout.write(literal.encode('utf8') + "\n")

            typeout.close()
            myask_log.debug(3, "Done")