Пример #1
0
 class Model(optplan.ProblemGraphNode):
     type = types.StringType(default="Model")
     value = types.DictType(types.ModelType(ModelB))
Пример #2
0
class Media(models.Model):
    """ Wrapper for Wistia Media results """

    id = types.IntType(
        required=True,
        metadata=dict(
            description="A unique numeric identifier for the media within the system."
        ),
    )
    name = types.StringType(
        required=True, metadata=dict(description="The display name of the media.")
    )
    hashed_id = types.StringType(
        required=True,
        metadata=dict(description="A unique alphanumeric identifier for this media."),
    )
    description = types.StringType(
        required=True,
        metadata=dict(
            description=(
                "A description for the media which usually appears near the top of the"
                "sidebar on the media’s page"
            )
        ),
    )
    project = types.ModelType(
        ProjectReference,
        required=False,
        metadata=dict(
            description="Information about the project in which the media resides"
        ),
    )
    type = types.StringType(
        required=True,
        metadata=dict(description="A string representing what type of media this is"),
        choices=[
            "Video",
            "Image",
            "Audio",
            "Swf",
            "MicrosoftOfficeDocument",
            "PdfDocument",
            "UnknownType",
        ],
    )
    status = types.StringType(
        required=True,
        default="ready",
        metadata=dict(description="Post upload processing status"),
        choices=["queued", "processing", "ready", "failed"],
    )
    progress = types.FloatType(
        required=False,
        default=1.0,
        metadata=dict(
            description=(
                "(optional) After a file has been uploaded to Wistia, it needs to be"
                "processed before it is available for online viewing. This field is"
                "a floating point value between 0 and 1 that indicates the progress of"
                "that processing."
            )
        ),
    )
    section = types.StringType(
        required=False,
        serialize_when_none=False,
        metadata=dict(
            description=(
                "(optional) The title of the section in which the media appears."
                "This attribute is omitted if the media is not in a section (default)."
            )
        ),
    )
    thumbnail = types.ModelType(
        Thumbnail,
        required=True,
        metadata=dict(
            description="An object representing the thumbnail for this media"
        ),
    )
    duration = types.FloatType(
        required=False,
        metadata=dict(
            description=(
                "(optional) For Audio or Video files, this field specifies the length"
                "(in seconds). For Document files, this field specifies the number of"
                "pages in the document. For other types of media, or if the duration"
                "is unknown, this field is omitted."
            )
        ),
    )
    created = types.DateTimeType(
        required=True,
        serialized_format=DATETIME_FORMAT,
        metadata=dict(description="The date when the media was originally uploaded."),
    )
    updated = types.DateTimeType(
        required=True,
        serialized_format=DATETIME_FORMAT,
        metadata=dict(description="The date when the media was last changed."),
    )
    assets = types.ListType(
        types.ModelType(Asset),
        required=False,
        metadata=dict(description="An array of the assets available for this media"),
    )
    embed_code = types.StringType(
        serialized_name="embedCode",
        required=False,
        metadata=dict(
            description=r"""
            DEPRECATED
            The HTML code that would be used for embedding the media into a web page.
            Please note that in JSON format, all quotes are escaped with a
            backslash (\) character. In XML, angle brackets (< and >) and
            ampersands (&) are converted to their equivalent XML entities
            ("&lt;", "&gt;", and "&amp;" respectively) to prevent XML parser errors.
            """
        ),
    )
Пример #3
0
 class Model(optplan.ProblemGraphNode.Schema):
     type = types.StringType(default="Model")
     value = types.ListType(types.ModelType(ModelB))
Пример #4
0
class CurrentIntentProperty(PyLexObject):
    name = types.StringType()
    slots = types.DictType(types.StringType())
    slotDetails = types.DictType(types.ModelType(SlotDetailValueProperty))
    confirmationStatus = types.StringType()
Пример #5
0
class Project(models.Model):
    """Wrapper for project results."""

    id = types.IntType(
        required=True,
        metadata=dict(
            description="A unique numeric identifier for the project within the system."
        ),
    )
    name = types.StringType(
        required=True, metadata=dict(description="The project's display name.")
    )
    hashed_id = types.StringType(
        required=True,
        metadata=dict(
            description=(
                "A private hashed id, uniquely identifying the project within the"
                "system. Used for playlists and RSS feeds"
            )
        ),
    )
    media_count = types.IntType(
        required=True,
        default=0,
        serialized_name="mediaCount",
        metadata=dict(
            description="The number of different medias that have been uploaded to the project."
        ),
    )
    created = types.DateTimeType(
        required=True,
        serialized_format=DATETIME_FORMAT,
        metadata=dict(description="The date that the project was originally created."),
    )
    updated = types.DateTimeType(
        required=True,
        serialized_format=DATETIME_FORMAT,
        metadata=dict(description="The date that the project was last updated"),
    )
    anonymous_can_upload = types.BooleanType(
        required=True,
        serialized_name="anonymousCanUpload",
        metadata=dict(
            description=(
                "A boolean indicating whether or not anonymous uploads are enabled for the project"
            )
        ),
    )
    anonymous_can_download = types.BooleanType(
        required=True,
        serialized_name="anonymousCanDownload",
        metadata=dict(
            description=(
                "A boolean indicating whether or not anonymous downloads are enabled for this project"
            )
        ),
    )
    public = types.BooleanType(
        required=True,
        metadata=dict(
            description=(
                "A boolean indicating whether the project is available for public (anonymous) viewing"
            )
        ),
    )
    public_id = types.StringType(
        required=False,
        serialized_name="publicId",
        metadata=dict(
            description=(
                "If the project is public, this field contains a string representing the "
                "ID used for referencing the project in public URLs"
            )
        ),
    )
    medias = types.ListType(
        types.ModelType(Media),
        required=False,  # Not present in lists of Projects
        serialize_when_none=False,
        metadata=dict(description="A list of the media associated with a project"),
    )
Пример #6
0
 class NewCurrentIntentProperty(CurrentIntentProperty):
     slots = types.ModelType(slots_property_class,
                             default=slots_property_class())
     """ :type : SlotsProperty """
Пример #7
0
 class NewLexInputEvent(cls):
     currentIntent = types.ModelType(NewCurrentIntentProperty,
                                     default=NewCurrentIntentProperty())
     """ :type : CurrentIntentProperty """
Пример #8
0
class BotProperty(BaseModel):
    name = types.StringType()
    description = types.StringType(serialize_when_none=False)
    intents = types.ListType(types.ModelType(BotIntentProperty),
                             serialize_when_none=False,
                             default=[])
    """ :type : BotIntentProperty"""
    clarificationPrompt = types.ModelType(PromptProperty,
                                          serialize_when_none=False,
                                          default=PromptProperty())
    """ :type : PromptProperty"""
    abortStatement = types.ModelType(StatmentProperty,
                                     serialize_when_none=False,
                                     default=StatmentProperty())
    """ :type : StatmentProperty"""
    idleSessionTTLInSeconds = types.IntType(serialize_when_none=False)
    voiceId = types.StringType(default='Joanna')
    checksum = types.StringType(serialize_when_none=False)
    version = types.StringType(serialize_when_none=False)
    processBehavior = types.StringType(default="BUILD")
    locale = types.StringType(default='en-US')
    childDirected = types.BooleanType()

    class IntentMeta:
        intents = []
        """ :type: list[IntentProperty] """
        existing_intents = []

    def create_all_intents(self, lambda_arn):
        for intent in self.IntentMeta.intents:
            if intent.is_lambda():
                intent.update_uri(lambda_arn)
            intent.create()

    def add_all_intents(self):
        for intent in self.get_all_intents():
            self.add_intent(intent.name, intent.version)

    def get_all_intents(self):
        all_intents = self.IntentMeta.intents + self.IntentMeta.existing_intents
        return all_intents

    def add_intent(self, name, version):
        intent = BotIntentProperty()
        intent.intentName = name
        intent.intentVersion = version
        self.intents.append(intent)
        return self

    @classmethod
    def wait_for_bot_build(cls, bot_name, version_name):
        build_status = 'BUILDING'
        response = {}
        while build_status == 'BUILDING':
            time.sleep(1)
            response = lex_model.get_bot(name=bot_name,
                                         versionOrAlias=version_name)
            logging.debug("get_bot: {}".format(pformat(response)))
            build_status = response.get('status')

        if build_status == 'FAILED' or build_status == 'NOT_BUILT':
            raise Exception(
                "Couldn't build {}. build_status: {}. failureReason: {}".
                format(bot_name, build_status, response.get('failureReason')))
        return response

    def delete_bot(self):
        raise NotImplementedError()

    @classmethod
    def get_bot_alias_checksum(cls, bot_name, alias_name):
        checksum = None
        try:
            response = lex_model.get_bot_alias(name=alias_name,
                                               botName=bot_name)
            logging.info("get_bot_alias: {}".format(pformat(response)))
            checksum = response.get('checksum')
        except ClientError as e:
            if e.response['Error']['Code'] != 'NotFoundException':
                raise

        return checksum

    @classmethod
    def get_bot_checksum(cls, bot_name, versionOrAlias):
        checksum = None
        try:
            response = lex_model.get_bot(name=bot_name,
                                         versionOrAlias=versionOrAlias)
            logging.info("get_bot: {}".format(pformat(response)))
            checksum = response.get('checksum')
        except ClientError as e:
            if e.response['Error']['Code'] != 'NotFoundException':
                raise
        return checksum

    def create_alias(self, version, alias='prod'):
        checksum = self.get_bot_alias_checksum(self.name, alias)
        kwargs = utils.get_kwargs(checksum)
        response = lex_model.put_bot_alias(name=alias,
                                           botVersion=version,
                                           botName=self.name,
                                           **kwargs)
        logging.info("put_bot_alias: {}".format(pformat(response)))

    def create(self, async=False):
        lambda_arn = self.deploy_cloudformation()
        self.create_all_intents(lambda_arn)
        self.add_all_intents()
        logging.info("Creating bot: {}".format(self.name))
        # Get the old bot checksum if available
        self.checksum = self.get_bot_checksum(self.name, '$LATEST')

        kwargs = self.to_primitive()
        # Build/Update the bot
        response = lex_model.put_bot(**kwargs)
        self.version = response.get('version')
        logging.info("put_bot: {}".format(pformat(response)))
        self.checksum = response.get('checksum')
        try:
            version_response = lex_model.create_bot_version(
                name=self.name, checksum=self.checksum)
            logging.info("create_bot_version: {}".format(pformat(response)))
            self.version = version_response.get('version')
            self.checksum = version_response.get('checksum')
        except ClientError as e:
            logging.warning("Failed to create Bot Version", exc_info=1)

        if not async:
            self.wait_for_bot_build(self.name, self.version)
            self.create_alias('$LATEST', 'dev')
            self.create_alias(self.version, 'prod')
Пример #9
0
class IntentProperty(BaseModel):
    name = types.StringType()
    description = types.StringType(serialize_when_none=False)
    slots = types.ListType(types.ModelType(IntentSlotProperty),
                           serialize_when_none=False,
                           default=[])
    """ :type : list[IntentSlotProperty] """

    sampleUtterances = types.ListType(types.StringType,
                                      serialize_when_none=False)
    """ :type : list[str] """

    confirmationPrompt = types.ModelType(PromptProperty,
                                         serialize_when_none=False)
    """ :type : PromptProperty """

    rejectionStatement = types.ModelType(StatmentProperty,
                                         serialize_when_none=False)
    """ :type : StatmentProperty """

    followUpPrompt = types.ModelType(FollowUpPromptProperty,
                                     serialize_when_none=False)
    """ :type : FollowUpPromptProperty """

    conclusionStatement = types.ModelType(StatmentProperty,
                                          serialize_when_none=False)
    """ :type : StatmentProperty """

    dialogCodeHook = types.ModelType(CodeHookProperty,
                                     serialize_when_none=False)
    """ :type : CodeHookProperty """

    fulfillmentActivity = types.ModelType(FulfilmentActivityProperty,
                                          serialize_when_none=False,
                                          default=FulfilmentActivityProperty())
    """ :type : FulfilmentActivityProperty """
    parentIntentSignature = types.StringType(serialize_when_none=False)
    checksum = types.StringType(serialize_when_none=False)

    def add_slot(self, slot_prop):
        self.slots.append(slot_prop)

    def add_utterance(self, utterance):
        self.sampleUtterances = self.sampleUtterances + [utterance]
        return self

    def get_intent_checksum(self, version='$LATEST'):
        checksum = None
        try:
            response = lex_model.get_intent(name=self.name, version=version)
            logging.info("get_intent: {}".format(pformat(response)))
            checksum = response.get('checksum')
        except ClientError as e:
            if e.response['Error']['Code'] != 'NotFoundException':
                raise

        return checksum

    def create_slots(self):
        for slot in self.slots:
            slot.create()

    def create(self):
        logging.info("Creating intent: {}".format(self.name))
        self.create_slots()
        # Create the intent and get the old checksum if it exists
        self.checksum = self.get_intent_checksum()
        kwargs = self.to_primitive()
        # Put the new/updated intent
        response = lex_model.put_intent(**kwargs)
        logging.info("put_intent: {}".format(pformat(response)))

        self.checksum = response.get('checksum')
        try:
            version_response = lex_model.create_intent_version(
                name=self.name, checksum=self.checksum)
            logging.info("create_intent_version: {}".format(
                pformat(version_response)))
            self.version = version_response.get('version')
            self.checksum = version_response.get('checksum')
        except ClientError as e:
            logging.warning('Failed to create new intent version ', exc_info=1)
        return self
Пример #10
0
class FollowUpPromptProperty(BaseModel):
    prompt = types.ModelType(PromptProperty, serialize_when_none=False)
    """ :type : PromptProperty """
    rejectionStatement = types.ModelType(StatmentProperty,
                                         serialize_when_none=False)
    """ :type : RejectionStatmentProperty """
Пример #11
0
 def decorator(model):
     return types.ModelType(model, **kwargs)
Пример #12
0
class WeatherStats(Model):
    last_report = types.ModelType(WeatherReport)
    prev_reports = types.ListType(types.ModelType(WeatherReport))
    date_list = types.ListType(types.DateTimeType())